@malloydata/render 0.0.144-dev240426181908 → 0.0.144-dev240503150037
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
CHANGED
|
@@ -4703,42 +4703,43 @@ let Yv = class extends NV {
|
|
|
4703
4703
|
], x = f.length > 0 ? `PARTITION BY ${f.join(", ")}` : "";
|
|
4704
4704
|
let h = a ?? "";
|
|
4705
4705
|
if (!a && i.needsWindowOrderBy) {
|
|
4706
|
-
const
|
|
4707
|
-
let
|
|
4708
|
-
const
|
|
4709
|
-
for (const
|
|
4710
|
-
typeof
|
|
4711
|
-
name:
|
|
4712
|
-
fif: e.getField(
|
|
4713
|
-
} :
|
|
4714
|
-
const
|
|
4715
|
-
if (!(0, Ue.expressionIsAnalytic)(
|
|
4706
|
+
const y = [];
|
|
4707
|
+
let E;
|
|
4708
|
+
const A = e.firstSegment.orderBy || e.calculateDefaultOrderBy();
|
|
4709
|
+
for (const v of A) {
|
|
4710
|
+
typeof v.field == "string" ? E = {
|
|
4711
|
+
name: v.field,
|
|
4712
|
+
fif: e.getField(v.field)
|
|
4713
|
+
} : E = e.getFieldByNumber(v.field);
|
|
4714
|
+
const S = E.fif.f.fieldDef.expressionType;
|
|
4715
|
+
if (!(0, Ue.expressionIsAnalytic)(S))
|
|
4716
4716
|
if (e.firstSegment.type === "reduce") {
|
|
4717
|
-
const
|
|
4718
|
-
|
|
4717
|
+
const C = E.fif.getAnalyticalSQL(!1);
|
|
4718
|
+
y.push(` ${C} ${v.dir || "ASC"}`);
|
|
4719
4719
|
} else
|
|
4720
|
-
e.firstSegment.type === "project" &&
|
|
4720
|
+
e.firstSegment.type === "project" && y.push(` ${E.fif.f.generateExpression(e)} ${v.dir || "ASC"}`);
|
|
4721
4721
|
}
|
|
4722
|
-
|
|
4722
|
+
y.length > 0 && (h = " " + this.parent.dialect.sqlOrderBy(y));
|
|
4723
4723
|
}
|
|
4724
4724
|
let p = "";
|
|
4725
4725
|
if (i.between) {
|
|
4726
|
-
const [
|
|
4726
|
+
const [y, E] = [
|
|
4727
4727
|
i.between.preceding,
|
|
4728
4728
|
i.between.following
|
|
4729
|
-
].map((
|
|
4730
|
-
if (
|
|
4729
|
+
].map((A) => {
|
|
4730
|
+
if (A === -1)
|
|
4731
4731
|
return "UNBOUNDED";
|
|
4732
|
-
if (typeof
|
|
4733
|
-
return
|
|
4734
|
-
const
|
|
4735
|
-
if (
|
|
4732
|
+
if (typeof A == "number")
|
|
4733
|
+
return A;
|
|
4734
|
+
const v = i.params.findIndex((C) => C.name === A), S = o[v];
|
|
4735
|
+
if (S.length !== 1 || typeof S[0] == "string" || S[0].type !== "dialect" || S[0].function !== "numberLiteral")
|
|
4736
4736
|
throw new Error("Invalid number of rows for window spec");
|
|
4737
|
-
return
|
|
4737
|
+
return S[0].literal;
|
|
4738
4738
|
});
|
|
4739
|
-
p = `ROWS BETWEEN ${
|
|
4739
|
+
p = `ROWS BETWEEN ${y} PRECEDING AND ${E} FOLLOWING`;
|
|
4740
4740
|
}
|
|
4741
|
-
|
|
4741
|
+
let g = `${this.generateExpressionFromExpr(e, n, r, s)} OVER(${x} ${h} ${p})`;
|
|
4742
|
+
return l && (g = `CASE WHEN group_set=${e.groupSet} THEN ${g} END`), g;
|
|
4742
4743
|
}
|
|
4743
4744
|
generateExpressionFromExpr(e, n, r, i = new pm()) {
|
|
4744
4745
|
let s = "";
|
package/dist/module/index.umd.js
CHANGED
|
@@ -286,7 +286,7 @@ ${(0,Or.indent)(o)})
|
|
|
286
286
|
`),r=this.pdts.join(`
|
|
287
287
|
`),i=this.combineStages(!1).sql;return n+r+i+this.withs[e]}generateCoorelatedSubQuery(e,n){return this.useCTE?this.combineStages(!0).sql+e.sqlCreateFunctionCombineLastStage(this.getName(this.withs.length-1),pp(n)):e.sqlCreateFunctionCombineLastStage(`(${this.withs[0]})`,pp(n))}}class mp{constructor(){this.totalGroupSet=-1}withWhere(e){const n=new mp;return n.whereSQL=e,n.applyValue=this.applyValue,n.totalGroupSet=this.totalGroupSet,n}withApply(e){const n=new mp;return n.whereSQL=this.whereSQL,n.applyValue=e,n.totalGroupSet=this.totalGroupSet,n}withTotal(e){const n=new mp;return n.whereSQL=this.whereSQL,n.applyValue=this.applyValue,n.totalGroupSet=e,n}}class qM{constructor(e){this.fieldDef=e}getIdentifier(){return(0,Ue.getIdentifier)(this.fieldDef)}getChildByName(e){}}let Nv=class extends qM{constructor(e,n){super(e),this.parent=n,this.fieldDef=e}uniqueKeyPossibleUse(){}getJoinableParent(){const e=this.parent;if(e.fieldDef.structRelationship.type==="inline"){if(e)return e.getJoinableParent();throw new Error("Internal Error: inline struct cannot be root")}return e}caseGroup(e,n){return e.length===0?n:`CASE WHEN group_set${e.length===1?`=${e[0]}`:` IN (${e.join(",")})`} THEN
|
|
288
288
|
${n}
|
|
289
|
-
END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,n,r,i){const s=n.getFieldByName(r.path);return(0,Ue.hasExpression)(s.fieldDef)?`(${this.generateExpressionFromExpr(e,s.parent,s.fieldDef.e,i)})`:s.generateExpression(e)}generateOutputFieldFragment(e,n,r,i){return`(${e.getField(r.name).getAnalyticalSQL(!1)})`}generateSQLExpression(e,n,r,i){return this.generateExpressionFromExpr(e,n,r.e,i)}getParameterMap(e,n){return new Map(e.params.map((r,i)=>{const s=r.isVariadic?(0,Or.range)(i,n):[i];return[r.name,{param:r,argIndexes:s}]}))}expandFunctionCall(e,n,r,i,s){const o=this.getParameterMap(n,r.length);if(n.dialect[e]===void 0)throw new Error(`Function is not defined for dialect ${e}`);return(0,Or.exprMap)(n.dialect[e].e,u=>{var a,l;if(typeof u=="string")return[u];if(u.type==="spread"){const c=u.e[0];if(u.e.length!==1||typeof c=="string"||c.type!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const f=o.get(c.name);return f===void 0?[u]:(0,Or.joinWith)(f.argIndexes.map(x=>r[x]),",")}else if(u.type==="function_parameter"){const c=o.get(u.name);return c===void 0?[u]:c.param.isVariadic?["[",...(0,Or.joinWith)(c.argIndexes.map(x=>r[x]),","),"]"]:r[c.argIndexes[0]]}else{if(u.type==="aggregate_order_by")return i?[` ${(a=u.prefix)!==null&&a!==void 0?a:""}${i}${(l=u.suffix)!==null&&l!==void 0?l:""}`]:[];if(u.type==="aggregate_limit")return s?[` ${s}`]:[]}return[u]})}getFunctionOrderBy(e,n,r,i,s,o){if(i.length!==0)return"ORDER BY "+i.map(u=>{var a,l;const c=(a=o.dialect[n.dialect.name].defaultOrderByArgIndex)!==null&&a!==void 0?a:0,f=(l=u.e)!==null&&l!==void 0?l:s[c],x=this.generateDimFragment(e,n,f,r),h=u.dir==="asc"?" ASC":u.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,n,r,i,s,o,u,a){if(o)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${u}`);const l=this.generateDimFragment(e,n,r,a),c=i?this.generateDimFragment(e,n,i,a):"";return this.parent.dialect.sqlStringAggDistinct(s,l,c)}getParamForArgIndex(e,n){const r=e.slice(0,n).find(i=>i.isVariadic);return r??e[n]}generateFunctionCallExpression(e,n,r,i){var s,o,u;const a=r.overload,l=r.args,c=(s=r.overload.isSymmetric)!==null&&s!==void 0?s:!1,f=(0,Ue.expressionIsAggregate)(a.returnType.expressionType)&&!c&&this.generateDistinctKeyIfNecessary(e,n,r.structPath),x=r.limit?`LIMIT ${r.limit}`:void 0;if(r.name==="string_agg"&&f&&!n.dialect.supportsAggDistinct&&n.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,n,l[0],l[1],f,r.orderBy,n.dialect.name,i);if(f){if(!n.dialect.supportsAggDistinct)throw new Error(`Function \`${r.name}\` does not support fanning out in ${n.dialect.name}`);const h=l.map(g=>this.generateDimFragment(e,n,g,i)),p=(o=r.orderBy)!==null&&o!==void 0?o:[],m=p.map(g=>{var y,E;const A=(y=a.dialect[n.dialect.name].defaultOrderByArgIndex)!==null&&y!==void 0?y:0,v=(E=g.e)!==null&&E!==void 0?E:l[A];return this.generateDimFragment(e,n,v,i)});return n.dialect.sqlAggDistinct(f,[...h,...m],g=>{const y=g.map((C,_)=>_<l.length&&this.getParamForArgIndex(a.params,_).allowedTypes.every(R=>(0,Ue.isLiteral)(R.evalSpace))?l[_]:[C]),E=y.slice(0,h.length),A=y.slice(h.length).map((C,_)=>({e:C,dir:p[_].dir})),v=this.getFunctionOrderBy(e,n,i,A,E,a),S=this.expandFunctionCall(n.dialect.name,a,E,v,x);return this.generateExpressionFromExpr(e,n,S,i)})}else{const h=(0,Ue.expressionIsAggregate)(a.returnType.expressionType)?l.map((g,y)=>this.getParamForArgIndex(a.params,y).allowedTypes.every(A=>(0,Ue.isLiteral)(A.evalSpace))?g:[this.generateDimFragment(e,n,g,i)]):l,p=r.orderBy?this.getFunctionOrderBy(e,n,i,r.orderBy,l,a):"",m=this.expandFunctionCall(n.dialect.name,a,h,p,x);if((0,Ue.expressionIsAnalytic)(a.returnType.expressionType)){const g=((u=r.partitionBy)!==null&&u!==void 0?u:[]).map(y=>`(${e.getField(y).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(e,n,m,a,i,l,g,p)}return this.generateExpressionFromExpr(e,n,m,i)}}generateSpread(e,n,r,i){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,n,r,i){throw new Error(`Can't generate SQL, no value for ${r.path}`)}generateFilterFragment(e,n,r,i){const s=new Or.AndChain(i.whereSQL);for(const o of r.filterList)s.add(this.generateExpressionFromExpr(e,n,o.expression,i.withWhere()));return this.generateExpressionFromExpr(e,n,r.e,i.withWhere(s.sql()))}generateDimFragment(e,n,r,i){let s=this.generateExpressionFromExpr(e,n,r,i);return i.whereSQL&&(s=`CASE WHEN ${i.whereSQL} THEN ${s} END`),s}generateUngroupedFragment(e,n,r,i){if(i.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let s,o;if(r.fields&&r.fields.length>0){const f=r.fields.sort().join("|")+r.type;if(o=e.ungroupedSets.get(f),o===void 0)throw new Error(`Internal Error, cannot find groupset with key ${f}`);s=o.groupSet}else s=e.parent?e.parent.groupSet:0;const u=this.generateExpressionFromExpr(e,n,r.e,i.withTotal(s)),a=e.getUngroupPartitions(o);let l="";const c=a.map(f=>f.getAnalyticalSQL(!0)).join(", ");return c.length>0&&(l=`PARTITION BY ${c}`),`MAX(${u}) OVER (${l})`}generateDistinctKeyIfNecessary(e,n,r){let i=n;if(r&&(i=this.parent.root().getStructByName(r)),i.needsSymetricCalculation(e))return i.getDistinctKey().generateExpression(e)}generateSumFragment(e,n,r,i){const s=this.generateDimFragment(e,n,r.e,i),o=this.generateDistinctKeyIfNecessary(e,n,r.structPath);let u;return o?this.parent.dialect.supportsSumDistinctFunction?u=this.parent.dialect.sqlSumDistinct(o,s,"SUM"):u=QM(this.parent.dialect,s,o):u=`SUM(${s})`,`COALESCE(${u},0)`}generateSymmetricFragment(e,n,r,i){const s=this.generateDimFragment(e,n,r.e,i);return`${r.function==="count_distinct"?"count(distinct ":r.function+"("}${s})`}generateAvgFragment(e,n,r,i){const s=this.generateDimFragment(e,n,r.e,i),o=this.generateDistinctKeyIfNecessary(e,n,r.structPath);if(o){let u=o;i.whereSQL&&(u=`CASE WHEN ${i.whereSQL} THEN ${o} END`);let a,l;return this.parent.dialect.supportsSumDistinctFunction?l=this.parent.dialect.sqlSumDistinct(o,s,"AVG"):(a=QM(this.parent.dialect,s,o),l=`(${a})/NULLIF(COUNT(DISTINCT CASE WHEN ${s} IS NOT NULL THEN ${u} END),0)`),l}else return`AVG(${s})`}generateCountFragment(e,n,r,i){let s="COUNT(",o="1",u=n;r.structPath&&(u=this.parent.root().getStructByName(r.structPath));const a=u.getJoinableParent().getIdentifier(),l=e.root().joins.get(a);if(!l)throw new Error(`Join ${a} not found in result set`);return(!l.leafiest||l.makeUniqueKey)&&(s="COUNT(DISTINCT ",o=u.getDistinctKey().generateExpression(e)),i.whereSQL?`${s}CASE WHEN ${i.whereSQL} THEN ${o} END)`:`${s}${o})`}generateDialect(e,n,r,i){return this.generateExpressionFromExpr(e,n,n.dialect.dialectExpr(e.getQueryInfo(),r),i)}generateSqlString(e,n,r,i){return r.e.map(s=>typeof s=="string"?s:this.generateExpressionFromExpr(e,n,[s],i)).join("")}generateSourceReference(e,n,r){return r.path===void 0?n.getSQLIdentifier():n.getFieldByName(r.path).getIdentifier()}getAnalyticPartitions(e,n){const r=[];let i=e.parent;for(;i!==void 0;){const o=i.fields(u=>Nr(u.f)&&u.fieldUsage.type==="result").map(u=>u.getAnalyticalSQL(!0));r.push(...o),i=i.parent}return n&&r.push(...n),r}generateAnalyticFragment(e,n,r,i,s,o,u,a){const l=e.root().isComplexQuery,c=this.getAnalyticPartitions(e,u),f=[...l?["group_set"]:[],...c],x=f.length>0?`PARTITION BY ${f.join(", ")}`:"";let h=a??"";if(!a&&i.needsWindowOrderBy){const g=[];let y;const E=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const A of E){typeof A.field=="string"?y={name:A.field,fif:e.getField(A.field)}:y=e.getFieldByNumber(A.field);const v=y.fif.f.fieldDef.expressionType;if(!(0,Ue.expressionIsAnalytic)(v))if(e.firstSegment.type==="reduce"){const S=y.fif.getAnalyticalSQL(!1);g.push(` ${S} ${A.dir||"ASC"}`)}else e.firstSegment.type==="project"&&g.push(` ${y.fif.f.generateExpression(e)} ${A.dir||"ASC"}`)}g.length>0&&(h=" "+this.parent.dialect.sqlOrderBy(g))}let p="";if(i.between){const[g,y]=[i.between.preceding,i.between.following].map(E=>{if(E===-1)return"UNBOUNDED";if(typeof E=="number")return E;const A=i.params.findIndex(S=>S.name===E),v=o[A];if(v.length!==1||typeof v[0]=="string"||v[0].type!=="dialect"||v[0].function!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return v[0].literal});p=`ROWS BETWEEN ${g} PRECEDING AND ${y} FOLLOWING`}return`${this.generateExpressionFromExpr(e,n,r,s)} OVER(${x} ${h} ${p})`}generateExpressionFromExpr(e,n,r,i=new mp){let s="";for(const o of r)if(typeof o=="string")s+=o;else if((0,Ue.isFieldFragment)(o))s+=this.generateFieldFragment(e,n,o,i);else if((0,Ue.isParameterFragment)(o))s+=this.generateParameterFragment(e,n,o,i);else if((0,Ue.isFilterFragment)(o))s+=this.generateFilterFragment(e,n,o,i);else if((0,Ue.isUngroupFragment)(o))s+=this.generateUngroupedFragment(e,n,o,i);else if((0,Ue.isAggregateFragment)(o)){let u;if(o.function==="sum")u=this.generateSumFragment(e,n,o,i);else if(o.function==="avg")u=this.generateAvgFragment(e,n,o,i);else if(o.function==="count")u=this.generateCountFragment(e,n,o,i);else if(["count_distinct","min","max"].includes(o.function))u=this.generateSymmetricFragment(e,n,o,i);else throw new Error(`Internal Error: Unknown aggregate function ${o.function}`);if(e.root().isComplexQuery){let a=e.groupSet;i.totalGroupSet!==-1&&(a=i.totalGroupSet),s+=this.caseGroup([a],u)}else s+=u}else if((0,Ue.isApplyFragment)(o)){const u=this.generateExpressionFromExpr(e,n,o.value,i);s+=this.generateExpressionFromExpr(e,n,o.to,i.withApply(u))}else if((0,Ue.isApplyValue)(o))if(i.applyValue)s+=i.applyValue;else throw new Error("Internal Error: Partial application value referenced but not provided");else{if((0,Ue.isFunctionParameterFragment)(o))throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");if((0,Ue.isOutputFieldFragment)(o))s+=this.generateOutputFieldFragment(e,n,o,i);else if((0,Ue.isSQLExpressionFragment)(o))s+=this.generateSQLExpression(e,n,o,i);else if((0,Ue.isFunctionCallFragment)(o))s+=this.generateFunctionCallExpression(e,n,o,i);else if((0,Ue.isSpreadFragment)(o))s+=this.generateSpread(e,n,o,i);else if(o.type==="dialect")s+=this.generateDialect(e,n,o,i);else if(o.type==="sql-string")s+=this.generateSqlString(e,n,o,i);else if(o.type==="source-reference")s+=this.generateSourceReference(e,n,o);else throw new Error(`Internal Error: Unknown expression fragment ${JSON.stringify(o,void 0,2)}`)}return s}getExpr(){return(0,Ue.hasExpression)(this.fieldDef)?this.fieldDef.e:[this.parent.dialect.sqlFieldReference(this.parent.getSQLIdentifier(),this.fieldDef.name,this.fieldDef.type,this.parent.fieldDef.structSource.type==="nested"||this.parent.fieldDef.structSource.type==="inline"||this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested",this.parent.fieldDef.structRelationship.type==="nested"&&this.parent.fieldDef.structRelationship.isArray)]}generateExpression(e){return this.generateExpressionFromExpr(e,this.parent,this.getExpr())}};function Dv(t){return t instanceof Hr&&t.isCalculated()}function HM(t){return t instanceof Hr&&t.isAggregate()}function Nr(t){return t instanceof Hr&&!t.isCalculated()&&!t.isAggregate()}class Hr extends Nv{includeInWildcard(){return!0}isCalculated(){return(0,Ue.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,Ue.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,Ue.hasExpression)(this.fieldDef)}}class A1e extends Hr{}class v1e extends Hr{}class _O extends Hr{}class S1e extends Hr{}class _1e extends Hr{}class C1e extends Hr{constructor(e,n,r){super(e,n),this.primaryKey=r}getName(){return(0,Ue.getIdentifier)(this.fieldDef)}getAsJoinedStructDef(e){return{...this.parent.fieldDef,structRelationship:{type:"one",matrixOperation:"left",onExpression:[{type:"field",path:[this.primaryKey]},"=",{type:"field",path:[e]}]}}}}class CO extends Hr{generateExpression(e){const n=this.fieldDef;if(n.timeframe){const r=this.parent.dialect.sqlTrunc(e.getQueryInfo(),{value:this.getExpr(),valueType:"date"},n.timeframe);return this.generateExpressionFromExpr(e,this.parent,r)}else return super.generateExpression(e)}getChildByName(e){const n={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new CO(n,this.parent)}}class bO extends Hr{getChildByName(e){const n={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new bO(n,this.parent)}}class b1e extends Hr{generateExpression(e){var n;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.fieldDef.structSource.type==="nested"){const r=(n=this.parent.parent)===null||n===void 0?void 0:n.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(r||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"__row_id","string",!0,!1))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"__distinct_key","string",this.parent.fieldDef.structRelationship.type==="nested",!1)}includeInWildcard(){return!1}}const zM=9;function QM(t,e,n){const i=t.sqlSumDistinctHashedKey(n),s=10**(9-zM);let u=`(${`
|
|
289
|
+
END`}getFullOutputName(){return this.parent.getFullOutputName()+this.getIdentifier()}generateFieldFragment(e,n,r,i){const s=n.getFieldByName(r.path);return(0,Ue.hasExpression)(s.fieldDef)?`(${this.generateExpressionFromExpr(e,s.parent,s.fieldDef.e,i)})`:s.generateExpression(e)}generateOutputFieldFragment(e,n,r,i){return`(${e.getField(r.name).getAnalyticalSQL(!1)})`}generateSQLExpression(e,n,r,i){return this.generateExpressionFromExpr(e,n,r.e,i)}getParameterMap(e,n){return new Map(e.params.map((r,i)=>{const s=r.isVariadic?(0,Or.range)(i,n):[i];return[r.name,{param:r,argIndexes:s}]}))}expandFunctionCall(e,n,r,i,s){const o=this.getParameterMap(n,r.length);if(n.dialect[e]===void 0)throw new Error(`Function is not defined for dialect ${e}`);return(0,Or.exprMap)(n.dialect[e].e,u=>{var a,l;if(typeof u=="string")return[u];if(u.type==="spread"){const c=u.e[0];if(u.e.length!==1||typeof c=="string"||c.type!=="function_parameter")throw new Error("Invalid function definition. Argument to spread must be a function parameter.");const f=o.get(c.name);return f===void 0?[u]:(0,Or.joinWith)(f.argIndexes.map(x=>r[x]),",")}else if(u.type==="function_parameter"){const c=o.get(u.name);return c===void 0?[u]:c.param.isVariadic?["[",...(0,Or.joinWith)(c.argIndexes.map(x=>r[x]),","),"]"]:r[c.argIndexes[0]]}else{if(u.type==="aggregate_order_by")return i?[` ${(a=u.prefix)!==null&&a!==void 0?a:""}${i}${(l=u.suffix)!==null&&l!==void 0?l:""}`]:[];if(u.type==="aggregate_limit")return s?[` ${s}`]:[]}return[u]})}getFunctionOrderBy(e,n,r,i,s,o){if(i.length!==0)return"ORDER BY "+i.map(u=>{var a,l;const c=(a=o.dialect[n.dialect.name].defaultOrderByArgIndex)!==null&&a!==void 0?a:0,f=(l=u.e)!==null&&l!==void 0?l:s[c],x=this.generateDimFragment(e,n,f,r),h=u.dir==="asc"?" ASC":u.dir==="desc"?" DESC":"";return`${x}${h}`}).join(", ")}generateAsymmetricStringAggExpression(e,n,r,i,s,o,u,a){if(o)throw new Error(`Function \`string_agg\` does not support fanning out with an order by in ${u}`);const l=this.generateDimFragment(e,n,r,a),c=i?this.generateDimFragment(e,n,i,a):"";return this.parent.dialect.sqlStringAggDistinct(s,l,c)}getParamForArgIndex(e,n){const r=e.slice(0,n).find(i=>i.isVariadic);return r??e[n]}generateFunctionCallExpression(e,n,r,i){var s,o,u;const a=r.overload,l=r.args,c=(s=r.overload.isSymmetric)!==null&&s!==void 0?s:!1,f=(0,Ue.expressionIsAggregate)(a.returnType.expressionType)&&!c&&this.generateDistinctKeyIfNecessary(e,n,r.structPath),x=r.limit?`LIMIT ${r.limit}`:void 0;if(r.name==="string_agg"&&f&&!n.dialect.supportsAggDistinct&&n.dialect.name!=="snowflake")return this.generateAsymmetricStringAggExpression(e,n,l[0],l[1],f,r.orderBy,n.dialect.name,i);if(f){if(!n.dialect.supportsAggDistinct)throw new Error(`Function \`${r.name}\` does not support fanning out in ${n.dialect.name}`);const h=l.map(g=>this.generateDimFragment(e,n,g,i)),p=(o=r.orderBy)!==null&&o!==void 0?o:[],m=p.map(g=>{var y,E;const A=(y=a.dialect[n.dialect.name].defaultOrderByArgIndex)!==null&&y!==void 0?y:0,v=(E=g.e)!==null&&E!==void 0?E:l[A];return this.generateDimFragment(e,n,v,i)});return n.dialect.sqlAggDistinct(f,[...h,...m],g=>{const y=g.map((C,_)=>_<l.length&&this.getParamForArgIndex(a.params,_).allowedTypes.every(R=>(0,Ue.isLiteral)(R.evalSpace))?l[_]:[C]),E=y.slice(0,h.length),A=y.slice(h.length).map((C,_)=>({e:C,dir:p[_].dir})),v=this.getFunctionOrderBy(e,n,i,A,E,a),S=this.expandFunctionCall(n.dialect.name,a,E,v,x);return this.generateExpressionFromExpr(e,n,S,i)})}else{const h=(0,Ue.expressionIsAggregate)(a.returnType.expressionType)?l.map((g,y)=>this.getParamForArgIndex(a.params,y).allowedTypes.every(A=>(0,Ue.isLiteral)(A.evalSpace))?g:[this.generateDimFragment(e,n,g,i)]):l,p=r.orderBy?this.getFunctionOrderBy(e,n,i,r.orderBy,l,a):"",m=this.expandFunctionCall(n.dialect.name,a,h,p,x);if((0,Ue.expressionIsAnalytic)(a.returnType.expressionType)){const g=((u=r.partitionBy)!==null&&u!==void 0?u:[]).map(y=>`(${e.getField(y).getAnalyticalSQL(!1)})`);return this.generateAnalyticFragment(e,n,m,a,i,l,g,p)}return this.generateExpressionFromExpr(e,n,m,i)}}generateSpread(e,n,r,i){throw new Error("Unexpanded spread encountered during SQL generation")}generateParameterFragment(e,n,r,i){throw new Error(`Can't generate SQL, no value for ${r.path}`)}generateFilterFragment(e,n,r,i){const s=new Or.AndChain(i.whereSQL);for(const o of r.filterList)s.add(this.generateExpressionFromExpr(e,n,o.expression,i.withWhere()));return this.generateExpressionFromExpr(e,n,r.e,i.withWhere(s.sql()))}generateDimFragment(e,n,r,i){let s=this.generateExpressionFromExpr(e,n,r,i);return i.whereSQL&&(s=`CASE WHEN ${i.whereSQL} THEN ${s} END`),s}generateUngroupedFragment(e,n,r,i){if(i.totalGroupSet!==-1)throw new Error("Already in ALL. Cannot nest within an all calcuation.");let s,o;if(r.fields&&r.fields.length>0){const f=r.fields.sort().join("|")+r.type;if(o=e.ungroupedSets.get(f),o===void 0)throw new Error(`Internal Error, cannot find groupset with key ${f}`);s=o.groupSet}else s=e.parent?e.parent.groupSet:0;const u=this.generateExpressionFromExpr(e,n,r.e,i.withTotal(s)),a=e.getUngroupPartitions(o);let l="";const c=a.map(f=>f.getAnalyticalSQL(!0)).join(", ");return c.length>0&&(l=`PARTITION BY ${c}`),`MAX(${u}) OVER (${l})`}generateDistinctKeyIfNecessary(e,n,r){let i=n;if(r&&(i=this.parent.root().getStructByName(r)),i.needsSymetricCalculation(e))return i.getDistinctKey().generateExpression(e)}generateSumFragment(e,n,r,i){const s=this.generateDimFragment(e,n,r.e,i),o=this.generateDistinctKeyIfNecessary(e,n,r.structPath);let u;return o?this.parent.dialect.supportsSumDistinctFunction?u=this.parent.dialect.sqlSumDistinct(o,s,"SUM"):u=QM(this.parent.dialect,s,o):u=`SUM(${s})`,`COALESCE(${u},0)`}generateSymmetricFragment(e,n,r,i){const s=this.generateDimFragment(e,n,r.e,i);return`${r.function==="count_distinct"?"count(distinct ":r.function+"("}${s})`}generateAvgFragment(e,n,r,i){const s=this.generateDimFragment(e,n,r.e,i),o=this.generateDistinctKeyIfNecessary(e,n,r.structPath);if(o){let u=o;i.whereSQL&&(u=`CASE WHEN ${i.whereSQL} THEN ${o} END`);let a,l;return this.parent.dialect.supportsSumDistinctFunction?l=this.parent.dialect.sqlSumDistinct(o,s,"AVG"):(a=QM(this.parent.dialect,s,o),l=`(${a})/NULLIF(COUNT(DISTINCT CASE WHEN ${s} IS NOT NULL THEN ${u} END),0)`),l}else return`AVG(${s})`}generateCountFragment(e,n,r,i){let s="COUNT(",o="1",u=n;r.structPath&&(u=this.parent.root().getStructByName(r.structPath));const a=u.getJoinableParent().getIdentifier(),l=e.root().joins.get(a);if(!l)throw new Error(`Join ${a} not found in result set`);return(!l.leafiest||l.makeUniqueKey)&&(s="COUNT(DISTINCT ",o=u.getDistinctKey().generateExpression(e)),i.whereSQL?`${s}CASE WHEN ${i.whereSQL} THEN ${o} END)`:`${s}${o})`}generateDialect(e,n,r,i){return this.generateExpressionFromExpr(e,n,n.dialect.dialectExpr(e.getQueryInfo(),r),i)}generateSqlString(e,n,r,i){return r.e.map(s=>typeof s=="string"?s:this.generateExpressionFromExpr(e,n,[s],i)).join("")}generateSourceReference(e,n,r){return r.path===void 0?n.getSQLIdentifier():n.getFieldByName(r.path).getIdentifier()}getAnalyticPartitions(e,n){const r=[];let i=e.parent;for(;i!==void 0;){const o=i.fields(u=>Nr(u.f)&&u.fieldUsage.type==="result").map(u=>u.getAnalyticalSQL(!0));r.push(...o),i=i.parent}return n&&r.push(...n),r}generateAnalyticFragment(e,n,r,i,s,o,u,a){const l=e.root().isComplexQuery,c=this.getAnalyticPartitions(e,u),f=[...l?["group_set"]:[],...c],x=f.length>0?`PARTITION BY ${f.join(", ")}`:"";let h=a??"";if(!a&&i.needsWindowOrderBy){const y=[];let E;const A=e.firstSegment.orderBy||e.calculateDefaultOrderBy();for(const v of A){typeof v.field=="string"?E={name:v.field,fif:e.getField(v.field)}:E=e.getFieldByNumber(v.field);const S=E.fif.f.fieldDef.expressionType;if(!(0,Ue.expressionIsAnalytic)(S))if(e.firstSegment.type==="reduce"){const C=E.fif.getAnalyticalSQL(!1);y.push(` ${C} ${v.dir||"ASC"}`)}else e.firstSegment.type==="project"&&y.push(` ${E.fif.f.generateExpression(e)} ${v.dir||"ASC"}`)}y.length>0&&(h=" "+this.parent.dialect.sqlOrderBy(y))}let p="";if(i.between){const[y,E]=[i.between.preceding,i.between.following].map(A=>{if(A===-1)return"UNBOUNDED";if(typeof A=="number")return A;const v=i.params.findIndex(C=>C.name===A),S=o[v];if(S.length!==1||typeof S[0]=="string"||S[0].type!=="dialect"||S[0].function!=="numberLiteral")throw new Error("Invalid number of rows for window spec");return S[0].literal});p=`ROWS BETWEEN ${y} PRECEDING AND ${E} FOLLOWING`}let g=`${this.generateExpressionFromExpr(e,n,r,s)} OVER(${x} ${h} ${p})`;return l&&(g=`CASE WHEN group_set=${e.groupSet} THEN ${g} END`),g}generateExpressionFromExpr(e,n,r,i=new mp){let s="";for(const o of r)if(typeof o=="string")s+=o;else if((0,Ue.isFieldFragment)(o))s+=this.generateFieldFragment(e,n,o,i);else if((0,Ue.isParameterFragment)(o))s+=this.generateParameterFragment(e,n,o,i);else if((0,Ue.isFilterFragment)(o))s+=this.generateFilterFragment(e,n,o,i);else if((0,Ue.isUngroupFragment)(o))s+=this.generateUngroupedFragment(e,n,o,i);else if((0,Ue.isAggregateFragment)(o)){let u;if(o.function==="sum")u=this.generateSumFragment(e,n,o,i);else if(o.function==="avg")u=this.generateAvgFragment(e,n,o,i);else if(o.function==="count")u=this.generateCountFragment(e,n,o,i);else if(["count_distinct","min","max"].includes(o.function))u=this.generateSymmetricFragment(e,n,o,i);else throw new Error(`Internal Error: Unknown aggregate function ${o.function}`);if(e.root().isComplexQuery){let a=e.groupSet;i.totalGroupSet!==-1&&(a=i.totalGroupSet),s+=this.caseGroup([a],u)}else s+=u}else if((0,Ue.isApplyFragment)(o)){const u=this.generateExpressionFromExpr(e,n,o.value,i);s+=this.generateExpressionFromExpr(e,n,o.to,i.withApply(u))}else if((0,Ue.isApplyValue)(o))if(i.applyValue)s+=i.applyValue;else throw new Error("Internal Error: Partial application value referenced but not provided");else{if((0,Ue.isFunctionParameterFragment)(o))throw new Error("Internal Error: Function parameter fragment remaining during SQL generation");if((0,Ue.isOutputFieldFragment)(o))s+=this.generateOutputFieldFragment(e,n,o,i);else if((0,Ue.isSQLExpressionFragment)(o))s+=this.generateSQLExpression(e,n,o,i);else if((0,Ue.isFunctionCallFragment)(o))s+=this.generateFunctionCallExpression(e,n,o,i);else if((0,Ue.isSpreadFragment)(o))s+=this.generateSpread(e,n,o,i);else if(o.type==="dialect")s+=this.generateDialect(e,n,o,i);else if(o.type==="sql-string")s+=this.generateSqlString(e,n,o,i);else if(o.type==="source-reference")s+=this.generateSourceReference(e,n,o);else throw new Error(`Internal Error: Unknown expression fragment ${JSON.stringify(o,void 0,2)}`)}return s}getExpr(){return(0,Ue.hasExpression)(this.fieldDef)?this.fieldDef.e:[this.parent.dialect.sqlFieldReference(this.parent.getSQLIdentifier(),this.fieldDef.name,this.fieldDef.type,this.parent.fieldDef.structSource.type==="nested"||this.parent.fieldDef.structSource.type==="inline"||this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested",this.parent.fieldDef.structRelationship.type==="nested"&&this.parent.fieldDef.structRelationship.isArray)]}generateExpression(e){return this.generateExpressionFromExpr(e,this.parent,this.getExpr())}};function Dv(t){return t instanceof Hr&&t.isCalculated()}function HM(t){return t instanceof Hr&&t.isAggregate()}function Nr(t){return t instanceof Hr&&!t.isCalculated()&&!t.isAggregate()}class Hr extends Nv{includeInWildcard(){return!0}isCalculated(){return(0,Ue.expressionIsCalculation)(this.fieldDef.expressionType)}isAggregate(){return(0,Ue.expressionIsAggregate)(this.fieldDef.expressionType)}getFilterList(){return[]}hasExpression(){return(0,Ue.hasExpression)(this.fieldDef)}}class A1e extends Hr{}class v1e extends Hr{}class _O extends Hr{}class S1e extends Hr{}class _1e extends Hr{}class C1e extends Hr{constructor(e,n,r){super(e,n),this.primaryKey=r}getName(){return(0,Ue.getIdentifier)(this.fieldDef)}getAsJoinedStructDef(e){return{...this.parent.fieldDef,structRelationship:{type:"one",matrixOperation:"left",onExpression:[{type:"field",path:[this.primaryKey]},"=",{type:"field",path:[e]}]}}}}class CO extends Hr{generateExpression(e){const n=this.fieldDef;if(n.timeframe){const r=this.parent.dialect.sqlTrunc(e.getQueryInfo(),{value:this.getExpr(),valueType:"date"},n.timeframe);return this.generateExpressionFromExpr(e,this.parent,r)}else return super.generateExpression(e)}getChildByName(e){const n={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new CO(n,this.parent)}}class bO extends Hr{getChildByName(e){const n={...this.fieldDef,as:`${this.getIdentifier()}_${e}`,timeframe:e};return new bO(n,this.parent)}}class b1e extends Hr{generateExpression(e){var n;if(this.parent.primaryKey())return this.parent.getPrimaryKeyField(this.fieldDef).generateExpression(e);if(this.parent.fieldDef.structSource.type==="nested"){const r=(n=this.parent.parent)===null||n===void 0?void 0:n.getDistinctKey().generateExpression(e);return this.parent.dialect.sqlMakeUnnestKey(r||"",this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"__row_id","string",!0,!1))}else return this.parent.dialect.sqlFieldReference(this.parent.getIdentifier(),"__distinct_key","string",this.parent.fieldDef.structRelationship.type==="nested",!1)}includeInWildcard(){return!1}}const zM=9;function QM(t,e,n){const i=t.sqlSumDistinctHashedKey(n),s=10**(9-zM);let u=`(${`
|
|
290
290
|
(
|
|
291
291
|
SUM(DISTINCT
|
|
292
292
|
(CAST(ROUND(COALESCE(${e},0)*(${s}*1.0), ${zM}) AS ${t.defaultDecimalType}) +
|