@malloydata/render 0.0.180 → 0.0.181-dev240907212110
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
|
@@ -2355,7 +2355,7 @@ const zde = Lt, JR = oe, TP = qW, Qde = p5, Gde = g5, Wde = {
|
|
|
2355
2355
|
};
|
|
2356
2356
|
class Yde extends Qde.PostgresBase {
|
|
2357
2357
|
constructor() {
|
|
2358
|
-
super(...arguments), this.name = "postgres", this.defaultNumberType = "DOUBLE PRECISION", this.defaultDecimalType = "NUMERIC", this.udfPrefix = "pg_temp.__udf", this.hasFinalStage = !0, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, 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.globalFunctions = TP.POSTGRES_FUNCTIONS, this.supportsNesting = !0, this.experimental = !1, this.readsNestedData = !1;
|
|
2358
|
+
super(...arguments), this.name = "postgres", this.defaultNumberType = "DOUBLE PRECISION", this.defaultDecimalType = "NUMERIC", this.udfPrefix = "pg_temp.__udf", this.hasFinalStage = !0, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, 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.globalFunctions = TP.POSTGRES_FUNCTIONS, this.supportsNesting = !0, this.experimental = !1, this.readsNestedData = !1, this.supportsComplexFilteredSources = !1;
|
|
2359
2359
|
}
|
|
2360
2360
|
quoteTablePath(e) {
|
|
2361
2361
|
return e.split(".").map((n) => `"${n}"`).join(".");
|
|
@@ -3224,7 +3224,7 @@ const whe = Lt, nO = oe, OP = VW, rp = jx, Lhe = j5, Ihe = {
|
|
|
3224
3224
|
};
|
|
3225
3225
|
class Bhe extends rp.Dialect {
|
|
3226
3226
|
constructor() {
|
|
3227
|
-
super(...arguments), this.name = "snowflake", this.experimental = !1, this.defaultNumberType = "NUMBER", this.defaultDecimalType = "NUMBER", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !1, this.supportsSumDistinctFunction = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.defaultSampling = { rows: 5e4 }, this.globalFunctions = OP.SNOWFLAKE_FUNCTIONS, this.unnestWithNumbers = !1, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !1, this.supportsQualify = !1, this.supportsPipelinesInViews = !1;
|
|
3227
|
+
super(...arguments), this.name = "snowflake", this.experimental = !1, this.defaultNumberType = "NUMBER", this.defaultDecimalType = "NUMBER", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !1, this.supportsSumDistinctFunction = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.defaultSampling = { rows: 5e4 }, this.globalFunctions = OP.SNOWFLAKE_FUNCTIONS, this.unnestWithNumbers = !1, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !1, this.supportsQualify = !1, this.supportsPipelinesInViews = !1, this.supportsComplexFilteredSources = !1;
|
|
3228
3228
|
}
|
|
3229
3229
|
// don't mess with the table pathing.
|
|
3230
3230
|
quoteTablePath(e) {
|
|
@@ -5388,13 +5388,11 @@ class so extends Fv {
|
|
|
5388
5388
|
e: s.onExpression
|
|
5389
5389
|
}, i.parent).generateExpression(this.rootResult) : a = "1=1";
|
|
5390
5390
|
let l = "", c;
|
|
5391
|
-
if (n.joinFilterConditions && (c = n.joinFilterConditions.map((f) => f.generateExpression(this.rootResult))), n.children.length === 0 || c === void 0)
|
|
5391
|
+
if (n.joinFilterConditions && (c = n.joinFilterConditions.map((f) => f.generateExpression(this.rootResult))), n.children.length === 0 || c === void 0 || !this.parent.dialect.supportsComplexFilteredSources)
|
|
5392
5392
|
c !== void 0 && c.length >= 1 && (l = ` AND (${c.join(" AND ")})`), r += ` ${u} JOIN ${o} AS ${n.alias}
|
|
5393
5393
|
ON ${a}${l}
|
|
5394
5394
|
`;
|
|
5395
5395
|
else {
|
|
5396
|
-
if (!this.parent.dialect.supportsComplexFilteredSources)
|
|
5397
|
-
throw new Error("Cannot join a source with a filter on a joined source");
|
|
5398
5396
|
let f = `SELECT ${n.alias}.*`, x = "";
|
|
5399
5397
|
for (const h of n.children)
|
|
5400
5398
|
x += this.generateSQLJoinBlock(e, h), f += `, ${this.parent.dialect.sqlSelectAliasAsStruct(h.alias, im(h.queryStruct.fieldDef))} AS ${h.alias}`;
|
package/dist/module/index.umd.js
CHANGED
|
@@ -114,7 +114,7 @@ AS (
|
|
|
114
114
|
${(0,JP.indent)(n)}
|
|
115
115
|
);
|
|
116
116
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
117
|
-
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,n){const r=bA(e),i=r?`, "${r}"`:"";return n.e.dataType==="date"?vde(n.units)?`DATE_TRUNC(${n.e.sql},${n.units})`:`TIMESTAMP(${n.e.sql}${i})`:`TIMESTAMP_TRUNC(${n.e.sql},${n.units}${i})`}sqlTimeExtractExpr(e,n){const r=Sde[n.units]||n.units,i=n.e.dataType==="timestamp"&&bA(e),s=i?` AT TIME ZONE '${i}'`:"";return`EXTRACT(${r} FROM ${n.e.sql}${s})`}sqlAlterTimeExpr(e){const n=e.kids.base;let r=n.dataType,i=n.sql;e.units!=="day"&&ZP(e.units)?r!=="timestamp"&&(i=`TIMESTAMP(${i})`,r="timestamp"):r==="timestamp"&&(i=`DATETIME(${i})`,r="datetime");const s=e.op==="+"?"_ADD":"_SUB",u=`${`${r.toUpperCase()}${s}`}(${i}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return r===n.dataType?u:`${n.dataType.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=bA(e),s=n.e.sql||"";if(r==="timestamp::date"&&i)return`DATE(${s},'${i}')`;if(r==="date::timestamp"&&i)return`TIMESTAMP(${s}, '${i}')`;if(n.srcType!==n.dstType){const o=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw;return`${n.safe?"SAFE_CAST":"CAST"}(${s} AS ${o})`}return s}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,n){if(n.dataType==="date")return`DATE('${n.literal}')`;if(n.dataType==="timestamp"){let r=`'${n.literal}'`;const i=n.timezone||bA(e);return i&&i!=="UTC"&&(r+=`,'${i}'`),`TIMESTAMP(${r})`}else throw new Error(`Unsupported Literal time format ${n.dataType}`)}sqlMeasureTimeExpr(e){const n={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},r=e.kids.left,i=e.kids.right;let s=r.sql,o=i.sql;if(n[e.units]){const{use:u,ratio:a}=n[e.units];if(!ZP(u))throw new Error(`Measure in '${u} not implemented`);if(r.dataType!==i.dataType)throw new Error("Can't measure difference between different types");r.dataType==="date"&&(s=`TIMESTAMP(${s})`,o=`TIMESTAMP(${o})`);let l=`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,nO.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,nO.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,nO.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${n.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return yde.STANDARDSQL_FUNCTIONS.get(e)}getDialectFunctions(){return Ade.STANDARDSQL_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return _de[i.toUpperCase()]}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}V1.StandardSQLDialect=Cde,function(t){var e=N&&N.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=N&&N.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(V1,t)}(UR);var rO={},RA={},eM={},tM={},jd={};Object.defineProperty(jd,"__esModule",{value:!0}),jd.fnStringAggDistinct=jd.fnStringAgg=void 0;const vn=pe;function Tde(){const t=(0,vn.makeParam)("value",(0,vn.maxScalar)("string")),e=(0,vn.makeParam)("separator",(0,vn.literal)((0,vn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,vn.overload)((0,vn.minAggregate)("string"),[t.param],(0,vn.sql)`STRING_AGG(${t.arg}, ','${n})`,{supportsOrderBy:!0}),(0,vn.overload)((0,vn.minAggregate)("string"),[t.param,e.param],(0,vn.sql)`STRING_AGG(${t.arg}, ${e.arg}${n})`,{supportsOrderBy:!0})]}jd.fnStringAgg=Tde;function bde(){const t=(0,vn.makeParam)("value",(0,vn.maxScalar)("string")),e=(0,vn.makeParam)("separator",(0,vn.literal)((0,vn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,vn.overload)((0,vn.minAggregate)("string"),[t.param],(0,vn.sql)`STRING_AGG(DISTINCT ${t.arg}, ','${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,vn.overload)((0,vn.minAggregate)("string"),[t.param,e.param],(0,vn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}jd.fnStringAggDistinct=bde;var OA={};Object.defineProperty(OA,"__esModule",{value:!0}),OA.fnByteLength=void 0;const Ud=pe;function Rde(){return[(0,Ud.overload)((0,Ud.minScalar)("number"),[(0,Ud.param)("value",(0,Ud.anyExprType)("string"))],(0,Ud.sql)`OCTET_LENGTH(${(0,Ud.arg)("value")})`)]}OA.fnByteLength=Rde;var NA={};Object.defineProperty(NA,"__esModule",{value:!0}),NA.fnEndsWith=void 0;const rf=pe;function Ode(){const t=(0,rf.makeParam)("value",(0,rf.anyExprType)("string")),e=(0,rf.makeParam)("suffix",(0,rf.anyExprType)("string"));return[(0,rf.overload)((0,rf.minScalar)("boolean"),[t.param,e.param],(0,rf.sql)`COALESCE(RIGHT(${t.arg}, LENGTH(${e.arg})) = ${e.arg}, false)`)]}NA.fnEndsWith=Ode;var qd={};Object.defineProperty(qd,"__esModule",{value:!0}),qd.fnLeast=qd.fnGreatest=void 0;const Ba=pe,Nde=["string","number","timestamp","date","json"];function nM(t){return Nde.map(e=>(0,Ba.overload)((0,Ba.minScalar)(e),[(0,Ba.params)("values",(0,Ba.anyExprType)(e))],(0,Ba.sql)`CASE WHEN NUM_NULLS(${(0,Ba.spread)((0,Ba.arg)("values"))}) > 0 THEN NULL ELSE ${t}(${(0,Ba.spread)((0,Ba.arg)("values"))}) END`))}const Dde=()=>nM("GREATEST");qd.fnGreatest=Dde;const Fde=()=>nM("LEAST");qd.fnLeast=Fde;var DA={};Object.defineProperty(DA,"__esModule",{value:!0}),DA.fnIfnull=void 0;const ka=pe,wde=["string","number","timestamp","date","json"];function Lde(){return wde.map(t=>(0,ka.overload)((0,ka.minScalar)(t),[(0,ka.param)("value",(0,ka.anyExprType)(t)),(0,ka.param)("default",(0,ka.anyExprType)(t))],(0,ka.sql)`COALESCE(${(0,ka.arg)("value")}, ${(0,ka.arg)("default")})`))}DA.fnIfnull=Lde;var FA={};Object.defineProperty(FA,"__esModule",{value:!0}),FA.fnIsInf=void 0;const ep=pe;function Ide(){const t=(0,ep.makeParam)("value",(0,ep.anyExprType)("number"));return[(0,ep.overload)((0,ep.minScalar)("boolean"),[t.param],(0,ep.sql)`COALESCE(${t.arg} = DOUBLE PRECISION 'Infinity' OR ${t.arg} = DOUBLE PRECISION '-Infinity', false)`)]}FA.fnIsInf=Ide;var wA={};Object.defineProperty(wA,"__esModule",{value:!0}),wA.fnIsNan=void 0;const Hd=pe;function $de(){return[(0,Hd.overload)((0,Hd.minScalar)("boolean"),[(0,Hd.param)("value",(0,Hd.anyExprType)("number"))],(0,Hd.sql)`COALESCE(${(0,Hd.arg)("value")} = NUMERIC 'NaN', false)`)]}wA.fnIsNan=$de;var LA={};Object.defineProperty(LA,"__esModule",{value:!0}),LA.fnLog=void 0;const sf=pe;function Bde(){const t=(0,sf.makeParam)("value",(0,sf.anyExprType)("number")),e=(0,sf.makeParam)("base",(0,sf.anyExprType)("number"));return[(0,sf.overload)((0,sf.minScalar)("number"),[t.param,e.param],(0,sf.sql)`LOG(${e.arg}, ${t.arg})`)]}LA.fnLog=Bde;var IA={};Object.defineProperty(IA,"__esModule",{value:!0}),IA.fnRand=void 0;const iO=pe;function kde(){return[(0,iO.overload)((0,iO.minScalar)("number"),[],(0,iO.sql)`RANDOM()`)]}IA.fnRand=kde;var $A={};Object.defineProperty($A,"__esModule",{value:!0}),$A.fnRegexpExtract=void 0;const of=pe;function Pde(){const t=(0,of.makeParam)("value",(0,of.anyExprType)("string")),e=(0,of.makeParam)("pattern",(0,of.anyExprType)("regular expression"));return[(0,of.overload)((0,of.minScalar)("string"),[t.param,e.param],(0,of.sql)`SUBSTRING(${t.arg}, ${e.arg})`)]}$A.fnRegexpExtract=Pde;var BA={};Object.defineProperty(BA,"__esModule",{value:!0}),BA.fnReplace=void 0;const ji=pe;function Mde(){const t=(0,ji.makeParam)("value",(0,ji.anyExprType)("string")),e=(0,ji.makeParam)("pattern",(0,ji.anyExprType)("string")),n=(0,ji.makeParam)("pattern",(0,ji.anyExprType)("regular expression")),r=(0,ji.makeParam)("replacement",(0,ji.anyExprType)("string"));return[(0,ji.overload)((0,ji.minScalar)("string"),[t.param,e.param,r.param],(0,ji.sql)`REPLACE(${t.arg}, ${e.arg}, ${r.arg})`),(0,ji.overload)((0,ji.minScalar)("string"),[t.param,n.param,r.param],(0,ji.sql)`REGEXP_REPLACE(${t.arg}, ${n.arg}, ${r.arg}, 'g')`)]}BA.fnReplace=Mde;var kA={};Object.defineProperty(kA,"__esModule",{value:!0}),kA.fnRound=void 0;const hu=pe;function jde(){const t=(0,hu.makeParam)("value",(0,hu.anyExprType)("number")),e=(0,hu.makeParam)("precision",(0,hu.anyExprType)("number"));return[(0,hu.overload)((0,hu.minScalar)("number"),[t.param],(0,hu.sql)`ROUND((${t.arg})::NUMERIC)`),(0,hu.overload)((0,hu.minScalar)("number"),[t.param,e.param],(0,hu.sql)`ROUND((${t.arg})::NUMERIC, ${e.arg})`)]}kA.fnRound=jde;var PA={};Object.defineProperty(PA,"__esModule",{value:!0}),PA.fnStddev=void 0;const tp=pe;function Ude(){const t=(0,tp.makeParam)("value",(0,tp.maxScalar)("number"));return[(0,tp.overload)((0,tp.minAggregate)("number"),[t.param],(0,tp.sql)`STDDEV(${t.arg}::DOUBLE PRECISION)`)]}PA.fnStddev=Ude;var MA={};Object.defineProperty(MA,"__esModule",{value:!0}),MA.fnSubstr=void 0;const Gs=pe;function qde(){const t=(0,Gs.makeParam)("value",(0,Gs.anyExprType)("string")),e=(0,Gs.makeParam)("position",(0,Gs.anyExprType)("number")),n=(0,Gs.makeParam)("length",(0,Gs.anyExprType)("number"));return[(0,Gs.overload)((0,Gs.minScalar)("string"),[t.param,e.param],(0,Gs.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END)`),(0,Gs.overload)((0,Gs.minScalar)("string"),[t.param,e.param,n.param],(0,Gs.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END, ${n.arg})`)]}MA.fnSubstr=qde;var jA={};Object.defineProperty(jA,"__esModule",{value:!0}),jA.fnTrunc=void 0;const pu=pe;function Hde(){const t=(0,pu.makeParam)("value",(0,pu.anyExprType)("number")),e=(0,pu.makeParam)("precision",(0,pu.anyExprType)("number"));return[(0,pu.overload)((0,pu.minScalar)("number"),[t.param],(0,pu.sql)`TRUNC(${t.arg}::NUMERIC)`),(0,pu.overload)((0,pu.minScalar)("number"),[t.param,e.param],(0,pu.sql)`TRUNC((${t.arg}::NUMERIC), ${e.arg})`)]}jA.fnTrunc=Hde;var UA={};Object.defineProperty(UA,"__esModule",{value:!0}),UA.fnUnicode=void 0;const zd=pe;function zde(){return[(0,zd.overload)((0,zd.minScalar)("number"),[(0,zd.param)("value",(0,zd.anyExprType)("string"))],(0,zd.sql)`ASCII(${(0,zd.arg)("value")})`)]}UA.fnUnicode=zde,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;const e=Vc,n=jd,r=OA,i=NA,s=qd,o=DA,u=FA,a=wA,l=LA,c=IA,f=$A,x=BA,h=kA,p=PA,m=MA,g=jA,y=UA;t.POSTGRES_FUNCTIONS=e.FUNCTIONS.clone(),t.POSTGRES_FUNCTIONS.add("regexp_extract",f.fnRegexpExtract),t.POSTGRES_FUNCTIONS.add("stddev",p.fnStddev),t.POSTGRES_FUNCTIONS.add("rand",c.fnRand),t.POSTGRES_FUNCTIONS.add("greatest",s.fnGreatest),t.POSTGRES_FUNCTIONS.add("least",s.fnLeast),t.POSTGRES_FUNCTIONS.add("is_nan",a.fnIsNan),t.POSTGRES_FUNCTIONS.add("is_inf",u.fnIsInf),t.POSTGRES_FUNCTIONS.add("round",h.fnRound),t.POSTGRES_FUNCTIONS.add("byte_length",r.fnByteLength),t.POSTGRES_FUNCTIONS.add("unicode",y.fnUnicode),t.POSTGRES_FUNCTIONS.add("ifnull",o.fnIfnull),t.POSTGRES_FUNCTIONS.add("trunc",g.fnTrunc),t.POSTGRES_FUNCTIONS.add("substr",m.fnSubstr),t.POSTGRES_FUNCTIONS.add("replace",x.fnReplace),t.POSTGRES_FUNCTIONS.add("ends_with",i.fnEndsWith),t.POSTGRES_FUNCTIONS.add("string_agg",n.fnStringAgg),t.POSTGRES_FUNCTIONS.add("string_agg_distinct",n.fnStringAggDistinct),t.POSTGRES_FUNCTIONS.add("log",l.fnLog),t.POSTGRES_FUNCTIONS.seal()}(tM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;var e=tM;Object.defineProperty(t,"POSTGRES_FUNCTIONS",{enumerable:!0,get:function(){return e.POSTGRES_FUNCTIONS}})}(eM);var qA={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=Wc;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class n extends e.Dialect{sqlTruncExpr(i,s){const o=s.units==="week",u=o?`${s.e.sql} + INTERVAL '1' DAY`:s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);if(l){const c=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`;let f=`DATE_TRUNC('${s.units}', ${c})`;return f=`${f}::TIMESTAMP`,`(${`${f} AT TIME ZONE '${l}'`})::TIMESTAMP`}}let a=`DATE_TRUNC('${s.units}', ${u})`;return o&&(a=`(${a} - INTERVAL '1' DAY)`),a}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(i,s){const o=t.timeExtractMap[s.units]||s.units;let u=s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);l&&(u=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`)}const a=`EXTRACT(${o} FROM ${u})`;return s.units==="day_of_week"?`mod(${a}+1,7)`:a}sqlCast(i,s){const o=s.e.sql||"",u=`${s.srcType}::${s.dstType}`,a=(0,e.qtz)(i);if(u==="timestamp::date"&&a)return`CAST((${`${o}::TIMESTAMPTZ`}) AT TIME ZONE '${a}' AS DATE)`;if(u==="date::timestamp"&&a)return`CAST((${o})::TIMESTAMP AT TIME ZONE '${a}' AS TIMESTAMP)`;if(s.srcType!==s.dstType){const l=typeof s.dstType=="string"?this.malloyTypeToSQLType({type:s.dstType}):s.dstType.raw;return`${s.safe?"TRY_CAST":"CAST"}(${o} AS ${l})`}return o}sqlRegexpMatch(i){return`${i.kids.expr.sql} ~ ${i.kids.regex.sql}`}sqlLiteralTime(i,s){if(s.dataType==="date")return`DATE '${s.literal}'`;const o=s.timezone||(0,e.qtz)(i);return o?`TIMESTAMPTZ '${s.literal} ${o}'::TIMESTAMP`:`TIMESTAMP '${s.literal}'`}}t.PostgresBase=n})(qA);var HA={};Object.defineProperty(HA,"__esModule",{value:!0}),HA.POSTGRES_DIALECT_FUNCTIONS=void 0,HA.POSTGRES_DIALECT_FUNCTIONS={},Object.defineProperty(RA,"__esModule",{value:!0}),RA.PostgresDialect=void 0;const Qde=wt,sO=oe,rM=eM,Gde=qA,Wde=HA,Vde={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},iM={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},Yde={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class Kde extends Gde.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,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.globalFunctions=rM.POSTGRES_FUNCTIONS,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1}quoteTablePath(e){return e.split(".").map(n=>`"${n}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,n){return`MAX(${n})`}mapFields(e){return e.map(n=>`
|
|
117
|
+
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,n){const r=bA(e),i=r?`, "${r}"`:"";return n.e.dataType==="date"?vde(n.units)?`DATE_TRUNC(${n.e.sql},${n.units})`:`TIMESTAMP(${n.e.sql}${i})`:`TIMESTAMP_TRUNC(${n.e.sql},${n.units}${i})`}sqlTimeExtractExpr(e,n){const r=Sde[n.units]||n.units,i=n.e.dataType==="timestamp"&&bA(e),s=i?` AT TIME ZONE '${i}'`:"";return`EXTRACT(${r} FROM ${n.e.sql}${s})`}sqlAlterTimeExpr(e){const n=e.kids.base;let r=n.dataType,i=n.sql;e.units!=="day"&&ZP(e.units)?r!=="timestamp"&&(i=`TIMESTAMP(${i})`,r="timestamp"):r==="timestamp"&&(i=`DATETIME(${i})`,r="datetime");const s=e.op==="+"?"_ADD":"_SUB",u=`${`${r.toUpperCase()}${s}`}(${i}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return r===n.dataType?u:`${n.dataType.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=bA(e),s=n.e.sql||"";if(r==="timestamp::date"&&i)return`DATE(${s},'${i}')`;if(r==="date::timestamp"&&i)return`TIMESTAMP(${s}, '${i}')`;if(n.srcType!==n.dstType){const o=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw;return`${n.safe?"SAFE_CAST":"CAST"}(${s} AS ${o})`}return s}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,n){if(n.dataType==="date")return`DATE('${n.literal}')`;if(n.dataType==="timestamp"){let r=`'${n.literal}'`;const i=n.timezone||bA(e);return i&&i!=="UTC"&&(r+=`,'${i}'`),`TIMESTAMP(${r})`}else throw new Error(`Unsupported Literal time format ${n.dataType}`)}sqlMeasureTimeExpr(e){const n={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},r=e.kids.left,i=e.kids.right;let s=r.sql,o=i.sql;if(n[e.units]){const{use:u,ratio:a}=n[e.units];if(!ZP(u))throw new Error(`Measure in '${u} not implemented`);if(r.dataType!==i.dataType)throw new Error("Can't measure difference between different types");r.dataType==="date"&&(s=`TIMESTAMP(${s})`,o=`TIMESTAMP(${o})`);let l=`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,nO.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,nO.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,nO.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${n.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return yde.STANDARDSQL_FUNCTIONS.get(e)}getDialectFunctions(){return Ade.STANDARDSQL_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return _de[i.toUpperCase()]}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}V1.StandardSQLDialect=Cde,function(t){var e=N&&N.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=N&&N.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(V1,t)}(UR);var rO={},RA={},eM={},tM={},jd={};Object.defineProperty(jd,"__esModule",{value:!0}),jd.fnStringAggDistinct=jd.fnStringAgg=void 0;const vn=pe;function Tde(){const t=(0,vn.makeParam)("value",(0,vn.maxScalar)("string")),e=(0,vn.makeParam)("separator",(0,vn.literal)((0,vn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,vn.overload)((0,vn.minAggregate)("string"),[t.param],(0,vn.sql)`STRING_AGG(${t.arg}, ','${n})`,{supportsOrderBy:!0}),(0,vn.overload)((0,vn.minAggregate)("string"),[t.param,e.param],(0,vn.sql)`STRING_AGG(${t.arg}, ${e.arg}${n})`,{supportsOrderBy:!0})]}jd.fnStringAgg=Tde;function bde(){const t=(0,vn.makeParam)("value",(0,vn.maxScalar)("string")),e=(0,vn.makeParam)("separator",(0,vn.literal)((0,vn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,vn.overload)((0,vn.minAggregate)("string"),[t.param],(0,vn.sql)`STRING_AGG(DISTINCT ${t.arg}, ','${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,vn.overload)((0,vn.minAggregate)("string"),[t.param,e.param],(0,vn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}jd.fnStringAggDistinct=bde;var OA={};Object.defineProperty(OA,"__esModule",{value:!0}),OA.fnByteLength=void 0;const Ud=pe;function Rde(){return[(0,Ud.overload)((0,Ud.minScalar)("number"),[(0,Ud.param)("value",(0,Ud.anyExprType)("string"))],(0,Ud.sql)`OCTET_LENGTH(${(0,Ud.arg)("value")})`)]}OA.fnByteLength=Rde;var NA={};Object.defineProperty(NA,"__esModule",{value:!0}),NA.fnEndsWith=void 0;const rf=pe;function Ode(){const t=(0,rf.makeParam)("value",(0,rf.anyExprType)("string")),e=(0,rf.makeParam)("suffix",(0,rf.anyExprType)("string"));return[(0,rf.overload)((0,rf.minScalar)("boolean"),[t.param,e.param],(0,rf.sql)`COALESCE(RIGHT(${t.arg}, LENGTH(${e.arg})) = ${e.arg}, false)`)]}NA.fnEndsWith=Ode;var qd={};Object.defineProperty(qd,"__esModule",{value:!0}),qd.fnLeast=qd.fnGreatest=void 0;const Ba=pe,Nde=["string","number","timestamp","date","json"];function nM(t){return Nde.map(e=>(0,Ba.overload)((0,Ba.minScalar)(e),[(0,Ba.params)("values",(0,Ba.anyExprType)(e))],(0,Ba.sql)`CASE WHEN NUM_NULLS(${(0,Ba.spread)((0,Ba.arg)("values"))}) > 0 THEN NULL ELSE ${t}(${(0,Ba.spread)((0,Ba.arg)("values"))}) END`))}const Dde=()=>nM("GREATEST");qd.fnGreatest=Dde;const Fde=()=>nM("LEAST");qd.fnLeast=Fde;var DA={};Object.defineProperty(DA,"__esModule",{value:!0}),DA.fnIfnull=void 0;const ka=pe,wde=["string","number","timestamp","date","json"];function Lde(){return wde.map(t=>(0,ka.overload)((0,ka.minScalar)(t),[(0,ka.param)("value",(0,ka.anyExprType)(t)),(0,ka.param)("default",(0,ka.anyExprType)(t))],(0,ka.sql)`COALESCE(${(0,ka.arg)("value")}, ${(0,ka.arg)("default")})`))}DA.fnIfnull=Lde;var FA={};Object.defineProperty(FA,"__esModule",{value:!0}),FA.fnIsInf=void 0;const ep=pe;function Ide(){const t=(0,ep.makeParam)("value",(0,ep.anyExprType)("number"));return[(0,ep.overload)((0,ep.minScalar)("boolean"),[t.param],(0,ep.sql)`COALESCE(${t.arg} = DOUBLE PRECISION 'Infinity' OR ${t.arg} = DOUBLE PRECISION '-Infinity', false)`)]}FA.fnIsInf=Ide;var wA={};Object.defineProperty(wA,"__esModule",{value:!0}),wA.fnIsNan=void 0;const Hd=pe;function $de(){return[(0,Hd.overload)((0,Hd.minScalar)("boolean"),[(0,Hd.param)("value",(0,Hd.anyExprType)("number"))],(0,Hd.sql)`COALESCE(${(0,Hd.arg)("value")} = NUMERIC 'NaN', false)`)]}wA.fnIsNan=$de;var LA={};Object.defineProperty(LA,"__esModule",{value:!0}),LA.fnLog=void 0;const sf=pe;function Bde(){const t=(0,sf.makeParam)("value",(0,sf.anyExprType)("number")),e=(0,sf.makeParam)("base",(0,sf.anyExprType)("number"));return[(0,sf.overload)((0,sf.minScalar)("number"),[t.param,e.param],(0,sf.sql)`LOG(${e.arg}, ${t.arg})`)]}LA.fnLog=Bde;var IA={};Object.defineProperty(IA,"__esModule",{value:!0}),IA.fnRand=void 0;const iO=pe;function kde(){return[(0,iO.overload)((0,iO.minScalar)("number"),[],(0,iO.sql)`RANDOM()`)]}IA.fnRand=kde;var $A={};Object.defineProperty($A,"__esModule",{value:!0}),$A.fnRegexpExtract=void 0;const of=pe;function Pde(){const t=(0,of.makeParam)("value",(0,of.anyExprType)("string")),e=(0,of.makeParam)("pattern",(0,of.anyExprType)("regular expression"));return[(0,of.overload)((0,of.minScalar)("string"),[t.param,e.param],(0,of.sql)`SUBSTRING(${t.arg}, ${e.arg})`)]}$A.fnRegexpExtract=Pde;var BA={};Object.defineProperty(BA,"__esModule",{value:!0}),BA.fnReplace=void 0;const ji=pe;function Mde(){const t=(0,ji.makeParam)("value",(0,ji.anyExprType)("string")),e=(0,ji.makeParam)("pattern",(0,ji.anyExprType)("string")),n=(0,ji.makeParam)("pattern",(0,ji.anyExprType)("regular expression")),r=(0,ji.makeParam)("replacement",(0,ji.anyExprType)("string"));return[(0,ji.overload)((0,ji.minScalar)("string"),[t.param,e.param,r.param],(0,ji.sql)`REPLACE(${t.arg}, ${e.arg}, ${r.arg})`),(0,ji.overload)((0,ji.minScalar)("string"),[t.param,n.param,r.param],(0,ji.sql)`REGEXP_REPLACE(${t.arg}, ${n.arg}, ${r.arg}, 'g')`)]}BA.fnReplace=Mde;var kA={};Object.defineProperty(kA,"__esModule",{value:!0}),kA.fnRound=void 0;const hu=pe;function jde(){const t=(0,hu.makeParam)("value",(0,hu.anyExprType)("number")),e=(0,hu.makeParam)("precision",(0,hu.anyExprType)("number"));return[(0,hu.overload)((0,hu.minScalar)("number"),[t.param],(0,hu.sql)`ROUND((${t.arg})::NUMERIC)`),(0,hu.overload)((0,hu.minScalar)("number"),[t.param,e.param],(0,hu.sql)`ROUND((${t.arg})::NUMERIC, ${e.arg})`)]}kA.fnRound=jde;var PA={};Object.defineProperty(PA,"__esModule",{value:!0}),PA.fnStddev=void 0;const tp=pe;function Ude(){const t=(0,tp.makeParam)("value",(0,tp.maxScalar)("number"));return[(0,tp.overload)((0,tp.minAggregate)("number"),[t.param],(0,tp.sql)`STDDEV(${t.arg}::DOUBLE PRECISION)`)]}PA.fnStddev=Ude;var MA={};Object.defineProperty(MA,"__esModule",{value:!0}),MA.fnSubstr=void 0;const Gs=pe;function qde(){const t=(0,Gs.makeParam)("value",(0,Gs.anyExprType)("string")),e=(0,Gs.makeParam)("position",(0,Gs.anyExprType)("number")),n=(0,Gs.makeParam)("length",(0,Gs.anyExprType)("number"));return[(0,Gs.overload)((0,Gs.minScalar)("string"),[t.param,e.param],(0,Gs.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END)`),(0,Gs.overload)((0,Gs.minScalar)("string"),[t.param,e.param,n.param],(0,Gs.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END, ${n.arg})`)]}MA.fnSubstr=qde;var jA={};Object.defineProperty(jA,"__esModule",{value:!0}),jA.fnTrunc=void 0;const pu=pe;function Hde(){const t=(0,pu.makeParam)("value",(0,pu.anyExprType)("number")),e=(0,pu.makeParam)("precision",(0,pu.anyExprType)("number"));return[(0,pu.overload)((0,pu.minScalar)("number"),[t.param],(0,pu.sql)`TRUNC(${t.arg}::NUMERIC)`),(0,pu.overload)((0,pu.minScalar)("number"),[t.param,e.param],(0,pu.sql)`TRUNC((${t.arg}::NUMERIC), ${e.arg})`)]}jA.fnTrunc=Hde;var UA={};Object.defineProperty(UA,"__esModule",{value:!0}),UA.fnUnicode=void 0;const zd=pe;function zde(){return[(0,zd.overload)((0,zd.minScalar)("number"),[(0,zd.param)("value",(0,zd.anyExprType)("string"))],(0,zd.sql)`ASCII(${(0,zd.arg)("value")})`)]}UA.fnUnicode=zde,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;const e=Vc,n=jd,r=OA,i=NA,s=qd,o=DA,u=FA,a=wA,l=LA,c=IA,f=$A,x=BA,h=kA,p=PA,m=MA,g=jA,y=UA;t.POSTGRES_FUNCTIONS=e.FUNCTIONS.clone(),t.POSTGRES_FUNCTIONS.add("regexp_extract",f.fnRegexpExtract),t.POSTGRES_FUNCTIONS.add("stddev",p.fnStddev),t.POSTGRES_FUNCTIONS.add("rand",c.fnRand),t.POSTGRES_FUNCTIONS.add("greatest",s.fnGreatest),t.POSTGRES_FUNCTIONS.add("least",s.fnLeast),t.POSTGRES_FUNCTIONS.add("is_nan",a.fnIsNan),t.POSTGRES_FUNCTIONS.add("is_inf",u.fnIsInf),t.POSTGRES_FUNCTIONS.add("round",h.fnRound),t.POSTGRES_FUNCTIONS.add("byte_length",r.fnByteLength),t.POSTGRES_FUNCTIONS.add("unicode",y.fnUnicode),t.POSTGRES_FUNCTIONS.add("ifnull",o.fnIfnull),t.POSTGRES_FUNCTIONS.add("trunc",g.fnTrunc),t.POSTGRES_FUNCTIONS.add("substr",m.fnSubstr),t.POSTGRES_FUNCTIONS.add("replace",x.fnReplace),t.POSTGRES_FUNCTIONS.add("ends_with",i.fnEndsWith),t.POSTGRES_FUNCTIONS.add("string_agg",n.fnStringAgg),t.POSTGRES_FUNCTIONS.add("string_agg_distinct",n.fnStringAggDistinct),t.POSTGRES_FUNCTIONS.add("log",l.fnLog),t.POSTGRES_FUNCTIONS.seal()}(tM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;var e=tM;Object.defineProperty(t,"POSTGRES_FUNCTIONS",{enumerable:!0,get:function(){return e.POSTGRES_FUNCTIONS}})}(eM);var qA={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=Wc;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class n extends e.Dialect{sqlTruncExpr(i,s){const o=s.units==="week",u=o?`${s.e.sql} + INTERVAL '1' DAY`:s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);if(l){const c=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`;let f=`DATE_TRUNC('${s.units}', ${c})`;return f=`${f}::TIMESTAMP`,`(${`${f} AT TIME ZONE '${l}'`})::TIMESTAMP`}}let a=`DATE_TRUNC('${s.units}', ${u})`;return o&&(a=`(${a} - INTERVAL '1' DAY)`),a}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(i,s){const o=t.timeExtractMap[s.units]||s.units;let u=s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);l&&(u=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`)}const a=`EXTRACT(${o} FROM ${u})`;return s.units==="day_of_week"?`mod(${a}+1,7)`:a}sqlCast(i,s){const o=s.e.sql||"",u=`${s.srcType}::${s.dstType}`,a=(0,e.qtz)(i);if(u==="timestamp::date"&&a)return`CAST((${`${o}::TIMESTAMPTZ`}) AT TIME ZONE '${a}' AS DATE)`;if(u==="date::timestamp"&&a)return`CAST((${o})::TIMESTAMP AT TIME ZONE '${a}' AS TIMESTAMP)`;if(s.srcType!==s.dstType){const l=typeof s.dstType=="string"?this.malloyTypeToSQLType({type:s.dstType}):s.dstType.raw;return`${s.safe?"TRY_CAST":"CAST"}(${o} AS ${l})`}return o}sqlRegexpMatch(i){return`${i.kids.expr.sql} ~ ${i.kids.regex.sql}`}sqlLiteralTime(i,s){if(s.dataType==="date")return`DATE '${s.literal}'`;const o=s.timezone||(0,e.qtz)(i);return o?`TIMESTAMPTZ '${s.literal} ${o}'::TIMESTAMP`:`TIMESTAMP '${s.literal}'`}}t.PostgresBase=n})(qA);var HA={};Object.defineProperty(HA,"__esModule",{value:!0}),HA.POSTGRES_DIALECT_FUNCTIONS=void 0,HA.POSTGRES_DIALECT_FUNCTIONS={},Object.defineProperty(RA,"__esModule",{value:!0}),RA.PostgresDialect=void 0;const Qde=wt,sO=oe,rM=eM,Gde=qA,Wde=HA,Vde={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},iM={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},Yde={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class Kde extends Gde.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,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.globalFunctions=rM.POSTGRES_FUNCTIONS,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1}quoteTablePath(e){return e.split(".").map(n=>`"${n}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,n){return`MAX(${n})`}mapFields(e){return e.map(n=>`
|
|
118
118
|
${n.sqlExpression}${n.type==="number"?`::${this.defaultNumberType}`:""} as ${n.sqlOutputName}`).join(", ")}sqlAggregateTurtle(e,n,r,i){let s="";return i!==void 0&&(s+=`[1:${i}]`),`COALESCE(TO_JSONB((ARRAY_AGG((SELECT TO_JSONB(__x) FROM (SELECT ${this.mapFields(n)}
|
|
119
119
|
) as __x) ${r} ) FILTER (WHERE group_set=${e}))${s}),'[]'::JSONB)`}sqlAnyValueTurtle(e,n){const r=n.map(i=>`${i.sqlExpression} as ${i.sqlOutputName}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`(ARRAY_AGG(${e}) FILTER (WHERE group_set=${n} AND ${e} IS NOT NULL))[1] as ${r}`}sqlCoaleseMeasuresInline(e,n){return`TO_JSONB((ARRAY_AGG((SELECT __x FROM (SELECT ${this.mapFields(n)}) as __x)) FILTER (WHERE group_set=${e}))[1])`}sqlUnnestAlias(e,n,r,i,s,o){return s?i?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_id', row_number() over (), 'value', v) FROM UNNEST(${e}) as v))) as ${n} ON true`:`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('value', v) FROM UNNEST(${e}) as v))) as ${n} ON true`:i?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_number', row_number() over())|| __xx::jsonb as b FROM JSONB_ARRAY_ELEMENTS(${e}) __xx ))) as ${n} ON true`:`LEFT JOIN JSONB_ARRAY_ELEMENTS(${e}) as ${n} ON true`}sqlSumDistinctHashedKey(e){return`('x' || MD5(${e}::varchar))::bit(64)::bigint::DECIMAL(65,0) *18446744073709551616 + ('x' || SUBSTR(MD5(${e}::varchar),17))::bit(64)::bigint::DECIMAL(65,0)`}sqlGenerateUUID(){return"GEN_RANDOM_UUID()"}sqlFieldReference(e,n,r,i,s){let o=`(${e}->>'${n}')`;if(i){switch(r){case"string":break;case"number":o=`${o}::double precision`;break;case"struct":o=`${o}::jsonb`;break}return o}else return`${e}."${n}"`}sqlUnnestPipelineHead(e,n){return e?`UNNEST(ARRAY((SELECT ${n})))`:`JSONB_ARRAY_ELEMENTS(${n})`}sqlCreateFunction(e,n){return`CREATE FUNCTION ${e}(JSONB) RETURNS JSONB AS $$
|
|
120
120
|
${(0,Qde.indent)(n)}
|
|
@@ -154,7 +154,7 @@ ${aM}
|
|
|
154
154
|
FROM (
|
|
155
155
|
SELECT UNNEST(list(distinct {key:${e}, ${n.map((i,s)=>`val${s}: ${i}`).join(",")}})) a
|
|
156
156
|
)
|
|
157
|
-
)`}sqlSampleTable(e,n){if(n!==void 0){if((0,aO.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,aO.isSamplingRows)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.rows})`;if((0,aO.isSamplingPercent)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.percent} PERCENT (bernoulli))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/'/g,"''")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getGlobalFunctionDef(e){return xhe.DUCKDB_FUNCTIONS.get(e)}getDialectFunctions(){return phe.DUCKDB_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double precision":e.type==="string"?"varchar":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return ghe[i.toUpperCase()]}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlAlterTimeExpr(e){let n=e.units,r=e.kids.delta.sql;n==="quarter"?(n="month",r=`${r}*3`):n==="week"&&(n="day",r=`${r}*7`);const i=`INTERVAL (${r}) ${n}`;return`${e.kids.base.sql} ${e.op} ${i}`}sqlRegexpMatch(e){return`REGEXP_MATCHES(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlMeasureTimeExpr(e){const n=e.kids.left,r=e.kids.right;let i=n.sql||"",s=r.sql||"";return(0,dhe.inDays)(e.units)||(n.dataType==="date"&&(i=`${i}::TIMESTAMP`),r.dataType==="date"&&(s=`${s}::TIMESTAMP`)),`DATE_SUB('${e.units}', ${i}, ${s})`}}zA.DuckDBDialect=mhe,function(t){var e=N&&N.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=N&&N.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(zA,t)}(oO);var lO={},rv={},lM={},cM={},iv={};Object.defineProperty(iv,"__esModule",{value:!0}),iv.fnChr=void 0;const rp=pe;function yhe(){const t=(0,rp.makeParam)("value",(0,rp.anyExprType)("number"));return[(0,rp.overload)((0,rp.minScalar)("string"),[t.param],(0,rp.sql)`COALESCE(CHR(${t.arg}), '')`)]}iv.fnChr=yhe;var sv={};Object.defineProperty(sv,"__esModule",{value:!0}),sv.fnDiv=void 0;const cf=pe;function Ehe(){const t=(0,cf.makeParam)("dividend",(0,cf.anyExprType)("number")),e=(0,cf.makeParam)("divisor",(0,cf.anyExprType)("number"));return[(0,cf.overload)((0,cf.minScalar)("number"),[t.param,e.param],(0,cf.sql)`CASE WHEN DIV0(${t.arg}, ${e.arg}) < 0 THEN CEIL(DIV0(${t.arg}, ${e.arg})) ELSE FLOOR(DIV0(${t.arg}, ${e.arg})) END`)]}sv.fnDiv=Ehe;var ov={};Object.defineProperty(ov,"__esModule",{value:!0}),ov.fnIsInf=void 0;const ip=pe;function Ahe(){const t=(0,ip.makeParam)("value",(0,ip.anyExprType)("number"));return[(0,ip.overload)((0,ip.minScalar)("boolean"),[t.param],(0,ip.sql)`COALESCE(${t.arg} = 'inf'::FLOAT OR ${t.arg} = '-inf'::FLOAT, false)`)]}ov.fnIsInf=Ahe;var uv={};Object.defineProperty(uv,"__esModule",{value:!0}),uv.fnIsNan=void 0;const Kd=pe;function vhe(){return[(0,Kd.overload)((0,Kd.minScalar)("boolean"),[(0,Kd.param)("value",(0,Kd.anyExprType)("number"))],(0,Kd.sql)`COALESCE(${(0,Kd.arg)("value")} = 'NAN'::FLOAT, false)`)]}uv.fnIsNan=vhe;var Xd={};Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.fnByteLength=Xd.fnLength=void 0;const Ws=pe;function She(){return[(0,Ws.overload)((0,Ws.minScalar)("number"),[(0,Ws.param)("value",(0,Ws.anyExprType)("string"))],(0,Ws.sql)`LENGTH(${(0,Ws.arg)("value")})`)]}Xd.fnLength=She;function _he(){return[(0,Ws.overload)((0,Ws.minScalar)("number"),[(0,Ws.param)("value",(0,Ws.anyExprType)("string"))],(0,Ws.sql)`CEIL(BIT_LENGTH(${(0,Ws.arg)("value")}) / 8)`)]}Xd.fnByteLength=_he;var av={};Object.defineProperty(av,"__esModule",{value:!0}),av.fnLog=void 0;const ff=pe;function Che(){const t=(0,ff.makeParam)("value",(0,ff.anyExprType)("number")),e=(0,ff.makeParam)("base",(0,ff.anyExprType)("number"));return[(0,ff.overload)((0,ff.minScalar)("number"),[t.param,e.param],(0,ff.sql)`LOG(${e.arg}, ${t.arg})`)]}av.fnLog=Che;var lv={};Object.defineProperty(lv,"__esModule",{value:!0}),lv.fnRand=void 0;const cO=pe;function The(){return[(0,cO.overload)((0,cO.minScalar)("number"),[],(0,cO.sql)`UNIFORM(0::FLOAT, 1::FLOAT, RANDOM())`)]}lv.fnRand=The;var cv={};Object.defineProperty(cv,"__esModule",{value:!0}),cv.fnRegexpExtract=void 0;const xf=pe;function bhe(){const t=(0,xf.makeParam)("value",(0,xf.anyExprType)("string")),e=(0,xf.makeParam)("pattern",(0,xf.anyExprType)("regular expression"));return[(0,xf.overload)((0,xf.minScalar)("string"),[t.param,e.param],(0,xf.sql)`REGEXP_SUBSTR(${t.arg}, ${e.arg}, 1, 1, 'e')`)]}cv.fnRegexpExtract=bhe;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.fnEndsWith=Jd.fnStartsWith=void 0;const qi=pe;function Rhe(){const t=(0,qi.makeParam)("value",(0,qi.anyExprType)("string")),e=(0,qi.makeParam)("prefix",(0,qi.anyExprType)("string"));return[(0,qi.overload)((0,qi.minScalar)("boolean"),[t.param,e.param],(0,qi.sql)`COALESCE(STARTSWITH(${t.arg}, ${e.arg}), false)`)]}Jd.fnStartsWith=Rhe;function Ohe(){const t=(0,qi.makeParam)("value",(0,qi.anyExprType)("string")),e=(0,qi.makeParam)("suffix",(0,qi.anyExprType)("string"));return[(0,qi.overload)((0,qi.minScalar)("boolean"),[t.param,e.param],(0,qi.sql)`COALESCE(ENDSWITH(${t.arg}, ${e.arg}), false)`)]}Jd.fnEndsWith=Ohe;var fv={};Object.defineProperty(fv,"__esModule",{value:!0}),fv.fnStrpos=void 0;const df=pe;function Nhe(){const t=(0,df.makeParam)("test_string",(0,df.anyExprType)("string")),e=(0,df.makeParam)("search_string",(0,df.anyExprType)("string"));return[(0,df.overload)((0,df.minScalar)("number"),[t.param,e.param],(0,df.sql)`POSITION(${e.arg}, ${t.arg})`)]}fv.fnStrpos=Nhe;var xv={};Object.defineProperty(xv,"__esModule",{value:!0}),xv.fnTrunc=void 0;const mu=pe;function Dhe(){const t=(0,mu.makeParam)("value",(0,mu.anyExprType)("number")),e=(0,mu.makeParam)("precision",(0,mu.anyExprType)("number"));return[(0,mu.overload)((0,mu.minScalar)("number"),[t.param],(0,mu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg}) ELSE FLOOR(${t.arg}) END`),(0,mu.overload)((0,mu.minScalar)("number"),[t.param,e.param],(0,mu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) ELSE FLOOR(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) END`)]}xv.fnTrunc=Dhe;var Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.fnStringAggDistinct=Zd.fnStringAgg=void 0;const Sn=pe;function Fhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`LISTAGG(${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`LISTAGG(${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Zd.fnStringAgg=Fhe;function whe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`LISTAGG(DISTINCT ${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`LISTAGG(DISTINCT ${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Zd.fnStringAggDistinct=whe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;const e=Vc,n=iv,r=sv,i=ov,s=uv,o=Xd,u=av,a=lv,l=cv,c=Jd,f=fv,x=xv,h=Zd;t.SNOWFLAKE_FUNCTIONS=e.FUNCTIONS.clone(),t.SNOWFLAKE_FUNCTIONS.add("byte_length",o.fnByteLength),t.SNOWFLAKE_FUNCTIONS.add("chr",n.fnChr),t.SNOWFLAKE_FUNCTIONS.add("div",r.fnDiv),t.SNOWFLAKE_FUNCTIONS.add("is_inf",i.fnIsInf),t.SNOWFLAKE_FUNCTIONS.add("is_nan",s.fnIsNan),t.SNOWFLAKE_FUNCTIONS.add("length",o.fnLength),t.SNOWFLAKE_FUNCTIONS.add("log",u.fnLog),t.SNOWFLAKE_FUNCTIONS.add("rand",a.fnRand),t.SNOWFLAKE_FUNCTIONS.add("regexp_extract",l.fnRegexpExtract),t.SNOWFLAKE_FUNCTIONS.add("starts_with",c.fnStartsWith),t.SNOWFLAKE_FUNCTIONS.add("ends_with",c.fnEndsWith),t.SNOWFLAKE_FUNCTIONS.add("strpos",f.fnStrpos),t.SNOWFLAKE_FUNCTIONS.add("trunc",x.fnTrunc),t.SNOWFLAKE_FUNCTIONS.add("string_agg",h.fnStringAgg),t.SNOWFLAKE_FUNCTIONS.add("string_agg_distinct",h.fnStringAggDistinct),t.SNOWFLAKE_FUNCTIONS.seal()}(cM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;var e=cM;Object.defineProperty(t,"SNOWFLAKE_FUNCTIONS",{enumerable:!0,get:function(){return e.SNOWFLAKE_FUNCTIONS}})}(lM);var dv={};Object.defineProperty(dv,"__esModule",{value:!0}),dv.SNOWFLAKE_DIALECT_FUNCTIONS=void 0,dv.SNOWFLAKE_DIALECT_FUNCTIONS={},Object.defineProperty(rv,"__esModule",{value:!0}),rv.SnowflakeDialect=void 0;const Lhe=wt,fO=oe,fM=lM,sp=Wc,Ihe=dv,$he={day_of_week:"dayofweek",day_of_year:"dayofyear"},Bhe={varchar:{type:"string"},text:{type:"string"},string:{type:"string"},char:{type:"string"},character:{type:"string"},nvarchar:{type:"string"},nvarchar2:{type:"string"},"char varying":{type:"string"},"nchar varying":{type:"string"},number:{type:"number",numberType:"integer"},numeric:{type:"number",numberType:"integer"},decimal:{type:"number",numberType:"integer"},dec:{type:"number",numberType:"integer"},integer:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},byteint:{type:"number",numberType:"integer"},float:{type:"number",numberType:"float"},float4:{type:"number",numberType:"float"},float8:{type:"number",numberType:"float"},double:{type:"number",numberType:"float"},"double precision":{type:"number",numberType:"float"},real:{type:"number",numberType:"float"},boolean:{type:"boolean"},date:{type:"date"},timestamp:{type:"timestamp"},timestampntz:{type:"timestamp"},timestamp_ntz:{type:"timestamp"},"timestamp without time zone":{type:"timestamp"},timestamptz:{type:"timestamp"},timestamp_tz:{type:"timestamp"},"timestamp with time zone":{type:"timestamp"}};class khe extends sp.Dialect{constructor(){super(...arguments),this.name="snowflake",this.experimental=!1,this.defaultNumberType="NUMBER",this.defaultDecimalType="NUMBER",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.defaultSampling={rows:5e4},this.globalFunctions=fM.SNOWFLAKE_FUNCTIONS,this.unnestWithNumbers=!1,this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsPipelinesInViews=!1}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT index as group_set FROM TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, ${e+1}))))`}sqlAnyValue(e,n){return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN ${n} END) WITHIN GROUP (ORDER BY ${n} ASC NULLS LAST))[0]`}mapFields(e){return e.map(n=>`
|
|
157
|
+
)`}sqlSampleTable(e,n){if(n!==void 0){if((0,aO.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,aO.isSamplingRows)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.rows})`;if((0,aO.isSamplingPercent)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.percent} PERCENT (bernoulli))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/'/g,"''")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getGlobalFunctionDef(e){return xhe.DUCKDB_FUNCTIONS.get(e)}getDialectFunctions(){return phe.DUCKDB_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double precision":e.type==="string"?"varchar":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return ghe[i.toUpperCase()]}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlAlterTimeExpr(e){let n=e.units,r=e.kids.delta.sql;n==="quarter"?(n="month",r=`${r}*3`):n==="week"&&(n="day",r=`${r}*7`);const i=`INTERVAL (${r}) ${n}`;return`${e.kids.base.sql} ${e.op} ${i}`}sqlRegexpMatch(e){return`REGEXP_MATCHES(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlMeasureTimeExpr(e){const n=e.kids.left,r=e.kids.right;let i=n.sql||"",s=r.sql||"";return(0,dhe.inDays)(e.units)||(n.dataType==="date"&&(i=`${i}::TIMESTAMP`),r.dataType==="date"&&(s=`${s}::TIMESTAMP`)),`DATE_SUB('${e.units}', ${i}, ${s})`}}zA.DuckDBDialect=mhe,function(t){var e=N&&N.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=N&&N.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(zA,t)}(oO);var lO={},rv={},lM={},cM={},iv={};Object.defineProperty(iv,"__esModule",{value:!0}),iv.fnChr=void 0;const rp=pe;function yhe(){const t=(0,rp.makeParam)("value",(0,rp.anyExprType)("number"));return[(0,rp.overload)((0,rp.minScalar)("string"),[t.param],(0,rp.sql)`COALESCE(CHR(${t.arg}), '')`)]}iv.fnChr=yhe;var sv={};Object.defineProperty(sv,"__esModule",{value:!0}),sv.fnDiv=void 0;const cf=pe;function Ehe(){const t=(0,cf.makeParam)("dividend",(0,cf.anyExprType)("number")),e=(0,cf.makeParam)("divisor",(0,cf.anyExprType)("number"));return[(0,cf.overload)((0,cf.minScalar)("number"),[t.param,e.param],(0,cf.sql)`CASE WHEN DIV0(${t.arg}, ${e.arg}) < 0 THEN CEIL(DIV0(${t.arg}, ${e.arg})) ELSE FLOOR(DIV0(${t.arg}, ${e.arg})) END`)]}sv.fnDiv=Ehe;var ov={};Object.defineProperty(ov,"__esModule",{value:!0}),ov.fnIsInf=void 0;const ip=pe;function Ahe(){const t=(0,ip.makeParam)("value",(0,ip.anyExprType)("number"));return[(0,ip.overload)((0,ip.minScalar)("boolean"),[t.param],(0,ip.sql)`COALESCE(${t.arg} = 'inf'::FLOAT OR ${t.arg} = '-inf'::FLOAT, false)`)]}ov.fnIsInf=Ahe;var uv={};Object.defineProperty(uv,"__esModule",{value:!0}),uv.fnIsNan=void 0;const Kd=pe;function vhe(){return[(0,Kd.overload)((0,Kd.minScalar)("boolean"),[(0,Kd.param)("value",(0,Kd.anyExprType)("number"))],(0,Kd.sql)`COALESCE(${(0,Kd.arg)("value")} = 'NAN'::FLOAT, false)`)]}uv.fnIsNan=vhe;var Xd={};Object.defineProperty(Xd,"__esModule",{value:!0}),Xd.fnByteLength=Xd.fnLength=void 0;const Ws=pe;function She(){return[(0,Ws.overload)((0,Ws.minScalar)("number"),[(0,Ws.param)("value",(0,Ws.anyExprType)("string"))],(0,Ws.sql)`LENGTH(${(0,Ws.arg)("value")})`)]}Xd.fnLength=She;function _he(){return[(0,Ws.overload)((0,Ws.minScalar)("number"),[(0,Ws.param)("value",(0,Ws.anyExprType)("string"))],(0,Ws.sql)`CEIL(BIT_LENGTH(${(0,Ws.arg)("value")}) / 8)`)]}Xd.fnByteLength=_he;var av={};Object.defineProperty(av,"__esModule",{value:!0}),av.fnLog=void 0;const ff=pe;function Che(){const t=(0,ff.makeParam)("value",(0,ff.anyExprType)("number")),e=(0,ff.makeParam)("base",(0,ff.anyExprType)("number"));return[(0,ff.overload)((0,ff.minScalar)("number"),[t.param,e.param],(0,ff.sql)`LOG(${e.arg}, ${t.arg})`)]}av.fnLog=Che;var lv={};Object.defineProperty(lv,"__esModule",{value:!0}),lv.fnRand=void 0;const cO=pe;function The(){return[(0,cO.overload)((0,cO.minScalar)("number"),[],(0,cO.sql)`UNIFORM(0::FLOAT, 1::FLOAT, RANDOM())`)]}lv.fnRand=The;var cv={};Object.defineProperty(cv,"__esModule",{value:!0}),cv.fnRegexpExtract=void 0;const xf=pe;function bhe(){const t=(0,xf.makeParam)("value",(0,xf.anyExprType)("string")),e=(0,xf.makeParam)("pattern",(0,xf.anyExprType)("regular expression"));return[(0,xf.overload)((0,xf.minScalar)("string"),[t.param,e.param],(0,xf.sql)`REGEXP_SUBSTR(${t.arg}, ${e.arg}, 1, 1, 'e')`)]}cv.fnRegexpExtract=bhe;var Jd={};Object.defineProperty(Jd,"__esModule",{value:!0}),Jd.fnEndsWith=Jd.fnStartsWith=void 0;const qi=pe;function Rhe(){const t=(0,qi.makeParam)("value",(0,qi.anyExprType)("string")),e=(0,qi.makeParam)("prefix",(0,qi.anyExprType)("string"));return[(0,qi.overload)((0,qi.minScalar)("boolean"),[t.param,e.param],(0,qi.sql)`COALESCE(STARTSWITH(${t.arg}, ${e.arg}), false)`)]}Jd.fnStartsWith=Rhe;function Ohe(){const t=(0,qi.makeParam)("value",(0,qi.anyExprType)("string")),e=(0,qi.makeParam)("suffix",(0,qi.anyExprType)("string"));return[(0,qi.overload)((0,qi.minScalar)("boolean"),[t.param,e.param],(0,qi.sql)`COALESCE(ENDSWITH(${t.arg}, ${e.arg}), false)`)]}Jd.fnEndsWith=Ohe;var fv={};Object.defineProperty(fv,"__esModule",{value:!0}),fv.fnStrpos=void 0;const df=pe;function Nhe(){const t=(0,df.makeParam)("test_string",(0,df.anyExprType)("string")),e=(0,df.makeParam)("search_string",(0,df.anyExprType)("string"));return[(0,df.overload)((0,df.minScalar)("number"),[t.param,e.param],(0,df.sql)`POSITION(${e.arg}, ${t.arg})`)]}fv.fnStrpos=Nhe;var xv={};Object.defineProperty(xv,"__esModule",{value:!0}),xv.fnTrunc=void 0;const mu=pe;function Dhe(){const t=(0,mu.makeParam)("value",(0,mu.anyExprType)("number")),e=(0,mu.makeParam)("precision",(0,mu.anyExprType)("number"));return[(0,mu.overload)((0,mu.minScalar)("number"),[t.param],(0,mu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg}) ELSE FLOOR(${t.arg}) END`),(0,mu.overload)((0,mu.minScalar)("number"),[t.param,e.param],(0,mu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) ELSE FLOOR(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) END`)]}xv.fnTrunc=Dhe;var Zd={};Object.defineProperty(Zd,"__esModule",{value:!0}),Zd.fnStringAggDistinct=Zd.fnStringAgg=void 0;const Sn=pe;function Fhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`LISTAGG(${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`LISTAGG(${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Zd.fnStringAgg=Fhe;function whe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`LISTAGG(DISTINCT ${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`LISTAGG(DISTINCT ${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Zd.fnStringAggDistinct=whe,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;const e=Vc,n=iv,r=sv,i=ov,s=uv,o=Xd,u=av,a=lv,l=cv,c=Jd,f=fv,x=xv,h=Zd;t.SNOWFLAKE_FUNCTIONS=e.FUNCTIONS.clone(),t.SNOWFLAKE_FUNCTIONS.add("byte_length",o.fnByteLength),t.SNOWFLAKE_FUNCTIONS.add("chr",n.fnChr),t.SNOWFLAKE_FUNCTIONS.add("div",r.fnDiv),t.SNOWFLAKE_FUNCTIONS.add("is_inf",i.fnIsInf),t.SNOWFLAKE_FUNCTIONS.add("is_nan",s.fnIsNan),t.SNOWFLAKE_FUNCTIONS.add("length",o.fnLength),t.SNOWFLAKE_FUNCTIONS.add("log",u.fnLog),t.SNOWFLAKE_FUNCTIONS.add("rand",a.fnRand),t.SNOWFLAKE_FUNCTIONS.add("regexp_extract",l.fnRegexpExtract),t.SNOWFLAKE_FUNCTIONS.add("starts_with",c.fnStartsWith),t.SNOWFLAKE_FUNCTIONS.add("ends_with",c.fnEndsWith),t.SNOWFLAKE_FUNCTIONS.add("strpos",f.fnStrpos),t.SNOWFLAKE_FUNCTIONS.add("trunc",x.fnTrunc),t.SNOWFLAKE_FUNCTIONS.add("string_agg",h.fnStringAgg),t.SNOWFLAKE_FUNCTIONS.add("string_agg_distinct",h.fnStringAggDistinct),t.SNOWFLAKE_FUNCTIONS.seal()}(cM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;var e=cM;Object.defineProperty(t,"SNOWFLAKE_FUNCTIONS",{enumerable:!0,get:function(){return e.SNOWFLAKE_FUNCTIONS}})}(lM);var dv={};Object.defineProperty(dv,"__esModule",{value:!0}),dv.SNOWFLAKE_DIALECT_FUNCTIONS=void 0,dv.SNOWFLAKE_DIALECT_FUNCTIONS={},Object.defineProperty(rv,"__esModule",{value:!0}),rv.SnowflakeDialect=void 0;const Lhe=wt,fO=oe,fM=lM,sp=Wc,Ihe=dv,$he={day_of_week:"dayofweek",day_of_year:"dayofyear"},Bhe={varchar:{type:"string"},text:{type:"string"},string:{type:"string"},char:{type:"string"},character:{type:"string"},nvarchar:{type:"string"},nvarchar2:{type:"string"},"char varying":{type:"string"},"nchar varying":{type:"string"},number:{type:"number",numberType:"integer"},numeric:{type:"number",numberType:"integer"},decimal:{type:"number",numberType:"integer"},dec:{type:"number",numberType:"integer"},integer:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},byteint:{type:"number",numberType:"integer"},float:{type:"number",numberType:"float"},float4:{type:"number",numberType:"float"},float8:{type:"number",numberType:"float"},double:{type:"number",numberType:"float"},"double precision":{type:"number",numberType:"float"},real:{type:"number",numberType:"float"},boolean:{type:"boolean"},date:{type:"date"},timestamp:{type:"timestamp"},timestampntz:{type:"timestamp"},timestamp_ntz:{type:"timestamp"},"timestamp without time zone":{type:"timestamp"},timestamptz:{type:"timestamp"},timestamp_tz:{type:"timestamp"},"timestamp with time zone":{type:"timestamp"}};class khe extends sp.Dialect{constructor(){super(...arguments),this.name="snowflake",this.experimental=!1,this.defaultNumberType="NUMBER",this.defaultDecimalType="NUMBER",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.defaultSampling={rows:5e4},this.globalFunctions=fM.SNOWFLAKE_FUNCTIONS,this.unnestWithNumbers=!1,this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsPipelinesInViews=!1,this.supportsComplexFilteredSources=!1}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT index as group_set FROM TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, ${e+1}))))`}sqlAnyValue(e,n){return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN ${n} END) WITHIN GROUP (ORDER BY ${n} ASC NULLS LAST))[0]`}mapFields(e){return e.map(n=>`
|
|
158
158
|
${n.sqlExpression} as ${n.sqlOutputName}`).join(", ")}mapFieldsForObjectConstruct(e){return e.map(n=>`'${n.rawName}', (${n.sqlExpression})`).join(", ")}sqlAggregateTurtle(e,n,r,i){const s=this.mapFieldsForObjectConstruct(n),o=r?` WITHIN GROUP (${r})`:"",u=`ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${s}) END)${o}`;return i===void 0?`COALESCE(${u}, [])`:`COALESCE(ARRAY_SLICE(${u}, 0, ${i}), [])`}sqlAnyValueTurtle(e,n){const r=this.mapFieldsForObjectConstruct(n);return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${r}) END) WITHIN GROUP (ORDER BY 1 ASC NULLS LAST))[0]`}sqlAnyValueLastTurtle(e,n,r){return`(ARRAY_AGG(CASE WHEN group_set=${n} THEN ${e} END) WITHIN GROUP (ORDER BY ${e} ASC NULLS LAST))[0] AS ${r}`}sqlCoaleseMeasuresInline(e,n){const r=this.mapFieldsForObjectConstruct(n),i=n.map(s=>`'${s.sqlOutputName}', NULL`).join(", ");return`COALESCE(ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${r}) END)[0], OBJECT_CONSTRUCT_KEEP_NULL(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){return s?`,LATERAL FLATTEN(INPUT => ${e}) AS ${n}_1, LATERAL (SELECT ${n}_1.INDEX, object_construct('value', ${n}_1.value) as value ) as ${n}`:`LEFT JOIN LATERAL FLATTEN(INPUT => ifnull(${e},[1])) AS ${n}`}sqlSumDistinctHashedKey(e){e=`${e}::STRING`;const n=`to_number(substr(md5_hex(${e}), 1, 15), repeat('X', 15)) * 4294967296`,r=`to_number(substr(md5_hex(${e}), 16, 8), repeat('X', 8))`;return`(${n} + ${r})`}sqlSumDistinct(e,n,r){const i=this.sqlSumDistinctHashedKey(e),s=1e8,o=`(COALESCE(${n},0)*${s})`,u=`(SUM(DISTINCT ${i} + ${o}) - SUM(DISTINCT ${i}))/${s}`;if(r==="SUM")return u;if(r==="AVG")return`(${u})/NULLIF(COUNT(DISTINCT CASE WHEN ${n} IS NOT NULL THEN ${e} END),0)`;throw new Error(`Unknown Symmetric Aggregate function ${r}`)}sqlGenerateUUID(){return"UUID_STRING()"}sqlFieldReference(e,n,r,i,s){if(n==="__row_id")return`${e}.INDEX::varchar`;if(i){let o=r;return r==="string"?o="varchar":r==="struct"&&(o="variant"),`${e}.value:"${n}"::${o}`}else return`${e}."${n}"`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`TABLE(FLATTEN(input =>${r}))`}sqlCreateFunction(e,n){throw new Error("not implemented yet")}sqlCreateFunctionCombineLastStage(e){throw new Error("not implemented yet")}sqlSelectAliasAsStruct(e){return`OBJECT_CONSTRUCT_KEEP_NULL(${e}.*)`}sqlMaybeQuoteIdentifier(e){return`"${e}"`}sqlCreateTableAsSelect(e,n){return`
|
|
159
159
|
CREATE TEMP TABLE IF NOT EXISTS \`${e}\`
|
|
160
160
|
AS (
|
|
@@ -302,9 +302,9 @@ ${(0,fn.indent)(o)})
|
|
|
302
302
|
))
|
|
303
303
|
-
|
|
304
304
|
SUM(DISTINCT ${i})
|
|
305
|
-
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class ui{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return Sr(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class vu{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,et.isIndexSegment)(this.firstSegment)&&!(0,et.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new ui(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof ui}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof ui)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof ui&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof ui&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof ui&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(Sr(n.f))return"nested";n.f instanceof kr&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof vu&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof ui&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||r.f.fieldDef.type==="struct"||(0,et.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(AM(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.fieldDef.structRelationship;(0,et.isJoinOn)(c)&&e.parent&&c.onExpression!==void 0&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new R2e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>Sr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>Sr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>Sr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class b2e extends vu{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new fn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.fieldDef.structRelationship.type==="nested"?i=i.parent:i=void 0}}}class R2e{constructor(e,n,r){if(this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new E2e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this),this.queryStruct.fieldDef.filterList){this.joinFilterConditions=[];for(const i of this.queryStruct.fieldDef.filterList){const s=new mO({type:"boolean",name:"ignoreme",e:i.e},this.queryStruct);this.joinFilterConditions.push(s)}}}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";switch(this.queryStruct.fieldDef.structRelationship.type){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many";case"nested":return"one_to_many";case"inline":return"one_to_one";default:throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.fieldDef.name}`)}}forceAllSymmetricCalculations(){const e=this.queryStruct.fieldDef.structRelationship;return this.queryStruct.parent===void 0||!(0,et.isJoinOn)(e)?!1:e.matrixOperation==="right"||e.matrixOperation==="full"}getDialectFieldList(){return up(this.queryStruct.fieldDef)}}class _M extends Tv{}class O2e{static nextStructDef(e,n){const r=new kr(e,void 0,{model:new CM(void 0)}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Vs.makeQuery(i,r,new ap(!0,void 0),!1).getResultStructDef()}}mf.Segment=O2e;class Vs extends Tv{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new b2e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.fieldDef;switch(r!==void 0&&(0,et.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new kr({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model}),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),a.queryTimezone&&(0,et.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new N2e(o,s,r,i);case"project":return new D2e(o,s,r,i);case"index":return new L2e(o,s,r,i);case"raw":return new w2e(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof Tv)u=o.parent;else if(o instanceof kr)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,fn.exprWalk)(r)){if(o.node==="function_call"){(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,et.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,et.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,et.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,et.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,et.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof _M||s instanceof Vs){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new vu(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Br&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),AM(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new fn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,et.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,et.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof ui){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=n.code,o=[i];return bv(e.f)?(r=e.f.getFilterList(),{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"measure"}):Sr(e.f)?{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"dimension"}:void 0}return}else if(e instanceof vu){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,et.isRawSegment)(s)?void 0:s.limit;let u;if((0,et.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof vu){const{structDef:c}=this.generateTurtlePipelineSQL(a,new ap(!0,void 0),"<nosource>"),f=a.getRepeatedResultType()==="nested"?"nested":"inline";c.name=u,c.structRelationship={fieldName:u,type:f,isArray:!1},c.structSource={type:f},c.resultMetadata=l,r.push(c)}else if(a instanceof ui&&a.fieldUsage.type==="result"){a.f instanceof C2e&&r.push(a.f.getAsJoinedStructDef(u)),Sr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"date":{r.push({name:u,type:a.f.fieldDef.type,timeframe:a.f.fieldDef.timeframe,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={fields:r,name:this.resultStage||"result",dialect:this.parent.dialect.name,primaryKey:i,structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"},resultMetadata:this.getResultMetadata(this.rootResult),type:"struct",queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.fieldDef.modelAnnotation&&(o.modelAnnotation=this.parent.fieldDef.modelAnnotation),o}generateSQLJoinBlock(e,n){let r="";const i=n.queryStruct,s=i.fieldDef.structRelationship;let o=i.structSourceSQL(e);if((0,et.isJoinOn)(s)){const u=s.matrixOperation.toUpperCase();if(n.makeUniqueKey){const f=this.generateSQLPassthroughKeys(i);o=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${f} FROM ${o} as x)`}let a="";if(i.parent===void 0)throw new Error("Expected joined struct to have a parent.");s.onExpression?a=new mO({type:"boolean",name:"ignoreme",e:s.onExpression},i.parent).generateExpression(this.rootResult):a="1=1";let l="",c;if(n.joinFilterConditions&&(c=n.joinFilterConditions.map(f=>f.generateExpression(this.rootResult))),n.children.length===0||c===void 0)c!==void 0&&c.length>=1&&(l=` AND (${c.join(" AND ")})`),r+=` ${u} JOIN ${o} AS ${n.alias}
|
|
305
|
+
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class ui{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return Sr(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class vu{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,et.isIndexSegment)(this.firstSegment)&&!(0,et.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new ui(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof ui}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof ui)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof ui&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof ui&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof ui&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(Sr(n.f))return"nested";n.f instanceof kr&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof vu&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof ui&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||r.f.fieldDef.type==="struct"||(0,et.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(AM(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.fieldDef.structRelationship;(0,et.isJoinOn)(c)&&e.parent&&c.onExpression!==void 0&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new R2e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>Sr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>Sr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>Sr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class b2e extends vu{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new fn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.fieldDef.structRelationship.type==="nested"?i=i.parent:i=void 0}}}class R2e{constructor(e,n,r){if(this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new E2e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this),this.queryStruct.fieldDef.filterList){this.joinFilterConditions=[];for(const i of this.queryStruct.fieldDef.filterList){const s=new mO({type:"boolean",name:"ignoreme",e:i.e},this.queryStruct);this.joinFilterConditions.push(s)}}}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";switch(this.queryStruct.fieldDef.structRelationship.type){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many";case"nested":return"one_to_many";case"inline":return"one_to_one";default:throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.fieldDef.name}`)}}forceAllSymmetricCalculations(){const e=this.queryStruct.fieldDef.structRelationship;return this.queryStruct.parent===void 0||!(0,et.isJoinOn)(e)?!1:e.matrixOperation==="right"||e.matrixOperation==="full"}getDialectFieldList(){return up(this.queryStruct.fieldDef)}}class _M extends Tv{}class O2e{static nextStructDef(e,n){const r=new kr(e,void 0,{model:new CM(void 0)}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Vs.makeQuery(i,r,new ap(!0,void 0),!1).getResultStructDef()}}mf.Segment=O2e;class Vs extends Tv{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new b2e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.fieldDef;switch(r!==void 0&&(0,et.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new kr({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model}),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),a.queryTimezone&&(0,et.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new N2e(o,s,r,i);case"project":return new D2e(o,s,r,i);case"index":return new L2e(o,s,r,i);case"raw":return new w2e(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof Tv)u=o.parent;else if(o instanceof kr)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,fn.exprWalk)(r)){if(o.node==="function_call"){(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,et.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,et.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,et.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,et.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,et.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof _M||s instanceof Vs){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new vu(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Br&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),AM(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new fn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,et.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,et.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof ui){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=n.code,o=[i];return bv(e.f)?(r=e.f.getFilterList(),{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"measure"}):Sr(e.f)?{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"dimension"}:void 0}return}else if(e instanceof vu){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,et.isRawSegment)(s)?void 0:s.limit;let u;if((0,et.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof vu){const{structDef:c}=this.generateTurtlePipelineSQL(a,new ap(!0,void 0),"<nosource>"),f=a.getRepeatedResultType()==="nested"?"nested":"inline";c.name=u,c.structRelationship={fieldName:u,type:f,isArray:!1},c.structSource={type:f},c.resultMetadata=l,r.push(c)}else if(a instanceof ui&&a.fieldUsage.type==="result"){a.f instanceof C2e&&r.push(a.f.getAsJoinedStructDef(u)),Sr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"date":{r.push({name:u,type:a.f.fieldDef.type,timeframe:a.f.fieldDef.timeframe,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={fields:r,name:this.resultStage||"result",dialect:this.parent.dialect.name,primaryKey:i,structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"},resultMetadata:this.getResultMetadata(this.rootResult),type:"struct",queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.fieldDef.modelAnnotation&&(o.modelAnnotation=this.parent.fieldDef.modelAnnotation),o}generateSQLJoinBlock(e,n){let r="";const i=n.queryStruct,s=i.fieldDef.structRelationship;let o=i.structSourceSQL(e);if((0,et.isJoinOn)(s)){const u=s.matrixOperation.toUpperCase();if(n.makeUniqueKey){const f=this.generateSQLPassthroughKeys(i);o=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${f} FROM ${o} as x)`}let a="";if(i.parent===void 0)throw new Error("Expected joined struct to have a parent.");s.onExpression?a=new mO({type:"boolean",name:"ignoreme",e:s.onExpression},i.parent).generateExpression(this.rootResult):a="1=1";let l="",c;if(n.joinFilterConditions&&(c=n.joinFilterConditions.map(f=>f.generateExpression(this.rootResult))),n.children.length===0||c===void 0||!this.parent.dialect.supportsComplexFilteredSources)c!==void 0&&c.length>=1&&(l=` AND (${c.join(" AND ")})`),r+=` ${u} JOIN ${o} AS ${n.alias}
|
|
306
306
|
ON ${a}${l}
|
|
307
|
-
`;else{
|
|
307
|
+
`;else{let f=`SELECT ${n.alias}.*`,x="";for(const h of n.children)x+=this.generateSQLJoinBlock(e,h),f+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(h.alias,up(h.queryStruct.fieldDef))} AS ${h.alias}`;return f+=`
|
|
308
308
|
FROM ${o} AS ${n.alias}
|
|
309
309
|
${x}
|
|
310
310
|
WHERE ${c==null?void 0:c.join(" AND ")}
|
|
@@ -3229,7 +3229,7 @@ const y2e = $t, OR = le, GP = bV, E2e = j5, A2e = U5, v2e = {
|
|
|
3229
3229
|
};
|
|
3230
3230
|
class _2e extends E2e.PostgresBase {
|
|
3231
3231
|
constructor() {
|
|
3232
|
-
super(...arguments), this.name = "postgres", this.defaultNumberType = "DOUBLE PRECISION", this.defaultDecimalType = "NUMERIC", this.udfPrefix = "pg_temp.__udf", this.hasFinalStage = !0, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, 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.globalFunctions = GP.POSTGRES_FUNCTIONS, this.supportsNesting = !0, this.experimental = !1, this.readsNestedData = !1;
|
|
3232
|
+
super(...arguments), this.name = "postgres", this.defaultNumberType = "DOUBLE PRECISION", this.defaultDecimalType = "NUMERIC", this.udfPrefix = "pg_temp.__udf", this.hasFinalStage = !0, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, 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.globalFunctions = GP.POSTGRES_FUNCTIONS, this.supportsNesting = !0, this.experimental = !1, this.readsNestedData = !1, this.supportsComplexFilteredSources = !1;
|
|
3233
3233
|
}
|
|
3234
3234
|
quoteTablePath(e) {
|
|
3235
3235
|
return e.split(".").map((n) => `"${n}"`).join(".");
|
|
@@ -4098,7 +4098,7 @@ const o1e = $t, FR = le, YP = FV, Lp = rd, u1e = fC, a1e = {
|
|
|
4098
4098
|
};
|
|
4099
4099
|
class c1e extends Lp.Dialect {
|
|
4100
4100
|
constructor() {
|
|
4101
|
-
super(...arguments), this.name = "snowflake", this.experimental = !1, this.defaultNumberType = "NUMBER", this.defaultDecimalType = "NUMBER", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !1, this.supportsSumDistinctFunction = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.defaultSampling = { rows: 5e4 }, this.globalFunctions = YP.SNOWFLAKE_FUNCTIONS, this.unnestWithNumbers = !1, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !1, this.supportsQualify = !1, this.supportsPipelinesInViews = !1;
|
|
4101
|
+
super(...arguments), this.name = "snowflake", this.experimental = !1, this.defaultNumberType = "NUMBER", this.defaultDecimalType = "NUMBER", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !1, this.supportsSumDistinctFunction = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.defaultSampling = { rows: 5e4 }, this.globalFunctions = YP.SNOWFLAKE_FUNCTIONS, this.unnestWithNumbers = !1, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !1, this.supportsQualify = !1, this.supportsPipelinesInViews = !1, this.supportsComplexFilteredSources = !1;
|
|
4102
4102
|
}
|
|
4103
4103
|
// don't mess with the table pathing.
|
|
4104
4104
|
quoteTablePath(e) {
|
|
@@ -6262,13 +6262,11 @@ class co extends yS {
|
|
|
6262
6262
|
e: s.onExpression
|
|
6263
6263
|
}, i.parent).generateExpression(this.rootResult) : a = "1=1";
|
|
6264
6264
|
let l = "", c;
|
|
6265
|
-
if (n.joinFilterConditions && (c = n.joinFilterConditions.map((f) => f.generateExpression(this.rootResult))), n.children.length === 0 || c === void 0)
|
|
6265
|
+
if (n.joinFilterConditions && (c = n.joinFilterConditions.map((f) => f.generateExpression(this.rootResult))), n.children.length === 0 || c === void 0 || !this.parent.dialect.supportsComplexFilteredSources)
|
|
6266
6266
|
c !== void 0 && c.length >= 1 && (l = ` AND (${c.join(" AND ")})`), r += ` ${u} JOIN ${o} AS ${n.alias}
|
|
6267
6267
|
ON ${a}${l}
|
|
6268
6268
|
`;
|
|
6269
6269
|
else {
|
|
6270
|
-
if (!this.parent.dialect.supportsComplexFilteredSources)
|
|
6271
|
-
throw new Error("Cannot join a source with a filter on a joined source");
|
|
6272
6270
|
let f = `SELECT ${n.alias}.*`, x = "";
|
|
6273
6271
|
for (const h of n.children)
|
|
6274
6272
|
x += this.generateSQLJoinBlock(e, h), f += `, ${this.parent.dialect.sqlSelectAliasAsStruct(h.alias, km(h.queryStruct.fieldDef))} AS ${h.alias}`;
|
|
@@ -114,7 +114,7 @@ AS (
|
|
|
114
114
|
${(0,LM.indent)(n)}
|
|
115
115
|
);
|
|
116
116
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
117
|
-
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,n){const r=pv(e),i=r?`, "${r}"`:"";return n.e.dataType==="date"?Whe(n.units)?`DATE_TRUNC(${n.e.sql},${n.units})`:`TIMESTAMP(${n.e.sql}${i})`:`TIMESTAMP_TRUNC(${n.e.sql},${n.units}${i})`}sqlTimeExtractExpr(e,n){const r=Vhe[n.units]||n.units,i=n.e.dataType==="timestamp"&&pv(e),s=i?` AT TIME ZONE '${i}'`:"";return`EXTRACT(${r} FROM ${n.e.sql}${s})`}sqlAlterTimeExpr(e){const n=e.kids.base;let r=n.dataType,i=n.sql;e.units!=="day"&&IM(e.units)?r!=="timestamp"&&(i=`TIMESTAMP(${i})`,r="timestamp"):r==="timestamp"&&(i=`DATETIME(${i})`,r="datetime");const s=e.op==="+"?"_ADD":"_SUB",u=`${`${r.toUpperCase()}${s}`}(${i}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return r===n.dataType?u:`${n.dataType.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=pv(e),s=n.e.sql||"";if(r==="timestamp::date"&&i)return`DATE(${s},'${i}')`;if(r==="date::timestamp"&&i)return`TIMESTAMP(${s}, '${i}')`;if(n.srcType!==n.dstType){const o=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw;return`${n.safe?"SAFE_CAST":"CAST"}(${s} AS ${o})`}return s}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,n){if(n.dataType==="date")return`DATE('${n.literal}')`;if(n.dataType==="timestamp"){let r=`'${n.literal}'`;const i=n.timezone||pv(e);return i&&i!=="UTC"&&(r+=`,'${i}'`),`TIMESTAMP(${r})`}else throw new Error(`Unsupported Literal time format ${n.dataType}`)}sqlMeasureTimeExpr(e){const n={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},r=e.kids.left,i=e.kids.right;let s=r.sql,o=i.sql;if(n[e.units]){const{use:u,ratio:a}=n[e.units];if(!IM(u))throw new Error(`Measure in '${u} not implemented`);if(r.dataType!==i.dataType)throw new Error("Can't measure difference between different types");r.dataType==="date"&&(s=`TIMESTAMP(${s})`,o=`TIMESTAMP(${o})`);let l=`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,PR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,PR.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,PR.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${n.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return Hhe.STANDARDSQL_FUNCTIONS.get(e)}getDialectFunctions(){return Ghe.STANDARDSQL_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return Yhe[i.toUpperCase()]}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}Op.StandardSQLDialect=Khe,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(Op,t)}(_R);var MR={},gv={},$M={},BM={},oh={};Object.defineProperty(oh,"__esModule",{value:!0}),oh.fnStringAggDistinct=oh.fnStringAgg=void 0;const Sn=pe;function Xhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ','${n})`,{supportsOrderBy:!0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ${e.arg}${n})`,{supportsOrderBy:!0})]}oh.fnStringAgg=Xhe;function Jhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ','${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}oh.fnStringAggDistinct=Jhe;var mv={};Object.defineProperty(mv,"__esModule",{value:!0}),mv.fnByteLength=void 0;const uh=pe;function Zhe(){return[(0,uh.overload)((0,uh.minScalar)("number"),[(0,uh.param)("value",(0,uh.anyExprType)("string"))],(0,uh.sql)`OCTET_LENGTH(${(0,uh.arg)("value")})`)]}mv.fnByteLength=Zhe;var yv={};Object.defineProperty(yv,"__esModule",{value:!0}),yv.fnEndsWith=void 0;const yf=pe;function e2e(){const t=(0,yf.makeParam)("value",(0,yf.anyExprType)("string")),e=(0,yf.makeParam)("suffix",(0,yf.anyExprType)("string"));return[(0,yf.overload)((0,yf.minScalar)("boolean"),[t.param,e.param],(0,yf.sql)`COALESCE(RIGHT(${t.arg}, LENGTH(${e.arg})) = ${e.arg}, false)`)]}yv.fnEndsWith=e2e;var ah={};Object.defineProperty(ah,"__esModule",{value:!0}),ah.fnLeast=ah.fnGreatest=void 0;const Va=pe,t2e=["string","number","timestamp","date","json"];function kM(t){return t2e.map(e=>(0,Va.overload)((0,Va.minScalar)(e),[(0,Va.params)("values",(0,Va.anyExprType)(e))],(0,Va.sql)`CASE WHEN NUM_NULLS(${(0,Va.spread)((0,Va.arg)("values"))}) > 0 THEN NULL ELSE ${t}(${(0,Va.spread)((0,Va.arg)("values"))}) END`))}const n2e=()=>kM("GREATEST");ah.fnGreatest=n2e;const r2e=()=>kM("LEAST");ah.fnLeast=r2e;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.fnIfnull=void 0;const Ya=pe,i2e=["string","number","timestamp","date","json"];function s2e(){return i2e.map(t=>(0,Ya.overload)((0,Ya.minScalar)(t),[(0,Ya.param)("value",(0,Ya.anyExprType)(t)),(0,Ya.param)("default",(0,Ya.anyExprType)(t))],(0,Ya.sql)`COALESCE(${(0,Ya.arg)("value")}, ${(0,Ya.arg)("default")})`))}Ev.fnIfnull=s2e;var Av={};Object.defineProperty(Av,"__esModule",{value:!0}),Av.fnIsInf=void 0;const Lp=pe;function o2e(){const t=(0,Lp.makeParam)("value",(0,Lp.anyExprType)("number"));return[(0,Lp.overload)((0,Lp.minScalar)("boolean"),[t.param],(0,Lp.sql)`COALESCE(${t.arg} = DOUBLE PRECISION 'Infinity' OR ${t.arg} = DOUBLE PRECISION '-Infinity', false)`)]}Av.fnIsInf=o2e;var vv={};Object.defineProperty(vv,"__esModule",{value:!0}),vv.fnIsNan=void 0;const lh=pe;function u2e(){return[(0,lh.overload)((0,lh.minScalar)("boolean"),[(0,lh.param)("value",(0,lh.anyExprType)("number"))],(0,lh.sql)`COALESCE(${(0,lh.arg)("value")} = NUMERIC 'NaN', false)`)]}vv.fnIsNan=u2e;var Sv={};Object.defineProperty(Sv,"__esModule",{value:!0}),Sv.fnLog=void 0;const Ef=pe;function a2e(){const t=(0,Ef.makeParam)("value",(0,Ef.anyExprType)("number")),e=(0,Ef.makeParam)("base",(0,Ef.anyExprType)("number"));return[(0,Ef.overload)((0,Ef.minScalar)("number"),[t.param,e.param],(0,Ef.sql)`LOG(${e.arg}, ${t.arg})`)]}Sv.fnLog=a2e;var _v={};Object.defineProperty(_v,"__esModule",{value:!0}),_v.fnRand=void 0;const jR=pe;function l2e(){return[(0,jR.overload)((0,jR.minScalar)("number"),[],(0,jR.sql)`RANDOM()`)]}_v.fnRand=l2e;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.fnRegexpExtract=void 0;const Af=pe;function c2e(){const t=(0,Af.makeParam)("value",(0,Af.anyExprType)("string")),e=(0,Af.makeParam)("pattern",(0,Af.anyExprType)("regular expression"));return[(0,Af.overload)((0,Af.minScalar)("string"),[t.param,e.param],(0,Af.sql)`SUBSTRING(${t.arg}, ${e.arg})`)]}Cv.fnRegexpExtract=c2e;var bv={};Object.defineProperty(bv,"__esModule",{value:!0}),bv.fnReplace=void 0;const Hi=pe;function f2e(){const t=(0,Hi.makeParam)("value",(0,Hi.anyExprType)("string")),e=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("string")),n=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("regular expression")),r=(0,Hi.makeParam)("replacement",(0,Hi.anyExprType)("string"));return[(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,e.param,r.param],(0,Hi.sql)`REPLACE(${t.arg}, ${e.arg}, ${r.arg})`),(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,n.param,r.param],(0,Hi.sql)`REGEXP_REPLACE(${t.arg}, ${n.arg}, ${r.arg}, 'g')`)]}bv.fnReplace=f2e;var Tv={};Object.defineProperty(Tv,"__esModule",{value:!0}),Tv.fnRound=void 0;const Su=pe;function x2e(){const t=(0,Su.makeParam)("value",(0,Su.anyExprType)("number")),e=(0,Su.makeParam)("precision",(0,Su.anyExprType)("number"));return[(0,Su.overload)((0,Su.minScalar)("number"),[t.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC)`),(0,Su.overload)((0,Su.minScalar)("number"),[t.param,e.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC, ${e.arg})`)]}Tv.fnRound=x2e;var Ov={};Object.defineProperty(Ov,"__esModule",{value:!0}),Ov.fnStddev=void 0;const Ip=pe;function d2e(){const t=(0,Ip.makeParam)("value",(0,Ip.maxScalar)("number"));return[(0,Ip.overload)((0,Ip.minAggregate)("number"),[t.param],(0,Ip.sql)`STDDEV(${t.arg}::DOUBLE PRECISION)`)]}Ov.fnStddev=d2e;var Rv={};Object.defineProperty(Rv,"__esModule",{value:!0}),Rv.fnSubstr=void 0;const Ks=pe;function h2e(){const t=(0,Ks.makeParam)("value",(0,Ks.anyExprType)("string")),e=(0,Ks.makeParam)("position",(0,Ks.anyExprType)("number")),n=(0,Ks.makeParam)("length",(0,Ks.anyExprType)("number"));return[(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END)`),(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param,n.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END, ${n.arg})`)]}Rv.fnSubstr=h2e;var Nv={};Object.defineProperty(Nv,"__esModule",{value:!0}),Nv.fnTrunc=void 0;const _u=pe;function p2e(){const t=(0,_u.makeParam)("value",(0,_u.anyExprType)("number")),e=(0,_u.makeParam)("precision",(0,_u.anyExprType)("number"));return[(0,_u.overload)((0,_u.minScalar)("number"),[t.param],(0,_u.sql)`TRUNC(${t.arg}::NUMERIC)`),(0,_u.overload)((0,_u.minScalar)("number"),[t.param,e.param],(0,_u.sql)`TRUNC((${t.arg}::NUMERIC), ${e.arg})`)]}Nv.fnTrunc=p2e;var Dv={};Object.defineProperty(Dv,"__esModule",{value:!0}),Dv.fnUnicode=void 0;const ch=pe;function g2e(){return[(0,ch.overload)((0,ch.minScalar)("number"),[(0,ch.param)("value",(0,ch.anyExprType)("string"))],(0,ch.sql)`ASCII(${(0,ch.arg)("value")})`)]}Dv.fnUnicode=g2e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;const e=lf,n=oh,r=mv,i=yv,s=ah,o=Ev,u=Av,a=vv,l=Sv,c=_v,f=Cv,x=bv,h=Tv,p=Ov,m=Rv,g=Nv,y=Dv;t.POSTGRES_FUNCTIONS=e.FUNCTIONS.clone(),t.POSTGRES_FUNCTIONS.add("regexp_extract",f.fnRegexpExtract),t.POSTGRES_FUNCTIONS.add("stddev",p.fnStddev),t.POSTGRES_FUNCTIONS.add("rand",c.fnRand),t.POSTGRES_FUNCTIONS.add("greatest",s.fnGreatest),t.POSTGRES_FUNCTIONS.add("least",s.fnLeast),t.POSTGRES_FUNCTIONS.add("is_nan",a.fnIsNan),t.POSTGRES_FUNCTIONS.add("is_inf",u.fnIsInf),t.POSTGRES_FUNCTIONS.add("round",h.fnRound),t.POSTGRES_FUNCTIONS.add("byte_length",r.fnByteLength),t.POSTGRES_FUNCTIONS.add("unicode",y.fnUnicode),t.POSTGRES_FUNCTIONS.add("ifnull",o.fnIfnull),t.POSTGRES_FUNCTIONS.add("trunc",g.fnTrunc),t.POSTGRES_FUNCTIONS.add("substr",m.fnSubstr),t.POSTGRES_FUNCTIONS.add("replace",x.fnReplace),t.POSTGRES_FUNCTIONS.add("ends_with",i.fnEndsWith),t.POSTGRES_FUNCTIONS.add("string_agg",n.fnStringAgg),t.POSTGRES_FUNCTIONS.add("string_agg_distinct",n.fnStringAggDistinct),t.POSTGRES_FUNCTIONS.add("log",l.fnLog),t.POSTGRES_FUNCTIONS.seal()}(BM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;var e=BM;Object.defineProperty(t,"POSTGRES_FUNCTIONS",{enumerable:!0,get:function(){return e.POSTGRES_FUNCTIONS}})}($M);var Fv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=af;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class n extends e.Dialect{sqlTruncExpr(i,s){const o=s.units==="week",u=o?`${s.e.sql} + INTERVAL '1' DAY`:s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);if(l){const c=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`;let f=`DATE_TRUNC('${s.units}', ${c})`;return f=`${f}::TIMESTAMP`,`(${`${f} AT TIME ZONE '${l}'`})::TIMESTAMP`}}let a=`DATE_TRUNC('${s.units}', ${u})`;return o&&(a=`(${a} - INTERVAL '1' DAY)`),a}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(i,s){const o=t.timeExtractMap[s.units]||s.units;let u=s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);l&&(u=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`)}const a=`EXTRACT(${o} FROM ${u})`;return s.units==="day_of_week"?`mod(${a}+1,7)`:a}sqlCast(i,s){const o=s.e.sql||"",u=`${s.srcType}::${s.dstType}`,a=(0,e.qtz)(i);if(u==="timestamp::date"&&a)return`CAST((${`${o}::TIMESTAMPTZ`}) AT TIME ZONE '${a}' AS DATE)`;if(u==="date::timestamp"&&a)return`CAST((${o})::TIMESTAMP AT TIME ZONE '${a}' AS TIMESTAMP)`;if(s.srcType!==s.dstType){const l=typeof s.dstType=="string"?this.malloyTypeToSQLType({type:s.dstType}):s.dstType.raw;return`${s.safe?"TRY_CAST":"CAST"}(${o} AS ${l})`}return o}sqlRegexpMatch(i){return`${i.kids.expr.sql} ~ ${i.kids.regex.sql}`}sqlLiteralTime(i,s){if(s.dataType==="date")return`DATE '${s.literal}'`;const o=s.timezone||(0,e.qtz)(i);return o?`TIMESTAMPTZ '${s.literal} ${o}'::TIMESTAMP`:`TIMESTAMP '${s.literal}'`}}t.PostgresBase=n})(Fv);var wv={};Object.defineProperty(wv,"__esModule",{value:!0}),wv.POSTGRES_DIALECT_FUNCTIONS=void 0,wv.POSTGRES_DIALECT_FUNCTIONS={},Object.defineProperty(gv,"__esModule",{value:!0}),gv.PostgresDialect=void 0;const m2e=It,UR=le,PM=$M,y2e=Fv,E2e=wv,A2e={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},MM={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},v2e={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class S2e extends y2e.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,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.globalFunctions=PM.POSTGRES_FUNCTIONS,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1}quoteTablePath(e){return e.split(".").map(n=>`"${n}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,n){return`MAX(${n})`}mapFields(e){return e.map(n=>`
|
|
117
|
+
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,n){const r=pv(e),i=r?`, "${r}"`:"";return n.e.dataType==="date"?Whe(n.units)?`DATE_TRUNC(${n.e.sql},${n.units})`:`TIMESTAMP(${n.e.sql}${i})`:`TIMESTAMP_TRUNC(${n.e.sql},${n.units}${i})`}sqlTimeExtractExpr(e,n){const r=Vhe[n.units]||n.units,i=n.e.dataType==="timestamp"&&pv(e),s=i?` AT TIME ZONE '${i}'`:"";return`EXTRACT(${r} FROM ${n.e.sql}${s})`}sqlAlterTimeExpr(e){const n=e.kids.base;let r=n.dataType,i=n.sql;e.units!=="day"&&IM(e.units)?r!=="timestamp"&&(i=`TIMESTAMP(${i})`,r="timestamp"):r==="timestamp"&&(i=`DATETIME(${i})`,r="datetime");const s=e.op==="+"?"_ADD":"_SUB",u=`${`${r.toUpperCase()}${s}`}(${i}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return r===n.dataType?u:`${n.dataType.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=pv(e),s=n.e.sql||"";if(r==="timestamp::date"&&i)return`DATE(${s},'${i}')`;if(r==="date::timestamp"&&i)return`TIMESTAMP(${s}, '${i}')`;if(n.srcType!==n.dstType){const o=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw;return`${n.safe?"SAFE_CAST":"CAST"}(${s} AS ${o})`}return s}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,n){if(n.dataType==="date")return`DATE('${n.literal}')`;if(n.dataType==="timestamp"){let r=`'${n.literal}'`;const i=n.timezone||pv(e);return i&&i!=="UTC"&&(r+=`,'${i}'`),`TIMESTAMP(${r})`}else throw new Error(`Unsupported Literal time format ${n.dataType}`)}sqlMeasureTimeExpr(e){const n={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},r=e.kids.left,i=e.kids.right;let s=r.sql,o=i.sql;if(n[e.units]){const{use:u,ratio:a}=n[e.units];if(!IM(u))throw new Error(`Measure in '${u} not implemented`);if(r.dataType!==i.dataType)throw new Error("Can't measure difference between different types");r.dataType==="date"&&(s=`TIMESTAMP(${s})`,o=`TIMESTAMP(${o})`);let l=`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,PR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,PR.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,PR.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${n.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return Hhe.STANDARDSQL_FUNCTIONS.get(e)}getDialectFunctions(){return Ghe.STANDARDSQL_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return Yhe[i.toUpperCase()]}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}Op.StandardSQLDialect=Khe,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(Op,t)}(_R);var MR={},gv={},$M={},BM={},oh={};Object.defineProperty(oh,"__esModule",{value:!0}),oh.fnStringAggDistinct=oh.fnStringAgg=void 0;const Sn=pe;function Xhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ','${n})`,{supportsOrderBy:!0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ${e.arg}${n})`,{supportsOrderBy:!0})]}oh.fnStringAgg=Xhe;function Jhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ','${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}oh.fnStringAggDistinct=Jhe;var mv={};Object.defineProperty(mv,"__esModule",{value:!0}),mv.fnByteLength=void 0;const uh=pe;function Zhe(){return[(0,uh.overload)((0,uh.minScalar)("number"),[(0,uh.param)("value",(0,uh.anyExprType)("string"))],(0,uh.sql)`OCTET_LENGTH(${(0,uh.arg)("value")})`)]}mv.fnByteLength=Zhe;var yv={};Object.defineProperty(yv,"__esModule",{value:!0}),yv.fnEndsWith=void 0;const yf=pe;function e2e(){const t=(0,yf.makeParam)("value",(0,yf.anyExprType)("string")),e=(0,yf.makeParam)("suffix",(0,yf.anyExprType)("string"));return[(0,yf.overload)((0,yf.minScalar)("boolean"),[t.param,e.param],(0,yf.sql)`COALESCE(RIGHT(${t.arg}, LENGTH(${e.arg})) = ${e.arg}, false)`)]}yv.fnEndsWith=e2e;var ah={};Object.defineProperty(ah,"__esModule",{value:!0}),ah.fnLeast=ah.fnGreatest=void 0;const Va=pe,t2e=["string","number","timestamp","date","json"];function kM(t){return t2e.map(e=>(0,Va.overload)((0,Va.minScalar)(e),[(0,Va.params)("values",(0,Va.anyExprType)(e))],(0,Va.sql)`CASE WHEN NUM_NULLS(${(0,Va.spread)((0,Va.arg)("values"))}) > 0 THEN NULL ELSE ${t}(${(0,Va.spread)((0,Va.arg)("values"))}) END`))}const n2e=()=>kM("GREATEST");ah.fnGreatest=n2e;const r2e=()=>kM("LEAST");ah.fnLeast=r2e;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.fnIfnull=void 0;const Ya=pe,i2e=["string","number","timestamp","date","json"];function s2e(){return i2e.map(t=>(0,Ya.overload)((0,Ya.minScalar)(t),[(0,Ya.param)("value",(0,Ya.anyExprType)(t)),(0,Ya.param)("default",(0,Ya.anyExprType)(t))],(0,Ya.sql)`COALESCE(${(0,Ya.arg)("value")}, ${(0,Ya.arg)("default")})`))}Ev.fnIfnull=s2e;var Av={};Object.defineProperty(Av,"__esModule",{value:!0}),Av.fnIsInf=void 0;const Lp=pe;function o2e(){const t=(0,Lp.makeParam)("value",(0,Lp.anyExprType)("number"));return[(0,Lp.overload)((0,Lp.minScalar)("boolean"),[t.param],(0,Lp.sql)`COALESCE(${t.arg} = DOUBLE PRECISION 'Infinity' OR ${t.arg} = DOUBLE PRECISION '-Infinity', false)`)]}Av.fnIsInf=o2e;var vv={};Object.defineProperty(vv,"__esModule",{value:!0}),vv.fnIsNan=void 0;const lh=pe;function u2e(){return[(0,lh.overload)((0,lh.minScalar)("boolean"),[(0,lh.param)("value",(0,lh.anyExprType)("number"))],(0,lh.sql)`COALESCE(${(0,lh.arg)("value")} = NUMERIC 'NaN', false)`)]}vv.fnIsNan=u2e;var Sv={};Object.defineProperty(Sv,"__esModule",{value:!0}),Sv.fnLog=void 0;const Ef=pe;function a2e(){const t=(0,Ef.makeParam)("value",(0,Ef.anyExprType)("number")),e=(0,Ef.makeParam)("base",(0,Ef.anyExprType)("number"));return[(0,Ef.overload)((0,Ef.minScalar)("number"),[t.param,e.param],(0,Ef.sql)`LOG(${e.arg}, ${t.arg})`)]}Sv.fnLog=a2e;var _v={};Object.defineProperty(_v,"__esModule",{value:!0}),_v.fnRand=void 0;const jR=pe;function l2e(){return[(0,jR.overload)((0,jR.minScalar)("number"),[],(0,jR.sql)`RANDOM()`)]}_v.fnRand=l2e;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.fnRegexpExtract=void 0;const Af=pe;function c2e(){const t=(0,Af.makeParam)("value",(0,Af.anyExprType)("string")),e=(0,Af.makeParam)("pattern",(0,Af.anyExprType)("regular expression"));return[(0,Af.overload)((0,Af.minScalar)("string"),[t.param,e.param],(0,Af.sql)`SUBSTRING(${t.arg}, ${e.arg})`)]}Cv.fnRegexpExtract=c2e;var bv={};Object.defineProperty(bv,"__esModule",{value:!0}),bv.fnReplace=void 0;const Hi=pe;function f2e(){const t=(0,Hi.makeParam)("value",(0,Hi.anyExprType)("string")),e=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("string")),n=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("regular expression")),r=(0,Hi.makeParam)("replacement",(0,Hi.anyExprType)("string"));return[(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,e.param,r.param],(0,Hi.sql)`REPLACE(${t.arg}, ${e.arg}, ${r.arg})`),(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,n.param,r.param],(0,Hi.sql)`REGEXP_REPLACE(${t.arg}, ${n.arg}, ${r.arg}, 'g')`)]}bv.fnReplace=f2e;var Tv={};Object.defineProperty(Tv,"__esModule",{value:!0}),Tv.fnRound=void 0;const Su=pe;function x2e(){const t=(0,Su.makeParam)("value",(0,Su.anyExprType)("number")),e=(0,Su.makeParam)("precision",(0,Su.anyExprType)("number"));return[(0,Su.overload)((0,Su.minScalar)("number"),[t.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC)`),(0,Su.overload)((0,Su.minScalar)("number"),[t.param,e.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC, ${e.arg})`)]}Tv.fnRound=x2e;var Ov={};Object.defineProperty(Ov,"__esModule",{value:!0}),Ov.fnStddev=void 0;const Ip=pe;function d2e(){const t=(0,Ip.makeParam)("value",(0,Ip.maxScalar)("number"));return[(0,Ip.overload)((0,Ip.minAggregate)("number"),[t.param],(0,Ip.sql)`STDDEV(${t.arg}::DOUBLE PRECISION)`)]}Ov.fnStddev=d2e;var Rv={};Object.defineProperty(Rv,"__esModule",{value:!0}),Rv.fnSubstr=void 0;const Ks=pe;function h2e(){const t=(0,Ks.makeParam)("value",(0,Ks.anyExprType)("string")),e=(0,Ks.makeParam)("position",(0,Ks.anyExprType)("number")),n=(0,Ks.makeParam)("length",(0,Ks.anyExprType)("number"));return[(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END)`),(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param,n.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END, ${n.arg})`)]}Rv.fnSubstr=h2e;var Nv={};Object.defineProperty(Nv,"__esModule",{value:!0}),Nv.fnTrunc=void 0;const _u=pe;function p2e(){const t=(0,_u.makeParam)("value",(0,_u.anyExprType)("number")),e=(0,_u.makeParam)("precision",(0,_u.anyExprType)("number"));return[(0,_u.overload)((0,_u.minScalar)("number"),[t.param],(0,_u.sql)`TRUNC(${t.arg}::NUMERIC)`),(0,_u.overload)((0,_u.minScalar)("number"),[t.param,e.param],(0,_u.sql)`TRUNC((${t.arg}::NUMERIC), ${e.arg})`)]}Nv.fnTrunc=p2e;var Dv={};Object.defineProperty(Dv,"__esModule",{value:!0}),Dv.fnUnicode=void 0;const ch=pe;function g2e(){return[(0,ch.overload)((0,ch.minScalar)("number"),[(0,ch.param)("value",(0,ch.anyExprType)("string"))],(0,ch.sql)`ASCII(${(0,ch.arg)("value")})`)]}Dv.fnUnicode=g2e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;const e=lf,n=oh,r=mv,i=yv,s=ah,o=Ev,u=Av,a=vv,l=Sv,c=_v,f=Cv,x=bv,h=Tv,p=Ov,m=Rv,g=Nv,y=Dv;t.POSTGRES_FUNCTIONS=e.FUNCTIONS.clone(),t.POSTGRES_FUNCTIONS.add("regexp_extract",f.fnRegexpExtract),t.POSTGRES_FUNCTIONS.add("stddev",p.fnStddev),t.POSTGRES_FUNCTIONS.add("rand",c.fnRand),t.POSTGRES_FUNCTIONS.add("greatest",s.fnGreatest),t.POSTGRES_FUNCTIONS.add("least",s.fnLeast),t.POSTGRES_FUNCTIONS.add("is_nan",a.fnIsNan),t.POSTGRES_FUNCTIONS.add("is_inf",u.fnIsInf),t.POSTGRES_FUNCTIONS.add("round",h.fnRound),t.POSTGRES_FUNCTIONS.add("byte_length",r.fnByteLength),t.POSTGRES_FUNCTIONS.add("unicode",y.fnUnicode),t.POSTGRES_FUNCTIONS.add("ifnull",o.fnIfnull),t.POSTGRES_FUNCTIONS.add("trunc",g.fnTrunc),t.POSTGRES_FUNCTIONS.add("substr",m.fnSubstr),t.POSTGRES_FUNCTIONS.add("replace",x.fnReplace),t.POSTGRES_FUNCTIONS.add("ends_with",i.fnEndsWith),t.POSTGRES_FUNCTIONS.add("string_agg",n.fnStringAgg),t.POSTGRES_FUNCTIONS.add("string_agg_distinct",n.fnStringAggDistinct),t.POSTGRES_FUNCTIONS.add("log",l.fnLog),t.POSTGRES_FUNCTIONS.seal()}(BM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;var e=BM;Object.defineProperty(t,"POSTGRES_FUNCTIONS",{enumerable:!0,get:function(){return e.POSTGRES_FUNCTIONS}})}($M);var Fv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=af;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class n extends e.Dialect{sqlTruncExpr(i,s){const o=s.units==="week",u=o?`${s.e.sql} + INTERVAL '1' DAY`:s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);if(l){const c=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`;let f=`DATE_TRUNC('${s.units}', ${c})`;return f=`${f}::TIMESTAMP`,`(${`${f} AT TIME ZONE '${l}'`})::TIMESTAMP`}}let a=`DATE_TRUNC('${s.units}', ${u})`;return o&&(a=`(${a} - INTERVAL '1' DAY)`),a}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(i,s){const o=t.timeExtractMap[s.units]||s.units;let u=s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);l&&(u=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`)}const a=`EXTRACT(${o} FROM ${u})`;return s.units==="day_of_week"?`mod(${a}+1,7)`:a}sqlCast(i,s){const o=s.e.sql||"",u=`${s.srcType}::${s.dstType}`,a=(0,e.qtz)(i);if(u==="timestamp::date"&&a)return`CAST((${`${o}::TIMESTAMPTZ`}) AT TIME ZONE '${a}' AS DATE)`;if(u==="date::timestamp"&&a)return`CAST((${o})::TIMESTAMP AT TIME ZONE '${a}' AS TIMESTAMP)`;if(s.srcType!==s.dstType){const l=typeof s.dstType=="string"?this.malloyTypeToSQLType({type:s.dstType}):s.dstType.raw;return`${s.safe?"TRY_CAST":"CAST"}(${o} AS ${l})`}return o}sqlRegexpMatch(i){return`${i.kids.expr.sql} ~ ${i.kids.regex.sql}`}sqlLiteralTime(i,s){if(s.dataType==="date")return`DATE '${s.literal}'`;const o=s.timezone||(0,e.qtz)(i);return o?`TIMESTAMPTZ '${s.literal} ${o}'::TIMESTAMP`:`TIMESTAMP '${s.literal}'`}}t.PostgresBase=n})(Fv);var wv={};Object.defineProperty(wv,"__esModule",{value:!0}),wv.POSTGRES_DIALECT_FUNCTIONS=void 0,wv.POSTGRES_DIALECT_FUNCTIONS={},Object.defineProperty(gv,"__esModule",{value:!0}),gv.PostgresDialect=void 0;const m2e=It,UR=le,PM=$M,y2e=Fv,E2e=wv,A2e={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},MM={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},v2e={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class S2e extends y2e.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,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.globalFunctions=PM.POSTGRES_FUNCTIONS,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1}quoteTablePath(e){return e.split(".").map(n=>`"${n}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,n){return`MAX(${n})`}mapFields(e){return e.map(n=>`
|
|
118
118
|
${n.sqlExpression}${n.type==="number"?`::${this.defaultNumberType}`:""} as ${n.sqlOutputName}`).join(", ")}sqlAggregateTurtle(e,n,r,i){let s="";return i!==void 0&&(s+=`[1:${i}]`),`COALESCE(TO_JSONB((ARRAY_AGG((SELECT TO_JSONB(__x) FROM (SELECT ${this.mapFields(n)}
|
|
119
119
|
) as __x) ${r} ) FILTER (WHERE group_set=${e}))${s}),'[]'::JSONB)`}sqlAnyValueTurtle(e,n){const r=n.map(i=>`${i.sqlExpression} as ${i.sqlOutputName}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`(ARRAY_AGG(${e}) FILTER (WHERE group_set=${n} AND ${e} IS NOT NULL))[1] as ${r}`}sqlCoaleseMeasuresInline(e,n){return`TO_JSONB((ARRAY_AGG((SELECT __x FROM (SELECT ${this.mapFields(n)}) as __x)) FILTER (WHERE group_set=${e}))[1])`}sqlUnnestAlias(e,n,r,i,s,o){return s?i?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_id', row_number() over (), 'value', v) FROM UNNEST(${e}) as v))) as ${n} ON true`:`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('value', v) FROM UNNEST(${e}) as v))) as ${n} ON true`:i?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_number', row_number() over())|| __xx::jsonb as b FROM JSONB_ARRAY_ELEMENTS(${e}) __xx ))) as ${n} ON true`:`LEFT JOIN JSONB_ARRAY_ELEMENTS(${e}) as ${n} ON true`}sqlSumDistinctHashedKey(e){return`('x' || MD5(${e}::varchar))::bit(64)::bigint::DECIMAL(65,0) *18446744073709551616 + ('x' || SUBSTR(MD5(${e}::varchar),17))::bit(64)::bigint::DECIMAL(65,0)`}sqlGenerateUUID(){return"GEN_RANDOM_UUID()"}sqlFieldReference(e,n,r,i,s){let o=`(${e}->>'${n}')`;if(i){switch(r){case"string":break;case"number":o=`${o}::double precision`;break;case"struct":o=`${o}::jsonb`;break}return o}else return`${e}."${n}"`}sqlUnnestPipelineHead(e,n){return e?`UNNEST(ARRAY((SELECT ${n})))`:`JSONB_ARRAY_ELEMENTS(${n})`}sqlCreateFunction(e,n){return`CREATE FUNCTION ${e}(JSONB) RETURNS JSONB AS $$
|
|
120
120
|
${(0,m2e.indent)(n)}
|
|
@@ -154,7 +154,7 @@ ${zM}
|
|
|
154
154
|
FROM (
|
|
155
155
|
SELECT UNNEST(list(distinct {key:${e}, ${n.map((i,s)=>`val${s}: ${i}`).join(",")}})) a
|
|
156
156
|
)
|
|
157
|
-
)`}sqlSampleTable(e,n){if(n!==void 0){if((0,HR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,HR.isSamplingRows)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.rows})`;if((0,HR.isSamplingPercent)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.percent} PERCENT (bernoulli))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/'/g,"''")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getGlobalFunctionDef(e){return P2e.DUCKDB_FUNCTIONS.get(e)}getDialectFunctions(){return U2e.DUCKDB_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double precision":e.type==="string"?"varchar":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return q2e[i.toUpperCase()]}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlAlterTimeExpr(e){let n=e.units,r=e.kids.delta.sql;n==="quarter"?(n="month",r=`${r}*3`):n==="week"&&(n="day",r=`${r}*7`);const i=`INTERVAL (${r}) ${n}`;return`${e.kids.base.sql} ${e.op} ${i}`}sqlRegexpMatch(e){return`REGEXP_MATCHES(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlMeasureTimeExpr(e){const n=e.kids.left,r=e.kids.right;let i=n.sql||"",s=r.sql||"";return(0,M2e.inDays)(e.units)||(n.dataType==="date"&&(i=`${i}::TIMESTAMP`),r.dataType==="date"&&(s=`${s}::TIMESTAMP`)),`DATE_SUB('${e.units}', ${i}, ${s})`}}Lv.DuckDBDialect=z2e,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(Lv,t)}(qR);var QR={},Gv={},HM={},QM={},Wv={};Object.defineProperty(Wv,"__esModule",{value:!0}),Wv.fnChr=void 0;const Bp=pe;function H2e(){const t=(0,Bp.makeParam)("value",(0,Bp.anyExprType)("number"));return[(0,Bp.overload)((0,Bp.minScalar)("string"),[t.param],(0,Bp.sql)`COALESCE(CHR(${t.arg}), '')`)]}Wv.fnChr=H2e;var Vv={};Object.defineProperty(Vv,"__esModule",{value:!0}),Vv.fnDiv=void 0;const Cf=pe;function Q2e(){const t=(0,Cf.makeParam)("dividend",(0,Cf.anyExprType)("number")),e=(0,Cf.makeParam)("divisor",(0,Cf.anyExprType)("number"));return[(0,Cf.overload)((0,Cf.minScalar)("number"),[t.param,e.param],(0,Cf.sql)`CASE WHEN DIV0(${t.arg}, ${e.arg}) < 0 THEN CEIL(DIV0(${t.arg}, ${e.arg})) ELSE FLOOR(DIV0(${t.arg}, ${e.arg})) END`)]}Vv.fnDiv=Q2e;var Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.fnIsInf=void 0;const kp=pe;function G2e(){const t=(0,kp.makeParam)("value",(0,kp.anyExprType)("number"));return[(0,kp.overload)((0,kp.minScalar)("boolean"),[t.param],(0,kp.sql)`COALESCE(${t.arg} = 'inf'::FLOAT OR ${t.arg} = '-inf'::FLOAT, false)`)]}Yv.fnIsInf=G2e;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.fnIsNan=void 0;const gh=pe;function W2e(){return[(0,gh.overload)((0,gh.minScalar)("boolean"),[(0,gh.param)("value",(0,gh.anyExprType)("number"))],(0,gh.sql)`COALESCE(${(0,gh.arg)("value")} = 'NAN'::FLOAT, false)`)]}Kv.fnIsNan=W2e;var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.fnByteLength=mh.fnLength=void 0;const Xs=pe;function V2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`LENGTH(${(0,Xs.arg)("value")})`)]}mh.fnLength=V2e;function Y2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`CEIL(BIT_LENGTH(${(0,Xs.arg)("value")}) / 8)`)]}mh.fnByteLength=Y2e;var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0}),Xv.fnLog=void 0;const bf=pe;function K2e(){const t=(0,bf.makeParam)("value",(0,bf.anyExprType)("number")),e=(0,bf.makeParam)("base",(0,bf.anyExprType)("number"));return[(0,bf.overload)((0,bf.minScalar)("number"),[t.param,e.param],(0,bf.sql)`LOG(${e.arg}, ${t.arg})`)]}Xv.fnLog=K2e;var Jv={};Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.fnRand=void 0;const GR=pe;function X2e(){return[(0,GR.overload)((0,GR.minScalar)("number"),[],(0,GR.sql)`UNIFORM(0::FLOAT, 1::FLOAT, RANDOM())`)]}Jv.fnRand=X2e;var Zv={};Object.defineProperty(Zv,"__esModule",{value:!0}),Zv.fnRegexpExtract=void 0;const Tf=pe;function J2e(){const t=(0,Tf.makeParam)("value",(0,Tf.anyExprType)("string")),e=(0,Tf.makeParam)("pattern",(0,Tf.anyExprType)("regular expression"));return[(0,Tf.overload)((0,Tf.minScalar)("string"),[t.param,e.param],(0,Tf.sql)`REGEXP_SUBSTR(${t.arg}, ${e.arg}, 1, 1, 'e')`)]}Zv.fnRegexpExtract=J2e;var yh={};Object.defineProperty(yh,"__esModule",{value:!0}),yh.fnEndsWith=yh.fnStartsWith=void 0;const Gi=pe;function Z2e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("prefix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(STARTSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnStartsWith=Z2e;function e1e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("suffix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(ENDSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnEndsWith=e1e;var eS={};Object.defineProperty(eS,"__esModule",{value:!0}),eS.fnStrpos=void 0;const Of=pe;function t1e(){const t=(0,Of.makeParam)("test_string",(0,Of.anyExprType)("string")),e=(0,Of.makeParam)("search_string",(0,Of.anyExprType)("string"));return[(0,Of.overload)((0,Of.minScalar)("number"),[t.param,e.param],(0,Of.sql)`POSITION(${e.arg}, ${t.arg})`)]}eS.fnStrpos=t1e;var tS={};Object.defineProperty(tS,"__esModule",{value:!0}),tS.fnTrunc=void 0;const bu=pe;function n1e(){const t=(0,bu.makeParam)("value",(0,bu.anyExprType)("number")),e=(0,bu.makeParam)("precision",(0,bu.anyExprType)("number"));return[(0,bu.overload)((0,bu.minScalar)("number"),[t.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg}) ELSE FLOOR(${t.arg}) END`),(0,bu.overload)((0,bu.minScalar)("number"),[t.param,e.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) ELSE FLOOR(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) END`)]}tS.fnTrunc=n1e;var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.fnStringAggDistinct=Eh.fnStringAgg=void 0;const _n=pe;function r1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAgg=r1e;function i1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAggDistinct=i1e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;const e=lf,n=Wv,r=Vv,i=Yv,s=Kv,o=mh,u=Xv,a=Jv,l=Zv,c=yh,f=eS,x=tS,h=Eh;t.SNOWFLAKE_FUNCTIONS=e.FUNCTIONS.clone(),t.SNOWFLAKE_FUNCTIONS.add("byte_length",o.fnByteLength),t.SNOWFLAKE_FUNCTIONS.add("chr",n.fnChr),t.SNOWFLAKE_FUNCTIONS.add("div",r.fnDiv),t.SNOWFLAKE_FUNCTIONS.add("is_inf",i.fnIsInf),t.SNOWFLAKE_FUNCTIONS.add("is_nan",s.fnIsNan),t.SNOWFLAKE_FUNCTIONS.add("length",o.fnLength),t.SNOWFLAKE_FUNCTIONS.add("log",u.fnLog),t.SNOWFLAKE_FUNCTIONS.add("rand",a.fnRand),t.SNOWFLAKE_FUNCTIONS.add("regexp_extract",l.fnRegexpExtract),t.SNOWFLAKE_FUNCTIONS.add("starts_with",c.fnStartsWith),t.SNOWFLAKE_FUNCTIONS.add("ends_with",c.fnEndsWith),t.SNOWFLAKE_FUNCTIONS.add("strpos",f.fnStrpos),t.SNOWFLAKE_FUNCTIONS.add("trunc",x.fnTrunc),t.SNOWFLAKE_FUNCTIONS.add("string_agg",h.fnStringAgg),t.SNOWFLAKE_FUNCTIONS.add("string_agg_distinct",h.fnStringAggDistinct),t.SNOWFLAKE_FUNCTIONS.seal()}(QM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;var e=QM;Object.defineProperty(t,"SNOWFLAKE_FUNCTIONS",{enumerable:!0,get:function(){return e.SNOWFLAKE_FUNCTIONS}})}(HM);var nS={};Object.defineProperty(nS,"__esModule",{value:!0}),nS.SNOWFLAKE_DIALECT_FUNCTIONS=void 0,nS.SNOWFLAKE_DIALECT_FUNCTIONS={},Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.SnowflakeDialect=void 0;const s1e=It,WR=le,GM=HM,Pp=af,o1e=nS,u1e={day_of_week:"dayofweek",day_of_year:"dayofyear"},a1e={varchar:{type:"string"},text:{type:"string"},string:{type:"string"},char:{type:"string"},character:{type:"string"},nvarchar:{type:"string"},nvarchar2:{type:"string"},"char varying":{type:"string"},"nchar varying":{type:"string"},number:{type:"number",numberType:"integer"},numeric:{type:"number",numberType:"integer"},decimal:{type:"number",numberType:"integer"},dec:{type:"number",numberType:"integer"},integer:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},byteint:{type:"number",numberType:"integer"},float:{type:"number",numberType:"float"},float4:{type:"number",numberType:"float"},float8:{type:"number",numberType:"float"},double:{type:"number",numberType:"float"},"double precision":{type:"number",numberType:"float"},real:{type:"number",numberType:"float"},boolean:{type:"boolean"},date:{type:"date"},timestamp:{type:"timestamp"},timestampntz:{type:"timestamp"},timestamp_ntz:{type:"timestamp"},"timestamp without time zone":{type:"timestamp"},timestamptz:{type:"timestamp"},timestamp_tz:{type:"timestamp"},"timestamp with time zone":{type:"timestamp"}};class l1e extends Pp.Dialect{constructor(){super(...arguments),this.name="snowflake",this.experimental=!1,this.defaultNumberType="NUMBER",this.defaultDecimalType="NUMBER",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.defaultSampling={rows:5e4},this.globalFunctions=GM.SNOWFLAKE_FUNCTIONS,this.unnestWithNumbers=!1,this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsPipelinesInViews=!1}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT index as group_set FROM TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, ${e+1}))))`}sqlAnyValue(e,n){return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN ${n} END) WITHIN GROUP (ORDER BY ${n} ASC NULLS LAST))[0]`}mapFields(e){return e.map(n=>`
|
|
157
|
+
)`}sqlSampleTable(e,n){if(n!==void 0){if((0,HR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,HR.isSamplingRows)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.rows})`;if((0,HR.isSamplingPercent)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.percent} PERCENT (bernoulli))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/'/g,"''")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getGlobalFunctionDef(e){return P2e.DUCKDB_FUNCTIONS.get(e)}getDialectFunctions(){return U2e.DUCKDB_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double precision":e.type==="string"?"varchar":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return q2e[i.toUpperCase()]}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlAlterTimeExpr(e){let n=e.units,r=e.kids.delta.sql;n==="quarter"?(n="month",r=`${r}*3`):n==="week"&&(n="day",r=`${r}*7`);const i=`INTERVAL (${r}) ${n}`;return`${e.kids.base.sql} ${e.op} ${i}`}sqlRegexpMatch(e){return`REGEXP_MATCHES(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlMeasureTimeExpr(e){const n=e.kids.left,r=e.kids.right;let i=n.sql||"",s=r.sql||"";return(0,M2e.inDays)(e.units)||(n.dataType==="date"&&(i=`${i}::TIMESTAMP`),r.dataType==="date"&&(s=`${s}::TIMESTAMP`)),`DATE_SUB('${e.units}', ${i}, ${s})`}}Lv.DuckDBDialect=z2e,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(Lv,t)}(qR);var QR={},Gv={},HM={},QM={},Wv={};Object.defineProperty(Wv,"__esModule",{value:!0}),Wv.fnChr=void 0;const Bp=pe;function H2e(){const t=(0,Bp.makeParam)("value",(0,Bp.anyExprType)("number"));return[(0,Bp.overload)((0,Bp.minScalar)("string"),[t.param],(0,Bp.sql)`COALESCE(CHR(${t.arg}), '')`)]}Wv.fnChr=H2e;var Vv={};Object.defineProperty(Vv,"__esModule",{value:!0}),Vv.fnDiv=void 0;const Cf=pe;function Q2e(){const t=(0,Cf.makeParam)("dividend",(0,Cf.anyExprType)("number")),e=(0,Cf.makeParam)("divisor",(0,Cf.anyExprType)("number"));return[(0,Cf.overload)((0,Cf.minScalar)("number"),[t.param,e.param],(0,Cf.sql)`CASE WHEN DIV0(${t.arg}, ${e.arg}) < 0 THEN CEIL(DIV0(${t.arg}, ${e.arg})) ELSE FLOOR(DIV0(${t.arg}, ${e.arg})) END`)]}Vv.fnDiv=Q2e;var Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.fnIsInf=void 0;const kp=pe;function G2e(){const t=(0,kp.makeParam)("value",(0,kp.anyExprType)("number"));return[(0,kp.overload)((0,kp.minScalar)("boolean"),[t.param],(0,kp.sql)`COALESCE(${t.arg} = 'inf'::FLOAT OR ${t.arg} = '-inf'::FLOAT, false)`)]}Yv.fnIsInf=G2e;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.fnIsNan=void 0;const gh=pe;function W2e(){return[(0,gh.overload)((0,gh.minScalar)("boolean"),[(0,gh.param)("value",(0,gh.anyExprType)("number"))],(0,gh.sql)`COALESCE(${(0,gh.arg)("value")} = 'NAN'::FLOAT, false)`)]}Kv.fnIsNan=W2e;var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.fnByteLength=mh.fnLength=void 0;const Xs=pe;function V2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`LENGTH(${(0,Xs.arg)("value")})`)]}mh.fnLength=V2e;function Y2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`CEIL(BIT_LENGTH(${(0,Xs.arg)("value")}) / 8)`)]}mh.fnByteLength=Y2e;var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0}),Xv.fnLog=void 0;const bf=pe;function K2e(){const t=(0,bf.makeParam)("value",(0,bf.anyExprType)("number")),e=(0,bf.makeParam)("base",(0,bf.anyExprType)("number"));return[(0,bf.overload)((0,bf.minScalar)("number"),[t.param,e.param],(0,bf.sql)`LOG(${e.arg}, ${t.arg})`)]}Xv.fnLog=K2e;var Jv={};Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.fnRand=void 0;const GR=pe;function X2e(){return[(0,GR.overload)((0,GR.minScalar)("number"),[],(0,GR.sql)`UNIFORM(0::FLOAT, 1::FLOAT, RANDOM())`)]}Jv.fnRand=X2e;var Zv={};Object.defineProperty(Zv,"__esModule",{value:!0}),Zv.fnRegexpExtract=void 0;const Tf=pe;function J2e(){const t=(0,Tf.makeParam)("value",(0,Tf.anyExprType)("string")),e=(0,Tf.makeParam)("pattern",(0,Tf.anyExprType)("regular expression"));return[(0,Tf.overload)((0,Tf.minScalar)("string"),[t.param,e.param],(0,Tf.sql)`REGEXP_SUBSTR(${t.arg}, ${e.arg}, 1, 1, 'e')`)]}Zv.fnRegexpExtract=J2e;var yh={};Object.defineProperty(yh,"__esModule",{value:!0}),yh.fnEndsWith=yh.fnStartsWith=void 0;const Gi=pe;function Z2e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("prefix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(STARTSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnStartsWith=Z2e;function e1e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("suffix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(ENDSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnEndsWith=e1e;var eS={};Object.defineProperty(eS,"__esModule",{value:!0}),eS.fnStrpos=void 0;const Of=pe;function t1e(){const t=(0,Of.makeParam)("test_string",(0,Of.anyExprType)("string")),e=(0,Of.makeParam)("search_string",(0,Of.anyExprType)("string"));return[(0,Of.overload)((0,Of.minScalar)("number"),[t.param,e.param],(0,Of.sql)`POSITION(${e.arg}, ${t.arg})`)]}eS.fnStrpos=t1e;var tS={};Object.defineProperty(tS,"__esModule",{value:!0}),tS.fnTrunc=void 0;const bu=pe;function n1e(){const t=(0,bu.makeParam)("value",(0,bu.anyExprType)("number")),e=(0,bu.makeParam)("precision",(0,bu.anyExprType)("number"));return[(0,bu.overload)((0,bu.minScalar)("number"),[t.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg}) ELSE FLOOR(${t.arg}) END`),(0,bu.overload)((0,bu.minScalar)("number"),[t.param,e.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) ELSE FLOOR(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) END`)]}tS.fnTrunc=n1e;var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.fnStringAggDistinct=Eh.fnStringAgg=void 0;const _n=pe;function r1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAgg=r1e;function i1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAggDistinct=i1e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;const e=lf,n=Wv,r=Vv,i=Yv,s=Kv,o=mh,u=Xv,a=Jv,l=Zv,c=yh,f=eS,x=tS,h=Eh;t.SNOWFLAKE_FUNCTIONS=e.FUNCTIONS.clone(),t.SNOWFLAKE_FUNCTIONS.add("byte_length",o.fnByteLength),t.SNOWFLAKE_FUNCTIONS.add("chr",n.fnChr),t.SNOWFLAKE_FUNCTIONS.add("div",r.fnDiv),t.SNOWFLAKE_FUNCTIONS.add("is_inf",i.fnIsInf),t.SNOWFLAKE_FUNCTIONS.add("is_nan",s.fnIsNan),t.SNOWFLAKE_FUNCTIONS.add("length",o.fnLength),t.SNOWFLAKE_FUNCTIONS.add("log",u.fnLog),t.SNOWFLAKE_FUNCTIONS.add("rand",a.fnRand),t.SNOWFLAKE_FUNCTIONS.add("regexp_extract",l.fnRegexpExtract),t.SNOWFLAKE_FUNCTIONS.add("starts_with",c.fnStartsWith),t.SNOWFLAKE_FUNCTIONS.add("ends_with",c.fnEndsWith),t.SNOWFLAKE_FUNCTIONS.add("strpos",f.fnStrpos),t.SNOWFLAKE_FUNCTIONS.add("trunc",x.fnTrunc),t.SNOWFLAKE_FUNCTIONS.add("string_agg",h.fnStringAgg),t.SNOWFLAKE_FUNCTIONS.add("string_agg_distinct",h.fnStringAggDistinct),t.SNOWFLAKE_FUNCTIONS.seal()}(QM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;var e=QM;Object.defineProperty(t,"SNOWFLAKE_FUNCTIONS",{enumerable:!0,get:function(){return e.SNOWFLAKE_FUNCTIONS}})}(HM);var nS={};Object.defineProperty(nS,"__esModule",{value:!0}),nS.SNOWFLAKE_DIALECT_FUNCTIONS=void 0,nS.SNOWFLAKE_DIALECT_FUNCTIONS={},Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.SnowflakeDialect=void 0;const s1e=It,WR=le,GM=HM,Pp=af,o1e=nS,u1e={day_of_week:"dayofweek",day_of_year:"dayofyear"},a1e={varchar:{type:"string"},text:{type:"string"},string:{type:"string"},char:{type:"string"},character:{type:"string"},nvarchar:{type:"string"},nvarchar2:{type:"string"},"char varying":{type:"string"},"nchar varying":{type:"string"},number:{type:"number",numberType:"integer"},numeric:{type:"number",numberType:"integer"},decimal:{type:"number",numberType:"integer"},dec:{type:"number",numberType:"integer"},integer:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},byteint:{type:"number",numberType:"integer"},float:{type:"number",numberType:"float"},float4:{type:"number",numberType:"float"},float8:{type:"number",numberType:"float"},double:{type:"number",numberType:"float"},"double precision":{type:"number",numberType:"float"},real:{type:"number",numberType:"float"},boolean:{type:"boolean"},date:{type:"date"},timestamp:{type:"timestamp"},timestampntz:{type:"timestamp"},timestamp_ntz:{type:"timestamp"},"timestamp without time zone":{type:"timestamp"},timestamptz:{type:"timestamp"},timestamp_tz:{type:"timestamp"},"timestamp with time zone":{type:"timestamp"}};class l1e extends Pp.Dialect{constructor(){super(...arguments),this.name="snowflake",this.experimental=!1,this.defaultNumberType="NUMBER",this.defaultDecimalType="NUMBER",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.defaultSampling={rows:5e4},this.globalFunctions=GM.SNOWFLAKE_FUNCTIONS,this.unnestWithNumbers=!1,this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsPipelinesInViews=!1,this.supportsComplexFilteredSources=!1}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT index as group_set FROM TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, ${e+1}))))`}sqlAnyValue(e,n){return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN ${n} END) WITHIN GROUP (ORDER BY ${n} ASC NULLS LAST))[0]`}mapFields(e){return e.map(n=>`
|
|
158
158
|
${n.sqlExpression} as ${n.sqlOutputName}`).join(", ")}mapFieldsForObjectConstruct(e){return e.map(n=>`'${n.rawName}', (${n.sqlExpression})`).join(", ")}sqlAggregateTurtle(e,n,r,i){const s=this.mapFieldsForObjectConstruct(n),o=r?` WITHIN GROUP (${r})`:"",u=`ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${s}) END)${o}`;return i===void 0?`COALESCE(${u}, [])`:`COALESCE(ARRAY_SLICE(${u}, 0, ${i}), [])`}sqlAnyValueTurtle(e,n){const r=this.mapFieldsForObjectConstruct(n);return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${r}) END) WITHIN GROUP (ORDER BY 1 ASC NULLS LAST))[0]`}sqlAnyValueLastTurtle(e,n,r){return`(ARRAY_AGG(CASE WHEN group_set=${n} THEN ${e} END) WITHIN GROUP (ORDER BY ${e} ASC NULLS LAST))[0] AS ${r}`}sqlCoaleseMeasuresInline(e,n){const r=this.mapFieldsForObjectConstruct(n),i=n.map(s=>`'${s.sqlOutputName}', NULL`).join(", ");return`COALESCE(ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${r}) END)[0], OBJECT_CONSTRUCT_KEEP_NULL(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){return s?`,LATERAL FLATTEN(INPUT => ${e}) AS ${n}_1, LATERAL (SELECT ${n}_1.INDEX, object_construct('value', ${n}_1.value) as value ) as ${n}`:`LEFT JOIN LATERAL FLATTEN(INPUT => ifnull(${e},[1])) AS ${n}`}sqlSumDistinctHashedKey(e){e=`${e}::STRING`;const n=`to_number(substr(md5_hex(${e}), 1, 15), repeat('X', 15)) * 4294967296`,r=`to_number(substr(md5_hex(${e}), 16, 8), repeat('X', 8))`;return`(${n} + ${r})`}sqlSumDistinct(e,n,r){const i=this.sqlSumDistinctHashedKey(e),s=1e8,o=`(COALESCE(${n},0)*${s})`,u=`(SUM(DISTINCT ${i} + ${o}) - SUM(DISTINCT ${i}))/${s}`;if(r==="SUM")return u;if(r==="AVG")return`(${u})/NULLIF(COUNT(DISTINCT CASE WHEN ${n} IS NOT NULL THEN ${e} END),0)`;throw new Error(`Unknown Symmetric Aggregate function ${r}`)}sqlGenerateUUID(){return"UUID_STRING()"}sqlFieldReference(e,n,r,i,s){if(n==="__row_id")return`${e}.INDEX::varchar`;if(i){let o=r;return r==="string"?o="varchar":r==="struct"&&(o="variant"),`${e}.value:"${n}"::${o}`}else return`${e}."${n}"`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`TABLE(FLATTEN(input =>${r}))`}sqlCreateFunction(e,n){throw new Error("not implemented yet")}sqlCreateFunctionCombineLastStage(e){throw new Error("not implemented yet")}sqlSelectAliasAsStruct(e){return`OBJECT_CONSTRUCT_KEEP_NULL(${e}.*)`}sqlMaybeQuoteIdentifier(e){return`"${e}"`}sqlCreateTableAsSelect(e,n){return`
|
|
159
159
|
CREATE TEMP TABLE IF NOT EXISTS \`${e}\`
|
|
160
160
|
AS (
|
|
@@ -302,9 +302,9 @@ ${(0,fn.indent)(o)})
|
|
|
302
302
|
))
|
|
303
303
|
-
|
|
304
304
|
SUM(DISTINCT ${i})
|
|
305
|
-
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class fi{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return Cr(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class Nu{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,et.isIndexSegment)(this.firstSegment)&&!(0,et.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new fi(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof fi}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof fi)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof fi&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof fi&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(Cr(n.f))return"nested";n.f instanceof Ur&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof Nu&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||r.f.fieldDef.type==="struct"||(0,et.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(tj(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.fieldDef.structRelationship;(0,et.isJoinOn)(c)&&e.parent&&c.onExpression!==void 0&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>Cr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class J1e extends Nu{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new fn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.fieldDef.structRelationship.type==="nested"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){if(this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new Q1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this),this.queryStruct.fieldDef.filterList){this.joinFilterConditions=[];for(const i of this.queryStruct.fieldDef.filterList){const s=new ZR({type:"boolean",name:"ignoreme",e:i.e},this.queryStruct);this.joinFilterConditions.push(s)}}}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";switch(this.queryStruct.fieldDef.structRelationship.type){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many";case"nested":return"one_to_many";case"inline":return"one_to_one";default:throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.fieldDef.name}`)}}forceAllSymmetricCalculations(){const e=this.queryStruct.fieldDef.structRelationship;return this.queryStruct.parent===void 0||!(0,et.isJoinOn)(e)?!1:e.matrixOperation==="right"||e.matrixOperation==="full"}getDialectFieldList(){return jp(this.queryStruct.fieldDef)}}class ij extends hS{}class epe{static nextStructDef(e,n){const r=new Ur(e,void 0,{model:new sj(void 0)}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Js.makeQuery(i,r,new Up(!0,void 0),!1).getResultStructDef()}}Ff.Segment=epe;class Js extends hS{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new J1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.fieldDef;switch(r!==void 0&&(0,et.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Ur({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model}),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),a.queryTimezone&&(0,et.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tpe(o,s,r,i);case"project":return new npe(o,s,r,i);case"index":return new spe(o,s,r,i);case"raw":return new ipe(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof hS)u=o.parent;else if(o instanceof Ur)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,fn.exprWalk)(r)){if(o.node==="function_call"){(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,et.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,et.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,et.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,et.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,et.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof ij||s instanceof Js){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new Nu(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof jr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),tj(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new fn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,et.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,et.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof fi){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=n.code,o=[i];return pS(e.f)?(r=e.f.getFilterList(),{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"measure"}):Cr(e.f)?{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"dimension"}:void 0}return}else if(e instanceof Nu){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,et.isRawSegment)(s)?void 0:s.limit;let u;if((0,et.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof Nu){const{structDef:c}=this.generateTurtlePipelineSQL(a,new Up(!0,void 0),"<nosource>"),f=a.getRepeatedResultType()==="nested"?"nested":"inline";c.name=u,c.structRelationship={fieldName:u,type:f,isArray:!1},c.structSource={type:f},c.resultMetadata=l,r.push(c)}else if(a instanceof fi&&a.fieldUsage.type==="result"){a.f instanceof K1e&&r.push(a.f.getAsJoinedStructDef(u)),Cr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"date":{r.push({name:u,type:a.f.fieldDef.type,timeframe:a.f.fieldDef.timeframe,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={fields:r,name:this.resultStage||"result",dialect:this.parent.dialect.name,primaryKey:i,structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"},resultMetadata:this.getResultMetadata(this.rootResult),type:"struct",queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.fieldDef.modelAnnotation&&(o.modelAnnotation=this.parent.fieldDef.modelAnnotation),o}generateSQLJoinBlock(e,n){let r="";const i=n.queryStruct,s=i.fieldDef.structRelationship;let o=i.structSourceSQL(e);if((0,et.isJoinOn)(s)){const u=s.matrixOperation.toUpperCase();if(n.makeUniqueKey){const f=this.generateSQLPassthroughKeys(i);o=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${f} FROM ${o} as x)`}let a="";if(i.parent===void 0)throw new Error("Expected joined struct to have a parent.");s.onExpression?a=new ZR({type:"boolean",name:"ignoreme",e:s.onExpression},i.parent).generateExpression(this.rootResult):a="1=1";let l="",c;if(n.joinFilterConditions&&(c=n.joinFilterConditions.map(f=>f.generateExpression(this.rootResult))),n.children.length===0||c===void 0)c!==void 0&&c.length>=1&&(l=` AND (${c.join(" AND ")})`),r+=` ${u} JOIN ${o} AS ${n.alias}
|
|
305
|
+
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class fi{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return Cr(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class Nu{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,et.isIndexSegment)(this.firstSegment)&&!(0,et.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new fi(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof fi}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof fi)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof fi&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof fi&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(Cr(n.f))return"nested";n.f instanceof Ur&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof Nu&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||r.f.fieldDef.type==="struct"||(0,et.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(tj(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.fieldDef.structRelationship;(0,et.isJoinOn)(c)&&e.parent&&c.onExpression!==void 0&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>Cr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class J1e extends Nu{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new fn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.fieldDef.structRelationship.type==="nested"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){if(this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new Q1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this),this.queryStruct.fieldDef.filterList){this.joinFilterConditions=[];for(const i of this.queryStruct.fieldDef.filterList){const s=new ZR({type:"boolean",name:"ignoreme",e:i.e},this.queryStruct);this.joinFilterConditions.push(s)}}}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";switch(this.queryStruct.fieldDef.structRelationship.type){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many";case"nested":return"one_to_many";case"inline":return"one_to_one";default:throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.fieldDef.name}`)}}forceAllSymmetricCalculations(){const e=this.queryStruct.fieldDef.structRelationship;return this.queryStruct.parent===void 0||!(0,et.isJoinOn)(e)?!1:e.matrixOperation==="right"||e.matrixOperation==="full"}getDialectFieldList(){return jp(this.queryStruct.fieldDef)}}class ij extends hS{}class epe{static nextStructDef(e,n){const r=new Ur(e,void 0,{model:new sj(void 0)}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Js.makeQuery(i,r,new Up(!0,void 0),!1).getResultStructDef()}}Ff.Segment=epe;class Js extends hS{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new J1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.fieldDef;switch(r!==void 0&&(0,et.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Ur({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model}),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),a.queryTimezone&&(0,et.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tpe(o,s,r,i);case"project":return new npe(o,s,r,i);case"index":return new spe(o,s,r,i);case"raw":return new ipe(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof hS)u=o.parent;else if(o instanceof Ur)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,fn.exprWalk)(r)){if(o.node==="function_call"){(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,et.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,et.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,et.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,et.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,et.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof ij||s instanceof Js){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new Nu(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof jr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),tj(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new fn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,et.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,et.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof fi){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=n.code,o=[i];return pS(e.f)?(r=e.f.getFilterList(),{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"measure"}):Cr(e.f)?{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"dimension"}:void 0}return}else if(e instanceof Nu){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,et.isRawSegment)(s)?void 0:s.limit;let u;if((0,et.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof Nu){const{structDef:c}=this.generateTurtlePipelineSQL(a,new Up(!0,void 0),"<nosource>"),f=a.getRepeatedResultType()==="nested"?"nested":"inline";c.name=u,c.structRelationship={fieldName:u,type:f,isArray:!1},c.structSource={type:f},c.resultMetadata=l,r.push(c)}else if(a instanceof fi&&a.fieldUsage.type==="result"){a.f instanceof K1e&&r.push(a.f.getAsJoinedStructDef(u)),Cr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"date":{r.push({name:u,type:a.f.fieldDef.type,timeframe:a.f.fieldDef.timeframe,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={fields:r,name:this.resultStage||"result",dialect:this.parent.dialect.name,primaryKey:i,structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"},resultMetadata:this.getResultMetadata(this.rootResult),type:"struct",queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.fieldDef.modelAnnotation&&(o.modelAnnotation=this.parent.fieldDef.modelAnnotation),o}generateSQLJoinBlock(e,n){let r="";const i=n.queryStruct,s=i.fieldDef.structRelationship;let o=i.structSourceSQL(e);if((0,et.isJoinOn)(s)){const u=s.matrixOperation.toUpperCase();if(n.makeUniqueKey){const f=this.generateSQLPassthroughKeys(i);o=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${f} FROM ${o} as x)`}let a="";if(i.parent===void 0)throw new Error("Expected joined struct to have a parent.");s.onExpression?a=new ZR({type:"boolean",name:"ignoreme",e:s.onExpression},i.parent).generateExpression(this.rootResult):a="1=1";let l="",c;if(n.joinFilterConditions&&(c=n.joinFilterConditions.map(f=>f.generateExpression(this.rootResult))),n.children.length===0||c===void 0||!this.parent.dialect.supportsComplexFilteredSources)c!==void 0&&c.length>=1&&(l=` AND (${c.join(" AND ")})`),r+=` ${u} JOIN ${o} AS ${n.alias}
|
|
306
306
|
ON ${a}${l}
|
|
307
|
-
`;else{
|
|
307
|
+
`;else{let f=`SELECT ${n.alias}.*`,x="";for(const h of n.children)x+=this.generateSQLJoinBlock(e,h),f+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(h.alias,jp(h.queryStruct.fieldDef))} AS ${h.alias}`;return f+=`
|
|
308
308
|
FROM ${o} AS ${n.alias}
|
|
309
309
|
${x}
|
|
310
310
|
WHERE ${c==null?void 0:c.join(" AND ")}
|
|
@@ -3229,7 +3229,7 @@ const y2e = $t, OR = le, GP = bV, E2e = j5, A2e = U5, v2e = {
|
|
|
3229
3229
|
};
|
|
3230
3230
|
class _2e extends E2e.PostgresBase {
|
|
3231
3231
|
constructor() {
|
|
3232
|
-
super(...arguments), this.name = "postgres", this.defaultNumberType = "DOUBLE PRECISION", this.defaultDecimalType = "NUMERIC", this.udfPrefix = "pg_temp.__udf", this.hasFinalStage = !0, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, 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.globalFunctions = GP.POSTGRES_FUNCTIONS, this.supportsNesting = !0, this.experimental = !1, this.readsNestedData = !1;
|
|
3232
|
+
super(...arguments), this.name = "postgres", this.defaultNumberType = "DOUBLE PRECISION", this.defaultDecimalType = "NUMERIC", this.udfPrefix = "pg_temp.__udf", this.hasFinalStage = !0, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, 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.globalFunctions = GP.POSTGRES_FUNCTIONS, this.supportsNesting = !0, this.experimental = !1, this.readsNestedData = !1, this.supportsComplexFilteredSources = !1;
|
|
3233
3233
|
}
|
|
3234
3234
|
quoteTablePath(e) {
|
|
3235
3235
|
return e.split(".").map((n) => `"${n}"`).join(".");
|
|
@@ -4098,7 +4098,7 @@ const o1e = $t, FR = le, YP = FV, Lp = rd, u1e = fC, a1e = {
|
|
|
4098
4098
|
};
|
|
4099
4099
|
class c1e extends Lp.Dialect {
|
|
4100
4100
|
constructor() {
|
|
4101
|
-
super(...arguments), this.name = "snowflake", this.experimental = !1, this.defaultNumberType = "NUMBER", this.defaultDecimalType = "NUMBER", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !1, this.supportsSumDistinctFunction = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.defaultSampling = { rows: 5e4 }, this.globalFunctions = YP.SNOWFLAKE_FUNCTIONS, this.unnestWithNumbers = !1, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !1, this.supportsQualify = !1, this.supportsPipelinesInViews = !1;
|
|
4101
|
+
super(...arguments), this.name = "snowflake", this.experimental = !1, this.defaultNumberType = "NUMBER", this.defaultDecimalType = "NUMBER", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !1, this.supportsSumDistinctFunction = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.defaultSampling = { rows: 5e4 }, this.globalFunctions = YP.SNOWFLAKE_FUNCTIONS, this.unnestWithNumbers = !1, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !1, this.supportsQualify = !1, this.supportsPipelinesInViews = !1, this.supportsComplexFilteredSources = !1;
|
|
4102
4102
|
}
|
|
4103
4103
|
// don't mess with the table pathing.
|
|
4104
4104
|
quoteTablePath(e) {
|
|
@@ -6262,13 +6262,11 @@ class co extends yS {
|
|
|
6262
6262
|
e: s.onExpression
|
|
6263
6263
|
}, i.parent).generateExpression(this.rootResult) : a = "1=1";
|
|
6264
6264
|
let l = "", c;
|
|
6265
|
-
if (n.joinFilterConditions && (c = n.joinFilterConditions.map((f) => f.generateExpression(this.rootResult))), n.children.length === 0 || c === void 0)
|
|
6265
|
+
if (n.joinFilterConditions && (c = n.joinFilterConditions.map((f) => f.generateExpression(this.rootResult))), n.children.length === 0 || c === void 0 || !this.parent.dialect.supportsComplexFilteredSources)
|
|
6266
6266
|
c !== void 0 && c.length >= 1 && (l = ` AND (${c.join(" AND ")})`), r += ` ${u} JOIN ${o} AS ${n.alias}
|
|
6267
6267
|
ON ${a}${l}
|
|
6268
6268
|
`;
|
|
6269
6269
|
else {
|
|
6270
|
-
if (!this.parent.dialect.supportsComplexFilteredSources)
|
|
6271
|
-
throw new Error("Cannot join a source with a filter on a joined source");
|
|
6272
6270
|
let f = `SELECT ${n.alias}.*`, x = "";
|
|
6273
6271
|
for (const h of n.children)
|
|
6274
6272
|
x += this.generateSQLJoinBlock(e, h), f += `, ${this.parent.dialect.sqlSelectAliasAsStruct(h.alias, km(h.queryStruct.fieldDef))} AS ${h.alias}`;
|
|
@@ -114,7 +114,7 @@ AS (
|
|
|
114
114
|
${(0,wM.indent)(n)}
|
|
115
115
|
);
|
|
116
116
|
`}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
|
|
117
|
-
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,n){const r=hv(e),i=r?`, "${r}"`:"";return n.e.dataType==="date"?Whe(n.units)?`DATE_TRUNC(${n.e.sql},${n.units})`:`TIMESTAMP(${n.e.sql}${i})`:`TIMESTAMP_TRUNC(${n.e.sql},${n.units}${i})`}sqlTimeExtractExpr(e,n){const r=Vhe[n.units]||n.units,i=n.e.dataType==="timestamp"&&hv(e),s=i?` AT TIME ZONE '${i}'`:"";return`EXTRACT(${r} FROM ${n.e.sql}${s})`}sqlAlterTimeExpr(e){const n=e.kids.base;let r=n.dataType,i=n.sql;e.units!=="day"&&LM(e.units)?r!=="timestamp"&&(i=`TIMESTAMP(${i})`,r="timestamp"):r==="timestamp"&&(i=`DATETIME(${i})`,r="datetime");const s=e.op==="+"?"_ADD":"_SUB",u=`${`${r.toUpperCase()}${s}`}(${i}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return r===n.dataType?u:`${n.dataType.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=hv(e),s=n.e.sql||"";if(r==="timestamp::date"&&i)return`DATE(${s},'${i}')`;if(r==="date::timestamp"&&i)return`TIMESTAMP(${s}, '${i}')`;if(n.srcType!==n.dstType){const o=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw;return`${n.safe?"SAFE_CAST":"CAST"}(${s} AS ${o})`}return s}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,n){if(n.dataType==="date")return`DATE('${n.literal}')`;if(n.dataType==="timestamp"){let r=`'${n.literal}'`;const i=n.timezone||hv(e);return i&&i!=="UTC"&&(r+=`,'${i}'`),`TIMESTAMP(${r})`}else throw new Error(`Unsupported Literal time format ${n.dataType}`)}sqlMeasureTimeExpr(e){const n={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},r=e.kids.left,i=e.kids.right;let s=r.sql,o=i.sql;if(n[e.units]){const{use:u,ratio:a}=n[e.units];if(!LM(u))throw new Error(`Measure in '${u} not implemented`);if(r.dataType!==i.dataType)throw new Error("Can't measure difference between different types");r.dataType==="date"&&(s=`TIMESTAMP(${s})`,o=`TIMESTAMP(${o})`);let l=`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,kR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,kR.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,kR.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${n.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return Hhe.STANDARDSQL_FUNCTIONS.get(e)}getDialectFunctions(){return Ghe.STANDARDSQL_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return Yhe[i.toUpperCase()]}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}bp.StandardSQLDialect=Khe,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(bp,t)}(SR);var PR={},pv={},IM={},$M={},oh={};Object.defineProperty(oh,"__esModule",{value:!0}),oh.fnStringAggDistinct=oh.fnStringAgg=void 0;const Sn=pe;function Xhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ','${n})`,{supportsOrderBy:!0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ${e.arg}${n})`,{supportsOrderBy:!0})]}oh.fnStringAgg=Xhe;function Jhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ','${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}oh.fnStringAggDistinct=Jhe;var gv={};Object.defineProperty(gv,"__esModule",{value:!0}),gv.fnByteLength=void 0;const uh=pe;function Zhe(){return[(0,uh.overload)((0,uh.minScalar)("number"),[(0,uh.param)("value",(0,uh.anyExprType)("string"))],(0,uh.sql)`OCTET_LENGTH(${(0,uh.arg)("value")})`)]}gv.fnByteLength=Zhe;var mv={};Object.defineProperty(mv,"__esModule",{value:!0}),mv.fnEndsWith=void 0;const yf=pe;function e2e(){const t=(0,yf.makeParam)("value",(0,yf.anyExprType)("string")),e=(0,yf.makeParam)("suffix",(0,yf.anyExprType)("string"));return[(0,yf.overload)((0,yf.minScalar)("boolean"),[t.param,e.param],(0,yf.sql)`COALESCE(RIGHT(${t.arg}, LENGTH(${e.arg})) = ${e.arg}, false)`)]}mv.fnEndsWith=e2e;var ah={};Object.defineProperty(ah,"__esModule",{value:!0}),ah.fnLeast=ah.fnGreatest=void 0;const Va=pe,t2e=["string","number","timestamp","date","json"];function BM(t){return t2e.map(e=>(0,Va.overload)((0,Va.minScalar)(e),[(0,Va.params)("values",(0,Va.anyExprType)(e))],(0,Va.sql)`CASE WHEN NUM_NULLS(${(0,Va.spread)((0,Va.arg)("values"))}) > 0 THEN NULL ELSE ${t}(${(0,Va.spread)((0,Va.arg)("values"))}) END`))}const n2e=()=>BM("GREATEST");ah.fnGreatest=n2e;const r2e=()=>BM("LEAST");ah.fnLeast=r2e;var yv={};Object.defineProperty(yv,"__esModule",{value:!0}),yv.fnIfnull=void 0;const Ya=pe,i2e=["string","number","timestamp","date","json"];function s2e(){return i2e.map(t=>(0,Ya.overload)((0,Ya.minScalar)(t),[(0,Ya.param)("value",(0,Ya.anyExprType)(t)),(0,Ya.param)("default",(0,Ya.anyExprType)(t))],(0,Ya.sql)`COALESCE(${(0,Ya.arg)("value")}, ${(0,Ya.arg)("default")})`))}yv.fnIfnull=s2e;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.fnIsInf=void 0;const Fp=pe;function o2e(){const t=(0,Fp.makeParam)("value",(0,Fp.anyExprType)("number"));return[(0,Fp.overload)((0,Fp.minScalar)("boolean"),[t.param],(0,Fp.sql)`COALESCE(${t.arg} = DOUBLE PRECISION 'Infinity' OR ${t.arg} = DOUBLE PRECISION '-Infinity', false)`)]}Ev.fnIsInf=o2e;var Av={};Object.defineProperty(Av,"__esModule",{value:!0}),Av.fnIsNan=void 0;const lh=pe;function u2e(){return[(0,lh.overload)((0,lh.minScalar)("boolean"),[(0,lh.param)("value",(0,lh.anyExprType)("number"))],(0,lh.sql)`COALESCE(${(0,lh.arg)("value")} = NUMERIC 'NaN', false)`)]}Av.fnIsNan=u2e;var vv={};Object.defineProperty(vv,"__esModule",{value:!0}),vv.fnLog=void 0;const Ef=pe;function a2e(){const t=(0,Ef.makeParam)("value",(0,Ef.anyExprType)("number")),e=(0,Ef.makeParam)("base",(0,Ef.anyExprType)("number"));return[(0,Ef.overload)((0,Ef.minScalar)("number"),[t.param,e.param],(0,Ef.sql)`LOG(${e.arg}, ${t.arg})`)]}vv.fnLog=a2e;var Sv={};Object.defineProperty(Sv,"__esModule",{value:!0}),Sv.fnRand=void 0;const MR=pe;function l2e(){return[(0,MR.overload)((0,MR.minScalar)("number"),[],(0,MR.sql)`RANDOM()`)]}Sv.fnRand=l2e;var _v={};Object.defineProperty(_v,"__esModule",{value:!0}),_v.fnRegexpExtract=void 0;const Af=pe;function c2e(){const t=(0,Af.makeParam)("value",(0,Af.anyExprType)("string")),e=(0,Af.makeParam)("pattern",(0,Af.anyExprType)("regular expression"));return[(0,Af.overload)((0,Af.minScalar)("string"),[t.param,e.param],(0,Af.sql)`SUBSTRING(${t.arg}, ${e.arg})`)]}_v.fnRegexpExtract=c2e;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.fnReplace=void 0;const Hi=pe;function f2e(){const t=(0,Hi.makeParam)("value",(0,Hi.anyExprType)("string")),e=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("string")),n=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("regular expression")),r=(0,Hi.makeParam)("replacement",(0,Hi.anyExprType)("string"));return[(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,e.param,r.param],(0,Hi.sql)`REPLACE(${t.arg}, ${e.arg}, ${r.arg})`),(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,n.param,r.param],(0,Hi.sql)`REGEXP_REPLACE(${t.arg}, ${n.arg}, ${r.arg}, 'g')`)]}Cv.fnReplace=f2e;var bv={};Object.defineProperty(bv,"__esModule",{value:!0}),bv.fnRound=void 0;const Su=pe;function x2e(){const t=(0,Su.makeParam)("value",(0,Su.anyExprType)("number")),e=(0,Su.makeParam)("precision",(0,Su.anyExprType)("number"));return[(0,Su.overload)((0,Su.minScalar)("number"),[t.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC)`),(0,Su.overload)((0,Su.minScalar)("number"),[t.param,e.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC, ${e.arg})`)]}bv.fnRound=x2e;var Tv={};Object.defineProperty(Tv,"__esModule",{value:!0}),Tv.fnStddev=void 0;const wp=pe;function d2e(){const t=(0,wp.makeParam)("value",(0,wp.maxScalar)("number"));return[(0,wp.overload)((0,wp.minAggregate)("number"),[t.param],(0,wp.sql)`STDDEV(${t.arg}::DOUBLE PRECISION)`)]}Tv.fnStddev=d2e;var Ov={};Object.defineProperty(Ov,"__esModule",{value:!0}),Ov.fnSubstr=void 0;const Ks=pe;function h2e(){const t=(0,Ks.makeParam)("value",(0,Ks.anyExprType)("string")),e=(0,Ks.makeParam)("position",(0,Ks.anyExprType)("number")),n=(0,Ks.makeParam)("length",(0,Ks.anyExprType)("number"));return[(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END)`),(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param,n.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END, ${n.arg})`)]}Ov.fnSubstr=h2e;var Rv={};Object.defineProperty(Rv,"__esModule",{value:!0}),Rv.fnTrunc=void 0;const _u=pe;function p2e(){const t=(0,_u.makeParam)("value",(0,_u.anyExprType)("number")),e=(0,_u.makeParam)("precision",(0,_u.anyExprType)("number"));return[(0,_u.overload)((0,_u.minScalar)("number"),[t.param],(0,_u.sql)`TRUNC(${t.arg}::NUMERIC)`),(0,_u.overload)((0,_u.minScalar)("number"),[t.param,e.param],(0,_u.sql)`TRUNC((${t.arg}::NUMERIC), ${e.arg})`)]}Rv.fnTrunc=p2e;var Nv={};Object.defineProperty(Nv,"__esModule",{value:!0}),Nv.fnUnicode=void 0;const ch=pe;function g2e(){return[(0,ch.overload)((0,ch.minScalar)("number"),[(0,ch.param)("value",(0,ch.anyExprType)("string"))],(0,ch.sql)`ASCII(${(0,ch.arg)("value")})`)]}Nv.fnUnicode=g2e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;const e=lf,n=oh,r=gv,i=mv,s=ah,o=yv,u=Ev,a=Av,l=vv,c=Sv,f=_v,x=Cv,h=bv,p=Tv,m=Ov,g=Rv,y=Nv;t.POSTGRES_FUNCTIONS=e.FUNCTIONS.clone(),t.POSTGRES_FUNCTIONS.add("regexp_extract",f.fnRegexpExtract),t.POSTGRES_FUNCTIONS.add("stddev",p.fnStddev),t.POSTGRES_FUNCTIONS.add("rand",c.fnRand),t.POSTGRES_FUNCTIONS.add("greatest",s.fnGreatest),t.POSTGRES_FUNCTIONS.add("least",s.fnLeast),t.POSTGRES_FUNCTIONS.add("is_nan",a.fnIsNan),t.POSTGRES_FUNCTIONS.add("is_inf",u.fnIsInf),t.POSTGRES_FUNCTIONS.add("round",h.fnRound),t.POSTGRES_FUNCTIONS.add("byte_length",r.fnByteLength),t.POSTGRES_FUNCTIONS.add("unicode",y.fnUnicode),t.POSTGRES_FUNCTIONS.add("ifnull",o.fnIfnull),t.POSTGRES_FUNCTIONS.add("trunc",g.fnTrunc),t.POSTGRES_FUNCTIONS.add("substr",m.fnSubstr),t.POSTGRES_FUNCTIONS.add("replace",x.fnReplace),t.POSTGRES_FUNCTIONS.add("ends_with",i.fnEndsWith),t.POSTGRES_FUNCTIONS.add("string_agg",n.fnStringAgg),t.POSTGRES_FUNCTIONS.add("string_agg_distinct",n.fnStringAggDistinct),t.POSTGRES_FUNCTIONS.add("log",l.fnLog),t.POSTGRES_FUNCTIONS.seal()}($M),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;var e=$M;Object.defineProperty(t,"POSTGRES_FUNCTIONS",{enumerable:!0,get:function(){return e.POSTGRES_FUNCTIONS}})}(IM);var Dv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=af;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class n extends e.Dialect{sqlTruncExpr(i,s){const o=s.units==="week",u=o?`${s.e.sql} + INTERVAL '1' DAY`:s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);if(l){const c=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`;let f=`DATE_TRUNC('${s.units}', ${c})`;return f=`${f}::TIMESTAMP`,`(${`${f} AT TIME ZONE '${l}'`})::TIMESTAMP`}}let a=`DATE_TRUNC('${s.units}', ${u})`;return o&&(a=`(${a} - INTERVAL '1' DAY)`),a}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(i,s){const o=t.timeExtractMap[s.units]||s.units;let u=s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);l&&(u=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`)}const a=`EXTRACT(${o} FROM ${u})`;return s.units==="day_of_week"?`mod(${a}+1,7)`:a}sqlCast(i,s){const o=s.e.sql||"",u=`${s.srcType}::${s.dstType}`,a=(0,e.qtz)(i);if(u==="timestamp::date"&&a)return`CAST((${`${o}::TIMESTAMPTZ`}) AT TIME ZONE '${a}' AS DATE)`;if(u==="date::timestamp"&&a)return`CAST((${o})::TIMESTAMP AT TIME ZONE '${a}' AS TIMESTAMP)`;if(s.srcType!==s.dstType){const l=typeof s.dstType=="string"?this.malloyTypeToSQLType({type:s.dstType}):s.dstType.raw;return`${s.safe?"TRY_CAST":"CAST"}(${o} AS ${l})`}return o}sqlRegexpMatch(i){return`${i.kids.expr.sql} ~ ${i.kids.regex.sql}`}sqlLiteralTime(i,s){if(s.dataType==="date")return`DATE '${s.literal}'`;const o=s.timezone||(0,e.qtz)(i);return o?`TIMESTAMPTZ '${s.literal} ${o}'::TIMESTAMP`:`TIMESTAMP '${s.literal}'`}}t.PostgresBase=n})(Dv);var Fv={};Object.defineProperty(Fv,"__esModule",{value:!0}),Fv.POSTGRES_DIALECT_FUNCTIONS=void 0,Fv.POSTGRES_DIALECT_FUNCTIONS={},Object.defineProperty(pv,"__esModule",{value:!0}),pv.PostgresDialect=void 0;const m2e=It,jR=le,kM=IM,y2e=Dv,E2e=Fv,A2e={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},PM={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},v2e={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class S2e extends y2e.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,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.globalFunctions=kM.POSTGRES_FUNCTIONS,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1}quoteTablePath(e){return e.split(".").map(n=>`"${n}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,n){return`MAX(${n})`}mapFields(e){return e.map(n=>`
|
|
117
|
+
`}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return"`"+e+"`"}sqlNowExpr(){return"CURRENT_TIMESTAMP()"}sqlTruncExpr(e,n){const r=hv(e),i=r?`, "${r}"`:"";return n.e.dataType==="date"?Whe(n.units)?`DATE_TRUNC(${n.e.sql},${n.units})`:`TIMESTAMP(${n.e.sql}${i})`:`TIMESTAMP_TRUNC(${n.e.sql},${n.units}${i})`}sqlTimeExtractExpr(e,n){const r=Vhe[n.units]||n.units,i=n.e.dataType==="timestamp"&&hv(e),s=i?` AT TIME ZONE '${i}'`:"";return`EXTRACT(${r} FROM ${n.e.sql}${s})`}sqlAlterTimeExpr(e){const n=e.kids.base;let r=n.dataType,i=n.sql;e.units!=="day"&&LM(e.units)?r!=="timestamp"&&(i=`TIMESTAMP(${i})`,r="timestamp"):r==="timestamp"&&(i=`DATETIME(${i})`,r="datetime");const s=e.op==="+"?"_ADD":"_SUB",u=`${`${r.toUpperCase()}${s}`}(${i}, INTERVAL ${e.kids.delta.sql} ${e.units})`;return r===n.dataType?u:`${n.dataType.toUpperCase()}(${u})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=hv(e),s=n.e.sql||"";if(r==="timestamp::date"&&i)return`DATE(${s},'${i}')`;if(r==="date::timestamp"&&i)return`TIMESTAMP(${s}, '${i}')`;if(n.srcType!==n.dstType){const o=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw;return`${n.safe?"SAFE_CAST":"CAST"}(${s} AS ${o})`}return s}sqlRegexpMatch(e){return`REGEXP_CONTAINS(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlLiteralTime(e,n){if(n.dataType==="date")return`DATE('${n.literal}')`;if(n.dataType==="timestamp"){let r=`'${n.literal}'`;const i=n.timezone||hv(e);return i&&i!=="UTC"&&(r+=`,'${i}'`),`TIMESTAMP(${r})`}else throw new Error(`Unsupported Literal time format ${n.dataType}`)}sqlMeasureTimeExpr(e){const n={microsecond:{use:"microsecond",ratio:1},millisecond:{use:"microsecond",ratio:1e3},second:{use:"millisecond",ratio:1e3},minute:{use:"second",ratio:60},hour:{use:"minute",ratio:60},day:{use:"hour",ratio:24},week:{use:"day",ratio:7}},r=e.kids.left,i=e.kids.right;let s=r.sql,o=i.sql;if(n[e.units]){const{use:u,ratio:a}=n[e.units];if(!LM(u))throw new Error(`Measure in '${u} not implemented`);if(r.dataType!==i.dataType)throw new Error("Can't measure difference between different types");r.dataType==="date"&&(s=`TIMESTAMP(${s})`,o=`TIMESTAMP(${o})`);let l=`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${e.units} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,kR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,kR.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,kR.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE SYSTEM (${n.percent} PERCENT))`}return e}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return Hhe.STANDARDSQL_FUNCTIONS.get(e)}getDialectFunctions(){return Ghe.STANDARDSQL_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"INT64":"FLOAT64":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return Yhe[i.toUpperCase()]}castToString(e){return`CAST(${e} as STRING)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}bp.StandardSQLDialect=Khe,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(bp,t)}(SR);var PR={},pv={},IM={},$M={},oh={};Object.defineProperty(oh,"__esModule",{value:!0}),oh.fnStringAggDistinct=oh.fnStringAgg=void 0;const Sn=pe;function Xhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ','${n})`,{supportsOrderBy:!0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(${t.arg}, ${e.arg}${n})`,{supportsOrderBy:!0})]}oh.fnStringAgg=Xhe;function Jhe(){const t=(0,Sn.makeParam)("value",(0,Sn.maxScalar)("string")),e=(0,Sn.makeParam)("separator",(0,Sn.literal)((0,Sn.maxScalar)("string"))),n={node:"aggregate_order_by"};return[(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ','${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0}),(0,Sn.overload)((0,Sn.minAggregate)("string"),[t.param,e.param],(0,Sn.sql)`STRING_AGG(DISTINCT ${t.arg}, ${e.arg}${n})`,{isSymmetric:!0,supportsOrderBy:"only_default",defaultOrderByArgIndex:0})]}oh.fnStringAggDistinct=Jhe;var gv={};Object.defineProperty(gv,"__esModule",{value:!0}),gv.fnByteLength=void 0;const uh=pe;function Zhe(){return[(0,uh.overload)((0,uh.minScalar)("number"),[(0,uh.param)("value",(0,uh.anyExprType)("string"))],(0,uh.sql)`OCTET_LENGTH(${(0,uh.arg)("value")})`)]}gv.fnByteLength=Zhe;var mv={};Object.defineProperty(mv,"__esModule",{value:!0}),mv.fnEndsWith=void 0;const yf=pe;function e2e(){const t=(0,yf.makeParam)("value",(0,yf.anyExprType)("string")),e=(0,yf.makeParam)("suffix",(0,yf.anyExprType)("string"));return[(0,yf.overload)((0,yf.minScalar)("boolean"),[t.param,e.param],(0,yf.sql)`COALESCE(RIGHT(${t.arg}, LENGTH(${e.arg})) = ${e.arg}, false)`)]}mv.fnEndsWith=e2e;var ah={};Object.defineProperty(ah,"__esModule",{value:!0}),ah.fnLeast=ah.fnGreatest=void 0;const Va=pe,t2e=["string","number","timestamp","date","json"];function BM(t){return t2e.map(e=>(0,Va.overload)((0,Va.minScalar)(e),[(0,Va.params)("values",(0,Va.anyExprType)(e))],(0,Va.sql)`CASE WHEN NUM_NULLS(${(0,Va.spread)((0,Va.arg)("values"))}) > 0 THEN NULL ELSE ${t}(${(0,Va.spread)((0,Va.arg)("values"))}) END`))}const n2e=()=>BM("GREATEST");ah.fnGreatest=n2e;const r2e=()=>BM("LEAST");ah.fnLeast=r2e;var yv={};Object.defineProperty(yv,"__esModule",{value:!0}),yv.fnIfnull=void 0;const Ya=pe,i2e=["string","number","timestamp","date","json"];function s2e(){return i2e.map(t=>(0,Ya.overload)((0,Ya.minScalar)(t),[(0,Ya.param)("value",(0,Ya.anyExprType)(t)),(0,Ya.param)("default",(0,Ya.anyExprType)(t))],(0,Ya.sql)`COALESCE(${(0,Ya.arg)("value")}, ${(0,Ya.arg)("default")})`))}yv.fnIfnull=s2e;var Ev={};Object.defineProperty(Ev,"__esModule",{value:!0}),Ev.fnIsInf=void 0;const Fp=pe;function o2e(){const t=(0,Fp.makeParam)("value",(0,Fp.anyExprType)("number"));return[(0,Fp.overload)((0,Fp.minScalar)("boolean"),[t.param],(0,Fp.sql)`COALESCE(${t.arg} = DOUBLE PRECISION 'Infinity' OR ${t.arg} = DOUBLE PRECISION '-Infinity', false)`)]}Ev.fnIsInf=o2e;var Av={};Object.defineProperty(Av,"__esModule",{value:!0}),Av.fnIsNan=void 0;const lh=pe;function u2e(){return[(0,lh.overload)((0,lh.minScalar)("boolean"),[(0,lh.param)("value",(0,lh.anyExprType)("number"))],(0,lh.sql)`COALESCE(${(0,lh.arg)("value")} = NUMERIC 'NaN', false)`)]}Av.fnIsNan=u2e;var vv={};Object.defineProperty(vv,"__esModule",{value:!0}),vv.fnLog=void 0;const Ef=pe;function a2e(){const t=(0,Ef.makeParam)("value",(0,Ef.anyExprType)("number")),e=(0,Ef.makeParam)("base",(0,Ef.anyExprType)("number"));return[(0,Ef.overload)((0,Ef.minScalar)("number"),[t.param,e.param],(0,Ef.sql)`LOG(${e.arg}, ${t.arg})`)]}vv.fnLog=a2e;var Sv={};Object.defineProperty(Sv,"__esModule",{value:!0}),Sv.fnRand=void 0;const MR=pe;function l2e(){return[(0,MR.overload)((0,MR.minScalar)("number"),[],(0,MR.sql)`RANDOM()`)]}Sv.fnRand=l2e;var _v={};Object.defineProperty(_v,"__esModule",{value:!0}),_v.fnRegexpExtract=void 0;const Af=pe;function c2e(){const t=(0,Af.makeParam)("value",(0,Af.anyExprType)("string")),e=(0,Af.makeParam)("pattern",(0,Af.anyExprType)("regular expression"));return[(0,Af.overload)((0,Af.minScalar)("string"),[t.param,e.param],(0,Af.sql)`SUBSTRING(${t.arg}, ${e.arg})`)]}_v.fnRegexpExtract=c2e;var Cv={};Object.defineProperty(Cv,"__esModule",{value:!0}),Cv.fnReplace=void 0;const Hi=pe;function f2e(){const t=(0,Hi.makeParam)("value",(0,Hi.anyExprType)("string")),e=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("string")),n=(0,Hi.makeParam)("pattern",(0,Hi.anyExprType)("regular expression")),r=(0,Hi.makeParam)("replacement",(0,Hi.anyExprType)("string"));return[(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,e.param,r.param],(0,Hi.sql)`REPLACE(${t.arg}, ${e.arg}, ${r.arg})`),(0,Hi.overload)((0,Hi.minScalar)("string"),[t.param,n.param,r.param],(0,Hi.sql)`REGEXP_REPLACE(${t.arg}, ${n.arg}, ${r.arg}, 'g')`)]}Cv.fnReplace=f2e;var bv={};Object.defineProperty(bv,"__esModule",{value:!0}),bv.fnRound=void 0;const Su=pe;function x2e(){const t=(0,Su.makeParam)("value",(0,Su.anyExprType)("number")),e=(0,Su.makeParam)("precision",(0,Su.anyExprType)("number"));return[(0,Su.overload)((0,Su.minScalar)("number"),[t.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC)`),(0,Su.overload)((0,Su.minScalar)("number"),[t.param,e.param],(0,Su.sql)`ROUND((${t.arg})::NUMERIC, ${e.arg})`)]}bv.fnRound=x2e;var Tv={};Object.defineProperty(Tv,"__esModule",{value:!0}),Tv.fnStddev=void 0;const wp=pe;function d2e(){const t=(0,wp.makeParam)("value",(0,wp.maxScalar)("number"));return[(0,wp.overload)((0,wp.minAggregate)("number"),[t.param],(0,wp.sql)`STDDEV(${t.arg}::DOUBLE PRECISION)`)]}Tv.fnStddev=d2e;var Ov={};Object.defineProperty(Ov,"__esModule",{value:!0}),Ov.fnSubstr=void 0;const Ks=pe;function h2e(){const t=(0,Ks.makeParam)("value",(0,Ks.anyExprType)("string")),e=(0,Ks.makeParam)("position",(0,Ks.anyExprType)("number")),n=(0,Ks.makeParam)("length",(0,Ks.anyExprType)("number"));return[(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END)`),(0,Ks.overload)((0,Ks.minScalar)("string"),[t.param,e.param,n.param],(0,Ks.sql)`SUBSTR(${t.arg}, CASE WHEN ${e.arg} < 0 THEN LENGTH(${t.arg}) + ${e.arg} + 1 ELSE ${e.arg} END, ${n.arg})`)]}Ov.fnSubstr=h2e;var Rv={};Object.defineProperty(Rv,"__esModule",{value:!0}),Rv.fnTrunc=void 0;const _u=pe;function p2e(){const t=(0,_u.makeParam)("value",(0,_u.anyExprType)("number")),e=(0,_u.makeParam)("precision",(0,_u.anyExprType)("number"));return[(0,_u.overload)((0,_u.minScalar)("number"),[t.param],(0,_u.sql)`TRUNC(${t.arg}::NUMERIC)`),(0,_u.overload)((0,_u.minScalar)("number"),[t.param,e.param],(0,_u.sql)`TRUNC((${t.arg}::NUMERIC), ${e.arg})`)]}Rv.fnTrunc=p2e;var Nv={};Object.defineProperty(Nv,"__esModule",{value:!0}),Nv.fnUnicode=void 0;const ch=pe;function g2e(){return[(0,ch.overload)((0,ch.minScalar)("number"),[(0,ch.param)("value",(0,ch.anyExprType)("string"))],(0,ch.sql)`ASCII(${(0,ch.arg)("value")})`)]}Nv.fnUnicode=g2e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;const e=lf,n=oh,r=gv,i=mv,s=ah,o=yv,u=Ev,a=Av,l=vv,c=Sv,f=_v,x=Cv,h=bv,p=Tv,m=Ov,g=Rv,y=Nv;t.POSTGRES_FUNCTIONS=e.FUNCTIONS.clone(),t.POSTGRES_FUNCTIONS.add("regexp_extract",f.fnRegexpExtract),t.POSTGRES_FUNCTIONS.add("stddev",p.fnStddev),t.POSTGRES_FUNCTIONS.add("rand",c.fnRand),t.POSTGRES_FUNCTIONS.add("greatest",s.fnGreatest),t.POSTGRES_FUNCTIONS.add("least",s.fnLeast),t.POSTGRES_FUNCTIONS.add("is_nan",a.fnIsNan),t.POSTGRES_FUNCTIONS.add("is_inf",u.fnIsInf),t.POSTGRES_FUNCTIONS.add("round",h.fnRound),t.POSTGRES_FUNCTIONS.add("byte_length",r.fnByteLength),t.POSTGRES_FUNCTIONS.add("unicode",y.fnUnicode),t.POSTGRES_FUNCTIONS.add("ifnull",o.fnIfnull),t.POSTGRES_FUNCTIONS.add("trunc",g.fnTrunc),t.POSTGRES_FUNCTIONS.add("substr",m.fnSubstr),t.POSTGRES_FUNCTIONS.add("replace",x.fnReplace),t.POSTGRES_FUNCTIONS.add("ends_with",i.fnEndsWith),t.POSTGRES_FUNCTIONS.add("string_agg",n.fnStringAgg),t.POSTGRES_FUNCTIONS.add("string_agg_distinct",n.fnStringAggDistinct),t.POSTGRES_FUNCTIONS.add("log",l.fnLog),t.POSTGRES_FUNCTIONS.seal()}($M),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.POSTGRES_FUNCTIONS=void 0;var e=$M;Object.defineProperty(t,"POSTGRES_FUNCTIONS",{enumerable:!0,get:function(){return e.POSTGRES_FUNCTIONS}})}(IM);var Dv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.PostgresBase=t.timeExtractMap=void 0;const e=af;t.timeExtractMap={day_of_week:"dow",day_of_year:"doy"};class n extends e.Dialect{sqlTruncExpr(i,s){const o=s.units==="week",u=o?`${s.e.sql} + INTERVAL '1' DAY`:s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);if(l){const c=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`;let f=`DATE_TRUNC('${s.units}', ${c})`;return f=`${f}::TIMESTAMP`,`(${`${f} AT TIME ZONE '${l}'`})::TIMESTAMP`}}let a=`DATE_TRUNC('${s.units}', ${u})`;return o&&(a=`(${a} - INTERVAL '1' DAY)`),a}sqlNowExpr(){return"LOCALTIMESTAMP"}sqlTimeExtractExpr(i,s){const o=t.timeExtractMap[s.units]||s.units;let u=s.e.sql;if(s.e.dataType==="timestamp"){const l=(0,e.qtz)(i);l&&(u=`(${u}::TIMESTAMPTZ AT TIME ZONE '${l}')`)}const a=`EXTRACT(${o} FROM ${u})`;return s.units==="day_of_week"?`mod(${a}+1,7)`:a}sqlCast(i,s){const o=s.e.sql||"",u=`${s.srcType}::${s.dstType}`,a=(0,e.qtz)(i);if(u==="timestamp::date"&&a)return`CAST((${`${o}::TIMESTAMPTZ`}) AT TIME ZONE '${a}' AS DATE)`;if(u==="date::timestamp"&&a)return`CAST((${o})::TIMESTAMP AT TIME ZONE '${a}' AS TIMESTAMP)`;if(s.srcType!==s.dstType){const l=typeof s.dstType=="string"?this.malloyTypeToSQLType({type:s.dstType}):s.dstType.raw;return`${s.safe?"TRY_CAST":"CAST"}(${o} AS ${l})`}return o}sqlRegexpMatch(i){return`${i.kids.expr.sql} ~ ${i.kids.regex.sql}`}sqlLiteralTime(i,s){if(s.dataType==="date")return`DATE '${s.literal}'`;const o=s.timezone||(0,e.qtz)(i);return o?`TIMESTAMPTZ '${s.literal} ${o}'::TIMESTAMP`:`TIMESTAMP '${s.literal}'`}}t.PostgresBase=n})(Dv);var Fv={};Object.defineProperty(Fv,"__esModule",{value:!0}),Fv.POSTGRES_DIALECT_FUNCTIONS=void 0,Fv.POSTGRES_DIALECT_FUNCTIONS={},Object.defineProperty(pv,"__esModule",{value:!0}),pv.PostgresDialect=void 0;const m2e=It,jR=le,kM=IM,y2e=Dv,E2e=Fv,A2e={year:"years",month:"months",week:"weeks",day:"days",hour:"hours",minute:"mins",second:"secs"},PM={second:1,minute:60,hour:3600,day:24*3600,week:7*24*3600},v2e={"character varying":{type:"string"},name:{type:"string"},text:{type:"string"},date:{type:"date"},integer:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},"double precision":{type:"number",numberType:"float"},"timestamp without time zone":{type:"timestamp"},oid:{type:"string"},boolean:{type:"boolean"},timestamp:{type:"timestamp"},'"char"':{type:"string"},character:{type:"string"},smallint:{type:"number",numberType:"integer"},xid:{type:"string"},real:{type:"number",numberType:"float"},interval:{type:"string"},inet:{type:"string"},regtype:{type:"string"},numeric:{type:"number",numberType:"float"},bytea:{type:"string"},pg_ndistinct:{type:"number",numberType:"integer"},varchar:{type:"string"}};class S2e extends y2e.PostgresBase{constructor(){super(...arguments),this.name="postgres",this.defaultNumberType="DOUBLE PRECISION",this.defaultDecimalType="NUMERIC",this.udfPrefix="pg_temp.__udf",this.hasFinalStage=!0,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,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.globalFunctions=kM.POSTGRES_FUNCTIONS,this.supportsNesting=!0,this.experimental=!1,this.readsNestedData=!1,this.supportsComplexFilteredSources=!1}quoteTablePath(e){return e.split(".").map(n=>`"${n}"`).join(".")}sqlGroupSetTable(e){return`CROSS JOIN GENERATE_SERIES(0,${e},1) as group_set`}sqlAnyValue(e,n){return`MAX(${n})`}mapFields(e){return e.map(n=>`
|
|
118
118
|
${n.sqlExpression}${n.type==="number"?`::${this.defaultNumberType}`:""} as ${n.sqlOutputName}`).join(", ")}sqlAggregateTurtle(e,n,r,i){let s="";return i!==void 0&&(s+=`[1:${i}]`),`COALESCE(TO_JSONB((ARRAY_AGG((SELECT TO_JSONB(__x) FROM (SELECT ${this.mapFields(n)}
|
|
119
119
|
) as __x) ${r} ) FILTER (WHERE group_set=${e}))${s}),'[]'::JSONB)`}sqlAnyValueTurtle(e,n){const r=n.map(i=>`${i.sqlExpression} as ${i.sqlOutputName}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`(ARRAY_AGG(${e}) FILTER (WHERE group_set=${n} AND ${e} IS NOT NULL))[1] as ${r}`}sqlCoaleseMeasuresInline(e,n){return`TO_JSONB((ARRAY_AGG((SELECT __x FROM (SELECT ${this.mapFields(n)}) as __x)) FILTER (WHERE group_set=${e}))[1])`}sqlUnnestAlias(e,n,r,i,s,o){return s?i?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_id', row_number() over (), 'value', v) FROM UNNEST(${e}) as v))) as ${n} ON true`:`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('value', v) FROM UNNEST(${e}) as v))) as ${n} ON true`:i?`LEFT JOIN UNNEST(ARRAY((SELECT jsonb_build_object('__row_number', row_number() over())|| __xx::jsonb as b FROM JSONB_ARRAY_ELEMENTS(${e}) __xx ))) as ${n} ON true`:`LEFT JOIN JSONB_ARRAY_ELEMENTS(${e}) as ${n} ON true`}sqlSumDistinctHashedKey(e){return`('x' || MD5(${e}::varchar))::bit(64)::bigint::DECIMAL(65,0) *18446744073709551616 + ('x' || SUBSTR(MD5(${e}::varchar),17))::bit(64)::bigint::DECIMAL(65,0)`}sqlGenerateUUID(){return"GEN_RANDOM_UUID()"}sqlFieldReference(e,n,r,i,s){let o=`(${e}->>'${n}')`;if(i){switch(r){case"string":break;case"number":o=`${o}::double precision`;break;case"struct":o=`${o}::jsonb`;break}return o}else return`${e}."${n}"`}sqlUnnestPipelineHead(e,n){return e?`UNNEST(ARRAY((SELECT ${n})))`:`JSONB_ARRAY_ELEMENTS(${n})`}sqlCreateFunction(e,n){return`CREATE FUNCTION ${e}(JSONB) RETURNS JSONB AS $$
|
|
120
120
|
${(0,m2e.indent)(n)}
|
|
@@ -154,7 +154,7 @@ ${qM}
|
|
|
154
154
|
FROM (
|
|
155
155
|
SELECT UNNEST(list(distinct {key:${e}, ${n.map((i,s)=>`val${s}: ${i}`).join(",")}})) a
|
|
156
156
|
)
|
|
157
|
-
)`}sqlSampleTable(e,n){if(n!==void 0){if((0,zR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,zR.isSamplingRows)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.rows})`;if((0,zR.isSamplingPercent)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.percent} PERCENT (bernoulli))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/'/g,"''")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getGlobalFunctionDef(e){return P2e.DUCKDB_FUNCTIONS.get(e)}getDialectFunctions(){return U2e.DUCKDB_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double precision":e.type==="string"?"varchar":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return q2e[i.toUpperCase()]}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlAlterTimeExpr(e){let n=e.units,r=e.kids.delta.sql;n==="quarter"?(n="month",r=`${r}*3`):n==="week"&&(n="day",r=`${r}*7`);const i=`INTERVAL (${r}) ${n}`;return`${e.kids.base.sql} ${e.op} ${i}`}sqlRegexpMatch(e){return`REGEXP_MATCHES(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlMeasureTimeExpr(e){const n=e.kids.left,r=e.kids.right;let i=n.sql||"",s=r.sql||"";return(0,M2e.inDays)(e.units)||(n.dataType==="date"&&(i=`${i}::TIMESTAMP`),r.dataType==="date"&&(s=`${s}::TIMESTAMP`)),`DATE_SUB('${e.units}', ${i}, ${s})`}}wv.DuckDBDialect=z2e,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(wv,t)}(UR);var HR={},Qv={},zM={},HM={},Gv={};Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.fnChr=void 0;const Ip=pe;function H2e(){const t=(0,Ip.makeParam)("value",(0,Ip.anyExprType)("number"));return[(0,Ip.overload)((0,Ip.minScalar)("string"),[t.param],(0,Ip.sql)`COALESCE(CHR(${t.arg}), '')`)]}Gv.fnChr=H2e;var Wv={};Object.defineProperty(Wv,"__esModule",{value:!0}),Wv.fnDiv=void 0;const Cf=pe;function Q2e(){const t=(0,Cf.makeParam)("dividend",(0,Cf.anyExprType)("number")),e=(0,Cf.makeParam)("divisor",(0,Cf.anyExprType)("number"));return[(0,Cf.overload)((0,Cf.minScalar)("number"),[t.param,e.param],(0,Cf.sql)`CASE WHEN DIV0(${t.arg}, ${e.arg}) < 0 THEN CEIL(DIV0(${t.arg}, ${e.arg})) ELSE FLOOR(DIV0(${t.arg}, ${e.arg})) END`)]}Wv.fnDiv=Q2e;var Vv={};Object.defineProperty(Vv,"__esModule",{value:!0}),Vv.fnIsInf=void 0;const $p=pe;function G2e(){const t=(0,$p.makeParam)("value",(0,$p.anyExprType)("number"));return[(0,$p.overload)((0,$p.minScalar)("boolean"),[t.param],(0,$p.sql)`COALESCE(${t.arg} = 'inf'::FLOAT OR ${t.arg} = '-inf'::FLOAT, false)`)]}Vv.fnIsInf=G2e;var Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.fnIsNan=void 0;const gh=pe;function W2e(){return[(0,gh.overload)((0,gh.minScalar)("boolean"),[(0,gh.param)("value",(0,gh.anyExprType)("number"))],(0,gh.sql)`COALESCE(${(0,gh.arg)("value")} = 'NAN'::FLOAT, false)`)]}Yv.fnIsNan=W2e;var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.fnByteLength=mh.fnLength=void 0;const Xs=pe;function V2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`LENGTH(${(0,Xs.arg)("value")})`)]}mh.fnLength=V2e;function Y2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`CEIL(BIT_LENGTH(${(0,Xs.arg)("value")}) / 8)`)]}mh.fnByteLength=Y2e;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.fnLog=void 0;const bf=pe;function K2e(){const t=(0,bf.makeParam)("value",(0,bf.anyExprType)("number")),e=(0,bf.makeParam)("base",(0,bf.anyExprType)("number"));return[(0,bf.overload)((0,bf.minScalar)("number"),[t.param,e.param],(0,bf.sql)`LOG(${e.arg}, ${t.arg})`)]}Kv.fnLog=K2e;var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0}),Xv.fnRand=void 0;const QR=pe;function X2e(){return[(0,QR.overload)((0,QR.minScalar)("number"),[],(0,QR.sql)`UNIFORM(0::FLOAT, 1::FLOAT, RANDOM())`)]}Xv.fnRand=X2e;var Jv={};Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.fnRegexpExtract=void 0;const Tf=pe;function J2e(){const t=(0,Tf.makeParam)("value",(0,Tf.anyExprType)("string")),e=(0,Tf.makeParam)("pattern",(0,Tf.anyExprType)("regular expression"));return[(0,Tf.overload)((0,Tf.minScalar)("string"),[t.param,e.param],(0,Tf.sql)`REGEXP_SUBSTR(${t.arg}, ${e.arg}, 1, 1, 'e')`)]}Jv.fnRegexpExtract=J2e;var yh={};Object.defineProperty(yh,"__esModule",{value:!0}),yh.fnEndsWith=yh.fnStartsWith=void 0;const Gi=pe;function Z2e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("prefix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(STARTSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnStartsWith=Z2e;function e1e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("suffix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(ENDSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnEndsWith=e1e;var Zv={};Object.defineProperty(Zv,"__esModule",{value:!0}),Zv.fnStrpos=void 0;const Of=pe;function t1e(){const t=(0,Of.makeParam)("test_string",(0,Of.anyExprType)("string")),e=(0,Of.makeParam)("search_string",(0,Of.anyExprType)("string"));return[(0,Of.overload)((0,Of.minScalar)("number"),[t.param,e.param],(0,Of.sql)`POSITION(${e.arg}, ${t.arg})`)]}Zv.fnStrpos=t1e;var eS={};Object.defineProperty(eS,"__esModule",{value:!0}),eS.fnTrunc=void 0;const bu=pe;function n1e(){const t=(0,bu.makeParam)("value",(0,bu.anyExprType)("number")),e=(0,bu.makeParam)("precision",(0,bu.anyExprType)("number"));return[(0,bu.overload)((0,bu.minScalar)("number"),[t.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg}) ELSE FLOOR(${t.arg}) END`),(0,bu.overload)((0,bu.minScalar)("number"),[t.param,e.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) ELSE FLOOR(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) END`)]}eS.fnTrunc=n1e;var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.fnStringAggDistinct=Eh.fnStringAgg=void 0;const _n=pe;function r1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAgg=r1e;function i1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAggDistinct=i1e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;const e=lf,n=Gv,r=Wv,i=Vv,s=Yv,o=mh,u=Kv,a=Xv,l=Jv,c=yh,f=Zv,x=eS,h=Eh;t.SNOWFLAKE_FUNCTIONS=e.FUNCTIONS.clone(),t.SNOWFLAKE_FUNCTIONS.add("byte_length",o.fnByteLength),t.SNOWFLAKE_FUNCTIONS.add("chr",n.fnChr),t.SNOWFLAKE_FUNCTIONS.add("div",r.fnDiv),t.SNOWFLAKE_FUNCTIONS.add("is_inf",i.fnIsInf),t.SNOWFLAKE_FUNCTIONS.add("is_nan",s.fnIsNan),t.SNOWFLAKE_FUNCTIONS.add("length",o.fnLength),t.SNOWFLAKE_FUNCTIONS.add("log",u.fnLog),t.SNOWFLAKE_FUNCTIONS.add("rand",a.fnRand),t.SNOWFLAKE_FUNCTIONS.add("regexp_extract",l.fnRegexpExtract),t.SNOWFLAKE_FUNCTIONS.add("starts_with",c.fnStartsWith),t.SNOWFLAKE_FUNCTIONS.add("ends_with",c.fnEndsWith),t.SNOWFLAKE_FUNCTIONS.add("strpos",f.fnStrpos),t.SNOWFLAKE_FUNCTIONS.add("trunc",x.fnTrunc),t.SNOWFLAKE_FUNCTIONS.add("string_agg",h.fnStringAgg),t.SNOWFLAKE_FUNCTIONS.add("string_agg_distinct",h.fnStringAggDistinct),t.SNOWFLAKE_FUNCTIONS.seal()}(HM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;var e=HM;Object.defineProperty(t,"SNOWFLAKE_FUNCTIONS",{enumerable:!0,get:function(){return e.SNOWFLAKE_FUNCTIONS}})}(zM);var tS={};Object.defineProperty(tS,"__esModule",{value:!0}),tS.SNOWFLAKE_DIALECT_FUNCTIONS=void 0,tS.SNOWFLAKE_DIALECT_FUNCTIONS={},Object.defineProperty(Qv,"__esModule",{value:!0}),Qv.SnowflakeDialect=void 0;const s1e=It,GR=le,QM=zM,Bp=af,o1e=tS,u1e={day_of_week:"dayofweek",day_of_year:"dayofyear"},a1e={varchar:{type:"string"},text:{type:"string"},string:{type:"string"},char:{type:"string"},character:{type:"string"},nvarchar:{type:"string"},nvarchar2:{type:"string"},"char varying":{type:"string"},"nchar varying":{type:"string"},number:{type:"number",numberType:"integer"},numeric:{type:"number",numberType:"integer"},decimal:{type:"number",numberType:"integer"},dec:{type:"number",numberType:"integer"},integer:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},byteint:{type:"number",numberType:"integer"},float:{type:"number",numberType:"float"},float4:{type:"number",numberType:"float"},float8:{type:"number",numberType:"float"},double:{type:"number",numberType:"float"},"double precision":{type:"number",numberType:"float"},real:{type:"number",numberType:"float"},boolean:{type:"boolean"},date:{type:"date"},timestamp:{type:"timestamp"},timestampntz:{type:"timestamp"},timestamp_ntz:{type:"timestamp"},"timestamp without time zone":{type:"timestamp"},timestamptz:{type:"timestamp"},timestamp_tz:{type:"timestamp"},"timestamp with time zone":{type:"timestamp"}};class l1e extends Bp.Dialect{constructor(){super(...arguments),this.name="snowflake",this.experimental=!1,this.defaultNumberType="NUMBER",this.defaultDecimalType="NUMBER",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.defaultSampling={rows:5e4},this.globalFunctions=QM.SNOWFLAKE_FUNCTIONS,this.unnestWithNumbers=!1,this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsPipelinesInViews=!1}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT index as group_set FROM TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, ${e+1}))))`}sqlAnyValue(e,n){return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN ${n} END) WITHIN GROUP (ORDER BY ${n} ASC NULLS LAST))[0]`}mapFields(e){return e.map(n=>`
|
|
157
|
+
)`}sqlSampleTable(e,n){if(n!==void 0){if((0,zR.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,zR.isSamplingRows)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.rows})`;if((0,zR.isSamplingPercent)(n))return`(SELECT * FROM ${e} USING SAMPLE ${n.percent} PERCENT (bernoulli))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/'/g,"''")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/'/g,"''")+"'"}getGlobalFunctionDef(e){return P2e.DUCKDB_FUNCTIONS.get(e)}getDialectFunctions(){return U2e.DUCKDB_DIALECT_FUNCTIONS}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double precision":e.type==="string"?"varchar":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^(\w+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return q2e[i.toUpperCase()]}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}sqlAlterTimeExpr(e){let n=e.units,r=e.kids.delta.sql;n==="quarter"?(n="month",r=`${r}*3`):n==="week"&&(n="day",r=`${r}*7`);const i=`INTERVAL (${r}) ${n}`;return`${e.kids.base.sql} ${e.op} ${i}`}sqlRegexpMatch(e){return`REGEXP_MATCHES(${e.kids.expr.sql},${e.kids.regex.sql})`}sqlMeasureTimeExpr(e){const n=e.kids.left,r=e.kids.right;let i=n.sql||"",s=r.sql||"";return(0,M2e.inDays)(e.units)||(n.dataType==="date"&&(i=`${i}::TIMESTAMP`),r.dataType==="date"&&(s=`${s}::TIMESTAMP`)),`DATE_SUB('${e.units}', ${i}, ${s})`}}wv.DuckDBDialect=z2e,function(t){var e=F&&F.__createBinding||(Object.create?function(r,i,s,o){o===void 0&&(o=s);var u=Object.getOwnPropertyDescriptor(i,s);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[s]}}),Object.defineProperty(r,o,u)}:function(r,i,s,o){o===void 0&&(o=s),r[o]=i[s]}),n=F&&F.__exportStar||function(r,i){for(var s in r)s!=="default"&&!Object.prototype.hasOwnProperty.call(i,s)&&e(i,r,s)};Object.defineProperty(t,"__esModule",{value:!0}),n(wv,t)}(UR);var HR={},Qv={},zM={},HM={},Gv={};Object.defineProperty(Gv,"__esModule",{value:!0}),Gv.fnChr=void 0;const Ip=pe;function H2e(){const t=(0,Ip.makeParam)("value",(0,Ip.anyExprType)("number"));return[(0,Ip.overload)((0,Ip.minScalar)("string"),[t.param],(0,Ip.sql)`COALESCE(CHR(${t.arg}), '')`)]}Gv.fnChr=H2e;var Wv={};Object.defineProperty(Wv,"__esModule",{value:!0}),Wv.fnDiv=void 0;const Cf=pe;function Q2e(){const t=(0,Cf.makeParam)("dividend",(0,Cf.anyExprType)("number")),e=(0,Cf.makeParam)("divisor",(0,Cf.anyExprType)("number"));return[(0,Cf.overload)((0,Cf.minScalar)("number"),[t.param,e.param],(0,Cf.sql)`CASE WHEN DIV0(${t.arg}, ${e.arg}) < 0 THEN CEIL(DIV0(${t.arg}, ${e.arg})) ELSE FLOOR(DIV0(${t.arg}, ${e.arg})) END`)]}Wv.fnDiv=Q2e;var Vv={};Object.defineProperty(Vv,"__esModule",{value:!0}),Vv.fnIsInf=void 0;const $p=pe;function G2e(){const t=(0,$p.makeParam)("value",(0,$p.anyExprType)("number"));return[(0,$p.overload)((0,$p.minScalar)("boolean"),[t.param],(0,$p.sql)`COALESCE(${t.arg} = 'inf'::FLOAT OR ${t.arg} = '-inf'::FLOAT, false)`)]}Vv.fnIsInf=G2e;var Yv={};Object.defineProperty(Yv,"__esModule",{value:!0}),Yv.fnIsNan=void 0;const gh=pe;function W2e(){return[(0,gh.overload)((0,gh.minScalar)("boolean"),[(0,gh.param)("value",(0,gh.anyExprType)("number"))],(0,gh.sql)`COALESCE(${(0,gh.arg)("value")} = 'NAN'::FLOAT, false)`)]}Yv.fnIsNan=W2e;var mh={};Object.defineProperty(mh,"__esModule",{value:!0}),mh.fnByteLength=mh.fnLength=void 0;const Xs=pe;function V2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`LENGTH(${(0,Xs.arg)("value")})`)]}mh.fnLength=V2e;function Y2e(){return[(0,Xs.overload)((0,Xs.minScalar)("number"),[(0,Xs.param)("value",(0,Xs.anyExprType)("string"))],(0,Xs.sql)`CEIL(BIT_LENGTH(${(0,Xs.arg)("value")}) / 8)`)]}mh.fnByteLength=Y2e;var Kv={};Object.defineProperty(Kv,"__esModule",{value:!0}),Kv.fnLog=void 0;const bf=pe;function K2e(){const t=(0,bf.makeParam)("value",(0,bf.anyExprType)("number")),e=(0,bf.makeParam)("base",(0,bf.anyExprType)("number"));return[(0,bf.overload)((0,bf.minScalar)("number"),[t.param,e.param],(0,bf.sql)`LOG(${e.arg}, ${t.arg})`)]}Kv.fnLog=K2e;var Xv={};Object.defineProperty(Xv,"__esModule",{value:!0}),Xv.fnRand=void 0;const QR=pe;function X2e(){return[(0,QR.overload)((0,QR.minScalar)("number"),[],(0,QR.sql)`UNIFORM(0::FLOAT, 1::FLOAT, RANDOM())`)]}Xv.fnRand=X2e;var Jv={};Object.defineProperty(Jv,"__esModule",{value:!0}),Jv.fnRegexpExtract=void 0;const Tf=pe;function J2e(){const t=(0,Tf.makeParam)("value",(0,Tf.anyExprType)("string")),e=(0,Tf.makeParam)("pattern",(0,Tf.anyExprType)("regular expression"));return[(0,Tf.overload)((0,Tf.minScalar)("string"),[t.param,e.param],(0,Tf.sql)`REGEXP_SUBSTR(${t.arg}, ${e.arg}, 1, 1, 'e')`)]}Jv.fnRegexpExtract=J2e;var yh={};Object.defineProperty(yh,"__esModule",{value:!0}),yh.fnEndsWith=yh.fnStartsWith=void 0;const Gi=pe;function Z2e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("prefix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(STARTSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnStartsWith=Z2e;function e1e(){const t=(0,Gi.makeParam)("value",(0,Gi.anyExprType)("string")),e=(0,Gi.makeParam)("suffix",(0,Gi.anyExprType)("string"));return[(0,Gi.overload)((0,Gi.minScalar)("boolean"),[t.param,e.param],(0,Gi.sql)`COALESCE(ENDSWITH(${t.arg}, ${e.arg}), false)`)]}yh.fnEndsWith=e1e;var Zv={};Object.defineProperty(Zv,"__esModule",{value:!0}),Zv.fnStrpos=void 0;const Of=pe;function t1e(){const t=(0,Of.makeParam)("test_string",(0,Of.anyExprType)("string")),e=(0,Of.makeParam)("search_string",(0,Of.anyExprType)("string"));return[(0,Of.overload)((0,Of.minScalar)("number"),[t.param,e.param],(0,Of.sql)`POSITION(${e.arg}, ${t.arg})`)]}Zv.fnStrpos=t1e;var eS={};Object.defineProperty(eS,"__esModule",{value:!0}),eS.fnTrunc=void 0;const bu=pe;function n1e(){const t=(0,bu.makeParam)("value",(0,bu.anyExprType)("number")),e=(0,bu.makeParam)("precision",(0,bu.anyExprType)("number"));return[(0,bu.overload)((0,bu.minScalar)("number"),[t.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg}) ELSE FLOOR(${t.arg}) END`),(0,bu.overload)((0,bu.minScalar)("number"),[t.param,e.param],(0,bu.sql)`CASE WHEN ${t.arg} < 0 THEN CEIL(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) ELSE FLOOR(${t.arg} * POW(10, ${e.arg})) / POW(10, ${e.arg}) END`)]}eS.fnTrunc=n1e;var Eh={};Object.defineProperty(Eh,"__esModule",{value:!0}),Eh.fnStringAggDistinct=Eh.fnStringAgg=void 0;const _n=pe;function r1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAgg=r1e;function i1e(){const t=(0,_n.makeParam)("value",(0,_n.maxScalar)("string")),e=(0,_n.makeParam)("separator",(0,_n.literal)((0,_n.maxScalar)("string"))),n={node:"aggregate_order_by",prefix:" WITHIN GROUP(",suffix:")"};return[(0,_n.overload)((0,_n.minAggregate)("string"),[t.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ',')${n}`,{supportsOrderBy:!0,supportsLimit:!1}),(0,_n.overload)((0,_n.minAggregate)("string"),[t.param,e.param],(0,_n.sql)`LISTAGG(DISTINCT ${t.arg}, ${e.arg})${n}`,{supportsOrderBy:!0,supportsLimit:!1})]}Eh.fnStringAggDistinct=i1e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;const e=lf,n=Gv,r=Wv,i=Vv,s=Yv,o=mh,u=Kv,a=Xv,l=Jv,c=yh,f=Zv,x=eS,h=Eh;t.SNOWFLAKE_FUNCTIONS=e.FUNCTIONS.clone(),t.SNOWFLAKE_FUNCTIONS.add("byte_length",o.fnByteLength),t.SNOWFLAKE_FUNCTIONS.add("chr",n.fnChr),t.SNOWFLAKE_FUNCTIONS.add("div",r.fnDiv),t.SNOWFLAKE_FUNCTIONS.add("is_inf",i.fnIsInf),t.SNOWFLAKE_FUNCTIONS.add("is_nan",s.fnIsNan),t.SNOWFLAKE_FUNCTIONS.add("length",o.fnLength),t.SNOWFLAKE_FUNCTIONS.add("log",u.fnLog),t.SNOWFLAKE_FUNCTIONS.add("rand",a.fnRand),t.SNOWFLAKE_FUNCTIONS.add("regexp_extract",l.fnRegexpExtract),t.SNOWFLAKE_FUNCTIONS.add("starts_with",c.fnStartsWith),t.SNOWFLAKE_FUNCTIONS.add("ends_with",c.fnEndsWith),t.SNOWFLAKE_FUNCTIONS.add("strpos",f.fnStrpos),t.SNOWFLAKE_FUNCTIONS.add("trunc",x.fnTrunc),t.SNOWFLAKE_FUNCTIONS.add("string_agg",h.fnStringAgg),t.SNOWFLAKE_FUNCTIONS.add("string_agg_distinct",h.fnStringAggDistinct),t.SNOWFLAKE_FUNCTIONS.seal()}(HM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.SNOWFLAKE_FUNCTIONS=void 0;var e=HM;Object.defineProperty(t,"SNOWFLAKE_FUNCTIONS",{enumerable:!0,get:function(){return e.SNOWFLAKE_FUNCTIONS}})}(zM);var tS={};Object.defineProperty(tS,"__esModule",{value:!0}),tS.SNOWFLAKE_DIALECT_FUNCTIONS=void 0,tS.SNOWFLAKE_DIALECT_FUNCTIONS={},Object.defineProperty(Qv,"__esModule",{value:!0}),Qv.SnowflakeDialect=void 0;const s1e=It,GR=le,QM=zM,Bp=af,o1e=tS,u1e={day_of_week:"dayofweek",day_of_year:"dayofyear"},a1e={varchar:{type:"string"},text:{type:"string"},string:{type:"string"},char:{type:"string"},character:{type:"string"},nvarchar:{type:"string"},nvarchar2:{type:"string"},"char varying":{type:"string"},"nchar varying":{type:"string"},number:{type:"number",numberType:"integer"},numeric:{type:"number",numberType:"integer"},decimal:{type:"number",numberType:"integer"},dec:{type:"number",numberType:"integer"},integer:{type:"number",numberType:"integer"},int:{type:"number",numberType:"integer"},bigint:{type:"number",numberType:"integer"},smallint:{type:"number",numberType:"integer"},tinyint:{type:"number",numberType:"integer"},byteint:{type:"number",numberType:"integer"},float:{type:"number",numberType:"float"},float4:{type:"number",numberType:"float"},float8:{type:"number",numberType:"float"},double:{type:"number",numberType:"float"},"double precision":{type:"number",numberType:"float"},real:{type:"number",numberType:"float"},boolean:{type:"boolean"},date:{type:"date"},timestamp:{type:"timestamp"},timestampntz:{type:"timestamp"},timestamp_ntz:{type:"timestamp"},"timestamp without time zone":{type:"timestamp"},timestamptz:{type:"timestamp"},timestamp_tz:{type:"timestamp"},"timestamp with time zone":{type:"timestamp"}};class l1e extends Bp.Dialect{constructor(){super(...arguments),this.name="snowflake",this.experimental=!1,this.defaultNumberType="NUMBER",this.defaultDecimalType="NUMBER",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!1,this.supportsSumDistinctFunction=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.defaultSampling={rows:5e4},this.globalFunctions=QM.SNOWFLAKE_FUNCTIONS,this.unnestWithNumbers=!1,this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!1,this.supportsQualify=!1,this.supportsPipelinesInViews=!1,this.supportsComplexFilteredSources=!1}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT index as group_set FROM TABLE(FLATTEN(ARRAY_GENERATE_RANGE(0, ${e+1}))))`}sqlAnyValue(e,n){return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN ${n} END) WITHIN GROUP (ORDER BY ${n} ASC NULLS LAST))[0]`}mapFields(e){return e.map(n=>`
|
|
158
158
|
${n.sqlExpression} as ${n.sqlOutputName}`).join(", ")}mapFieldsForObjectConstruct(e){return e.map(n=>`'${n.rawName}', (${n.sqlExpression})`).join(", ")}sqlAggregateTurtle(e,n,r,i){const s=this.mapFieldsForObjectConstruct(n),o=r?` WITHIN GROUP (${r})`:"",u=`ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${s}) END)${o}`;return i===void 0?`COALESCE(${u}, [])`:`COALESCE(ARRAY_SLICE(${u}, 0, ${i}), [])`}sqlAnyValueTurtle(e,n){const r=this.mapFieldsForObjectConstruct(n);return`(ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${r}) END) WITHIN GROUP (ORDER BY 1 ASC NULLS LAST))[0]`}sqlAnyValueLastTurtle(e,n,r){return`(ARRAY_AGG(CASE WHEN group_set=${n} THEN ${e} END) WITHIN GROUP (ORDER BY ${e} ASC NULLS LAST))[0] AS ${r}`}sqlCoaleseMeasuresInline(e,n){const r=this.mapFieldsForObjectConstruct(n),i=n.map(s=>`'${s.sqlOutputName}', NULL`).join(", ");return`COALESCE(ARRAY_AGG(CASE WHEN group_set=${e} THEN OBJECT_CONSTRUCT_KEEP_NULL(${r}) END)[0], OBJECT_CONSTRUCT_KEEP_NULL(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){return s?`,LATERAL FLATTEN(INPUT => ${e}) AS ${n}_1, LATERAL (SELECT ${n}_1.INDEX, object_construct('value', ${n}_1.value) as value ) as ${n}`:`LEFT JOIN LATERAL FLATTEN(INPUT => ifnull(${e},[1])) AS ${n}`}sqlSumDistinctHashedKey(e){e=`${e}::STRING`;const n=`to_number(substr(md5_hex(${e}), 1, 15), repeat('X', 15)) * 4294967296`,r=`to_number(substr(md5_hex(${e}), 16, 8), repeat('X', 8))`;return`(${n} + ${r})`}sqlSumDistinct(e,n,r){const i=this.sqlSumDistinctHashedKey(e),s=1e8,o=`(COALESCE(${n},0)*${s})`,u=`(SUM(DISTINCT ${i} + ${o}) - SUM(DISTINCT ${i}))/${s}`;if(r==="SUM")return u;if(r==="AVG")return`(${u})/NULLIF(COUNT(DISTINCT CASE WHEN ${n} IS NOT NULL THEN ${e} END),0)`;throw new Error(`Unknown Symmetric Aggregate function ${r}`)}sqlGenerateUUID(){return"UUID_STRING()"}sqlFieldReference(e,n,r,i,s){if(n==="__row_id")return`${e}.INDEX::varchar`;if(i){let o=r;return r==="string"?o="varchar":r==="struct"&&(o="variant"),`${e}.value:"${n}"::${o}`}else return`${e}."${n}"`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`TABLE(FLATTEN(input =>${r}))`}sqlCreateFunction(e,n){throw new Error("not implemented yet")}sqlCreateFunctionCombineLastStage(e){throw new Error("not implemented yet")}sqlSelectAliasAsStruct(e){return`OBJECT_CONSTRUCT_KEEP_NULL(${e}.*)`}sqlMaybeQuoteIdentifier(e){return`"${e}"`}sqlCreateTableAsSelect(e,n){return`
|
|
159
159
|
CREATE TEMP TABLE IF NOT EXISTS \`${e}\`
|
|
160
160
|
AS (
|
|
@@ -302,9 +302,9 @@ ${(0,fn.indent)(o)})
|
|
|
302
302
|
))
|
|
303
303
|
-
|
|
304
304
|
SUM(DISTINCT ${i})
|
|
305
|
-
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class fi{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return Cr(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class Nu{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,et.isIndexSegment)(this.firstSegment)&&!(0,et.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new fi(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof fi}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof fi)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof fi&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof fi&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(Cr(n.f))return"nested";n.f instanceof Ur&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof Nu&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||r.f.fieldDef.type==="struct"||(0,et.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(ej(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.fieldDef.structRelationship;(0,et.isJoinOn)(c)&&e.parent&&c.onExpression!==void 0&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>Cr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class J1e extends Nu{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new fn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.fieldDef.structRelationship.type==="nested"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){if(this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new Q1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this),this.queryStruct.fieldDef.filterList){this.joinFilterConditions=[];for(const i of this.queryStruct.fieldDef.filterList){const s=new JR({type:"boolean",name:"ignoreme",e:i.e},this.queryStruct);this.joinFilterConditions.push(s)}}}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";switch(this.queryStruct.fieldDef.structRelationship.type){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many";case"nested":return"one_to_many";case"inline":return"one_to_one";default:throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.fieldDef.name}`)}}forceAllSymmetricCalculations(){const e=this.queryStruct.fieldDef.structRelationship;return this.queryStruct.parent===void 0||!(0,et.isJoinOn)(e)?!1:e.matrixOperation==="right"||e.matrixOperation==="full"}getDialectFieldList(){return Pp(this.queryStruct.fieldDef)}}class rj extends dS{}class epe{static nextStructDef(e,n){const r=new Ur(e,void 0,{model:new ij(void 0)}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Js.makeQuery(i,r,new Mp(!0,void 0),!1).getResultStructDef()}}Ff.Segment=epe;class Js extends dS{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new J1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.fieldDef;switch(r!==void 0&&(0,et.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Ur({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model}),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),a.queryTimezone&&(0,et.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tpe(o,s,r,i);case"project":return new npe(o,s,r,i);case"index":return new spe(o,s,r,i);case"raw":return new ipe(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof dS)u=o.parent;else if(o instanceof Ur)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,fn.exprWalk)(r)){if(o.node==="function_call"){(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,et.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,et.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,et.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,et.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,et.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof rj||s instanceof Js){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new Nu(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof jr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),ej(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new fn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,et.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,et.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof fi){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=n.code,o=[i];return hS(e.f)?(r=e.f.getFilterList(),{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"measure"}):Cr(e.f)?{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"dimension"}:void 0}return}else if(e instanceof Nu){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,et.isRawSegment)(s)?void 0:s.limit;let u;if((0,et.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof Nu){const{structDef:c}=this.generateTurtlePipelineSQL(a,new Mp(!0,void 0),"<nosource>"),f=a.getRepeatedResultType()==="nested"?"nested":"inline";c.name=u,c.structRelationship={fieldName:u,type:f,isArray:!1},c.structSource={type:f},c.resultMetadata=l,r.push(c)}else if(a instanceof fi&&a.fieldUsage.type==="result"){a.f instanceof K1e&&r.push(a.f.getAsJoinedStructDef(u)),Cr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"date":{r.push({name:u,type:a.f.fieldDef.type,timeframe:a.f.fieldDef.timeframe,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={fields:r,name:this.resultStage||"result",dialect:this.parent.dialect.name,primaryKey:i,structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"},resultMetadata:this.getResultMetadata(this.rootResult),type:"struct",queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.fieldDef.modelAnnotation&&(o.modelAnnotation=this.parent.fieldDef.modelAnnotation),o}generateSQLJoinBlock(e,n){let r="";const i=n.queryStruct,s=i.fieldDef.structRelationship;let o=i.structSourceSQL(e);if((0,et.isJoinOn)(s)){const u=s.matrixOperation.toUpperCase();if(n.makeUniqueKey){const f=this.generateSQLPassthroughKeys(i);o=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${f} FROM ${o} as x)`}let a="";if(i.parent===void 0)throw new Error("Expected joined struct to have a parent.");s.onExpression?a=new JR({type:"boolean",name:"ignoreme",e:s.onExpression},i.parent).generateExpression(this.rootResult):a="1=1";let l="",c;if(n.joinFilterConditions&&(c=n.joinFilterConditions.map(f=>f.generateExpression(this.rootResult))),n.children.length===0||c===void 0)c!==void 0&&c.length>=1&&(l=` AND (${c.join(" AND ")})`),r+=` ${u} JOIN ${o} AS ${n.alias}
|
|
305
|
+
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class fi{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return Cr(this.f)&&(e=this.f.caseGroup(this.parent.groupSet>0?this.parent.childGroups.concat(this.additionalGroupSets):[],e)),e}getAnalyticalSQL(e){return this.analyticalSQL===void 0?this.getSQL():e&&this.partitionSQL?this.partitionSQL:this.analyticalSQL}}class Nu{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,et.isIndexSegment)(this.firstSegment)&&!(0,et.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new fi(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof fi}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof fi)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof fi&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof fi&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(Cr(n.f))return"nested";n.f instanceof Ur&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof Nu&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof fi&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||r.f.fieldDef.type==="struct"||(0,et.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(ej(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.fieldDef.structRelationship;(0,et.isJoinOn)(c)&&e.parent&&c.onExpression!==void 0&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>Cr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>Cr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class J1e extends Nu{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new fn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.fieldDef.structRelationship.type==="nested"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){if(this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new Q1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this),this.queryStruct.fieldDef.filterList){this.joinFilterConditions=[];for(const i of this.queryStruct.fieldDef.filterList){const s=new JR({type:"boolean",name:"ignoreme",e:i.e},this.queryStruct);this.joinFilterConditions.push(s)}}}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";switch(this.queryStruct.fieldDef.structRelationship.type){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many";case"nested":return"one_to_many";case"inline":return"one_to_one";default:throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.fieldDef.name}`)}}forceAllSymmetricCalculations(){const e=this.queryStruct.fieldDef.structRelationship;return this.queryStruct.parent===void 0||!(0,et.isJoinOn)(e)?!1:e.matrixOperation==="right"||e.matrixOperation==="full"}getDialectFieldList(){return Pp(this.queryStruct.fieldDef)}}class rj extends dS{}class epe{static nextStructDef(e,n){const r=new Ur(e,void 0,{model:new ij(void 0)}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Js.makeQuery(i,r,new Mp(!0,void 0),!1).getResultStructDef()}}Ff.Segment=epe;class Js extends dS{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new J1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.fieldDef;switch(r!==void 0&&(0,et.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Ur({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model}),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),a.queryTimezone&&(0,et.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tpe(o,s,r,i);case"project":return new npe(o,s,r,i);case"index":return new spe(o,s,r,i);case"raw":return new ipe(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.fieldDef.structSource.type==="sql"&&this.parent.fieldDef.structSource.method==="nested"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof dS)u=o.parent;else if(o instanceof Ur)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,fn.exprWalk)(r)){if(o.node==="function_call"){(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,et.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,et.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,et.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,et.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,et.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,et.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof rj||s instanceof Js){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new Nu(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof jr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),ej(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new fn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,et.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,et.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof fi){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=n.code,o=[i];return hS(e.f)?(r=e.f.getFilterList(),{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"measure"}):Cr(e.f)?{sourceField:i,sourceExpression:s,filterList:r,sourceClasses:o,fieldKind:"dimension"}:void 0}return}else if(e instanceof Nu){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,et.isRawSegment)(s)?void 0:s.limit;let u;if((0,et.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof Nu){const{structDef:c}=this.generateTurtlePipelineSQL(a,new Mp(!0,void 0),"<nosource>"),f=a.getRepeatedResultType()==="nested"?"nested":"inline";c.name=u,c.structRelationship={fieldName:u,type:f,isArray:!1},c.structSource={type:f},c.resultMetadata=l,r.push(c)}else if(a instanceof fi&&a.fieldUsage.type==="result"){a.f instanceof K1e&&r.push(a.f.getAsJoinedStructDef(u)),Cr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"date":{r.push({name:u,type:a.f.fieldDef.type,timeframe:a.f.fieldDef.timeframe,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={fields:r,name:this.resultStage||"result",dialect:this.parent.dialect.name,primaryKey:i,structRelationship:{type:"basetable",connectionName:this.parent.connectionName},structSource:{type:"query_result"},resultMetadata:this.getResultMetadata(this.rootResult),type:"struct",queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.fieldDef.modelAnnotation&&(o.modelAnnotation=this.parent.fieldDef.modelAnnotation),o}generateSQLJoinBlock(e,n){let r="";const i=n.queryStruct,s=i.fieldDef.structRelationship;let o=i.structSourceSQL(e);if((0,et.isJoinOn)(s)){const u=s.matrixOperation.toUpperCase();if(n.makeUniqueKey){const f=this.generateSQLPassthroughKeys(i);o=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${f} FROM ${o} as x)`}let a="";if(i.parent===void 0)throw new Error("Expected joined struct to have a parent.");s.onExpression?a=new JR({type:"boolean",name:"ignoreme",e:s.onExpression},i.parent).generateExpression(this.rootResult):a="1=1";let l="",c;if(n.joinFilterConditions&&(c=n.joinFilterConditions.map(f=>f.generateExpression(this.rootResult))),n.children.length===0||c===void 0||!this.parent.dialect.supportsComplexFilteredSources)c!==void 0&&c.length>=1&&(l=` AND (${c.join(" AND ")})`),r+=` ${u} JOIN ${o} AS ${n.alias}
|
|
306
306
|
ON ${a}${l}
|
|
307
|
-
`;else{
|
|
307
|
+
`;else{let f=`SELECT ${n.alias}.*`,x="";for(const h of n.children)x+=this.generateSQLJoinBlock(e,h),f+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(h.alias,Pp(h.queryStruct.fieldDef))} AS ${h.alias}`;return f+=`
|
|
308
308
|
FROM ${o} AS ${n.alias}
|
|
309
309
|
${x}
|
|
310
310
|
WHERE ${c==null?void 0:c.join(" AND ")}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@malloydata/render",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.181-dev240907212110",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"main": "dist/module/index.umd.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"build-types": "tsc --build --declaration --emitDeclarationOnly"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@malloydata/malloy": "^0.0.
|
|
35
|
+
"@malloydata/malloy": "^0.0.181-dev240907212110",
|
|
36
36
|
"@tanstack/solid-virtual": "^3.10.4",
|
|
37
37
|
"component-register": "^0.8.6",
|
|
38
38
|
"lodash": "^4.17.20",
|