@malloydata/render 0.0.138-dev240331204754 → 0.0.138-dev240401131656

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.
@@ -3708,7 +3708,7 @@ const E2e = {
3708
3708
  };
3709
3709
  class A2e extends wP.Dialect {
3710
3710
  constructor() {
3711
- super(...arguments), this.name = "trino", this.defaultNumberType = "DOUBLE", this.defaultDecimalType = "DECIMAL", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, this.unnestWithNumbers = !1, this.defaultSampling = { enable: !1 }, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !0, this.supportsQualify = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.cantPartitionWindowFunctionsOnExpressions = !0, this.orderByClause = "output_name", this.keywords = `
3711
+ super(...arguments), this.name = "trino", this.defaultNumberType = "DOUBLE", this.defaultDecimalType = "DECIMAL", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, this.unnestWithNumbers = !1, this.defaultSampling = { enable: !1 }, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !0, this.supportsQualify = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.cantPartitionWindowFunctionsOnExpressions = !1, this.orderByClause = "output_name", this.keywords = `
3712
3712
  ALL
3713
3713
  AND
3714
3714
  ANY
@@ -3859,7 +3859,8 @@ class A2e extends wP.Dialect {
3859
3859
  // BigQuery will allocate more resources if we use a CROSS JOIN so we do that instead.
3860
3860
  //
3861
3861
  sqlUnnestAlias(e, n, r, i, s, o) {
3862
- return s ? i ? `LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}` : `LEFT JOIN UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}` : i ? `LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, * FROM UNNEST(${e})))) as ${n}` : `LEFT JOIN UNNEST(${e}) as ${n}`;
3862
+ const u = r.map((a) => this.sqlMaybeQuoteIdentifier(a.sqlOutputName));
3863
+ return s ? i ? `,UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}` : `,UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}` : i ? `,UNNEST(zip_with(a, SEQUENCE(1,cardinality(a)), (r,__row_id) -> (r, __row_id))) as ${n}_outer(${n},__row_id)` : `,UNNEST(${e}) as ${n}(${u.join(", ")})`;
3863
3864
  }
3864
3865
  sqlSumDistinctHashedKey(e) {
3865
3866
  e = `CAST(${e} AS VARCHAR)`;
@@ -3867,10 +3868,10 @@ class A2e extends wP.Dialect {
3867
3868
  return `(${n} + ${r}) * 0.000000001`;
3868
3869
  }
3869
3870
  sqlGenerateUUID() {
3870
- return "GENERATE_UUID()";
3871
+ return "UUID()";
3871
3872
  }
3872
3873
  sqlFieldReference(e, n, r, i, s) {
3873
- return `${e}.${n}`;
3874
+ return n === "__row_id" ? `${e}_outer.__row_id` : `${e}.${n}`;
3874
3875
  }
3875
3876
  sqlUnnestPipelineHead(e, n) {
3876
3877
  let r = n;
@@ -3900,7 +3901,7 @@ ${(0, FP.indent)(n)}
3900
3901
  return `(SELECT AS STRUCT ${e}.*)`;
3901
3902
  }
3902
3903
  sqlMaybeQuoteIdentifier(e) {
3903
- return e;
3904
+ return '"' + e + '"';
3904
3905
  }
3905
3906
  sqlNow() {
3906
3907
  return (0, wn.mkExpr)`CURRENT_TIMESTAMP()`;
@@ -3935,7 +3936,7 @@ ${(0, FP.indent)(n)}
3935
3936
  return n.expr;
3936
3937
  }
3937
3938
  sqlRegexpMatch(e, n) {
3938
- return (0, wn.mkExpr)`REGEXP_CONTAINS(${e}, ${n})`;
3939
+ return (0, wn.mkExpr)`REGEXP_LIKE(${e}, ${n})`;
3939
3940
  }
3940
3941
  sqlLiteralTime(e, n, r, i) {
3941
3942
  if (r === "date")
@@ -5398,7 +5399,7 @@ ${(0, Tr.indent)(f)}) AS ${n.alias}
5398
5399
  if (typeof o.field == "string") {
5399
5400
  const u = n.getField(o.field);
5400
5401
  if (u && u.fieldUsage.type === "result")
5401
- this.parent.dialect.orderByClause === "ordinal" ? s.push(`${u.fieldUsage.resultIndex} ${o.dir || "ASC"}`) : this.parent.dialect.orderByClause === "output_name" && s.push(`${o.field}${o.dir || "ASC"}`);
5402
+ this.parent.dialect.orderByClause === "ordinal" ? s.push(`${u.fieldUsage.resultIndex} ${o.dir || "ASC"}`) : this.parent.dialect.orderByClause === "output_name" && s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(o.field)} ${o.dir || "ASC"}`);
5402
5403
  else
5403
5404
  throw new Error(`Unknown field in ORDER BY ${o.field}`);
5404
5405
  } else if (this.parent.dialect.orderByClause === "ordinal")
@@ -163,7 +163,7 @@ ${(0,x2e.indent)(n)}
163
163
  EXTRACT('epoch_${i}', ${n.value}) - EXTRACT('epoch_${i}', ${e.value}),
164
164
  '1970-01-01 00:00:00'::TIMESTAMP_NTZ
165
165
  )
166
- )`}sqlRegexpMatch(e,n){return(0,ar.mkExpr)`(REGEXP_INSTR(${e}, ${n}) != 0)`}sqlSampleTable(e,n){if(n!==void 0){if((0,ar.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,ar.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,ar.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.percent}))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return fM.SNOWFLAKE_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^([\w\s]+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return h2e[i.trim().toLowerCase()]}castToString(e){return`TO_VARCHAR(${e})`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}}GA.SnowflakeDialect=p2e,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(GA,t)}(WR);var YR={},nv={},xM={},dM={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;const e=tf;t.TRINO_FUNCTIONS=e.FUNCTIONS.clone(),t.TRINO_FUNCTIONS.seal()})(dM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;var e=dM;Object.defineProperty(t,"TRINO_FUNCTIONS",{enumerable:!0,get:function(){return e.TRINO_FUNCTIONS}})}(xM),Object.defineProperty(nv,"__esModule",{value:!0}),nv.TrinoDialect=void 0;const hM=Wt,wn=ne,g2e=xM,pM=ef;function gM(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function m2e(t){return["day","week","month","quarter","year"].includes(t)}const y2e={day_of_week:"dayofweek",day_of_year:"dayofyear"};function rv(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const E2e={string:"VARCHAR",number:"DOUBLE"};class A2e extends pM.Dialect{constructor(){super(...arguments),this.name="trino",this.defaultNumberType="DOUBLE",this.defaultDecimalType="DECIMAL",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!0,this.orderByClause="output_name",this.keywords=`
166
+ )`}sqlRegexpMatch(e,n){return(0,ar.mkExpr)`(REGEXP_INSTR(${e}, ${n}) != 0)`}sqlSampleTable(e,n){if(n!==void 0){if((0,ar.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,ar.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,ar.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.percent}))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return fM.SNOWFLAKE_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^([\w\s]+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return h2e[i.trim().toLowerCase()]}castToString(e){return`TO_VARCHAR(${e})`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}}GA.SnowflakeDialect=p2e,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(GA,t)}(WR);var YR={},nv={},xM={},dM={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;const e=tf;t.TRINO_FUNCTIONS=e.FUNCTIONS.clone(),t.TRINO_FUNCTIONS.seal()})(dM),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;var e=dM;Object.defineProperty(t,"TRINO_FUNCTIONS",{enumerable:!0,get:function(){return e.TRINO_FUNCTIONS}})}(xM),Object.defineProperty(nv,"__esModule",{value:!0}),nv.TrinoDialect=void 0;const hM=Wt,wn=ne,g2e=xM,pM=ef;function gM(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function m2e(t){return["day","week","month","quarter","year"].includes(t)}const y2e={day_of_week:"dayofweek",day_of_year:"dayofyear"};function rv(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const E2e={string:"VARCHAR",number:"DOUBLE"};class A2e extends pM.Dialect{constructor(){super(...arguments),this.name="trino",this.defaultNumberType="DOUBLE",this.defaultDecimalType="DECIMAL",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!1,this.orderByClause="output_name",this.keywords=`
167
167
  ALL
168
168
  AND
169
169
  ANY
@@ -261,7 +261,7 @@ ${(0,x2e.indent)(n)}
261
261
  WITHIN`.split(/\s/)}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT row_number() OVER() -1 group_set FROM UNNEST(SEQUENCE(0,${e})))`}dialectExpr(e,n){switch(n.function){case"div":return(0,wn.mkExpr)`CAST(${n.numerator} AS DOUBLE)/${n.denominator}`}return super.dialectExpr(e,n)}sqlAnyValue(e,n){return`ANY_VALUE(CASE WHEN group_set=${e} THEN ${n} END)`}buildTypeExpression(e){const n=[];for(const r of e)if((0,pM.isDialectFieldStruct)(r)){let i=`ROW(${this.buildTypeExpression(r.nestedStruct)})`;r.isArray&&(i=`array(${i})`),n.push(i)}else n.push(`${r.sqlOutputName} ${E2e[r.type]||r.type}`);return n.join(`,
262
262
  `)}sqlAggregateTurtle(e,n,r,i){const s=n.map(a=>a.sqlExpression).join(`,
263
263
  `),o=this.buildTypeExpression(n);let u=`ARRAY_AGG(CASE WHEN group_set=${e} THEN CAST(ROW(${s}) AS ROW(${o})) END ${r})`;return i!==void 0&&(u=`SLICE(${u}, 1, ${i})`),u}sqlAnyValueTurtle(e,n){const r=n.map(i=>`
264
- '${i.sqlOutputName}' VALUE ${i.sqlExpression}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN JSON_OBJECT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`ANY_VALUE(CASE WHEN group_set=${n} THEN ${e} END) as ${r}`}sqlCoaleseMeasuresInline(e,n){const r=n.map(s=>`${s.sqlExpression} as ${s.sqlOutputName}`).join(", "),i=n.map(s=>`NULL as ${s.sqlOutputName}`).join(", ");return`COALESCE(ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}) END), STRUCT(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){return s?i?`LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}`:`LEFT JOIN UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}`:i?`LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, * FROM UNNEST(${e})))) as ${n}`:`LEFT JOIN UNNEST(${e}) as ${n}`}sqlSumDistinctHashedKey(e){e=`CAST(${e} AS VARCHAR)`;const n=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 1, 15),16) as DECIMAL) * DECIMAL '4294967296' `,r=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 16, 8),16) as DECIMAL) `;return`(${n} + ${r}) * 0.000000001`}sqlGenerateUUID(){return"GENERATE_UUID()"}sqlFieldReference(e,n,r,i,s){return`${e}.${n}`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`UNNEST(${r})`}sqlCreateFunction(e,n){return`CREATE TEMPORARY FUNCTION ${e}(__param ANY TYPE) AS ((
264
+ '${i.sqlOutputName}' VALUE ${i.sqlExpression}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN JSON_OBJECT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`ANY_VALUE(CASE WHEN group_set=${n} THEN ${e} END) as ${r}`}sqlCoaleseMeasuresInline(e,n){const r=n.map(s=>`${s.sqlExpression} as ${s.sqlOutputName}`).join(", "),i=n.map(s=>`NULL as ${s.sqlOutputName}`).join(", ");return`COALESCE(ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}) END), STRUCT(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){const u=r.map(a=>this.sqlMaybeQuoteIdentifier(a.sqlOutputName));return s?i?`,UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}`:`,UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}`:i?`,UNNEST(zip_with(a, SEQUENCE(1,cardinality(a)), (r,__row_id) -> (r, __row_id))) as ${n}_outer(${n},__row_id)`:`,UNNEST(${e}) as ${n}(${u.join(", ")})`}sqlSumDistinctHashedKey(e){e=`CAST(${e} AS VARCHAR)`;const n=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 1, 15),16) as DECIMAL) * DECIMAL '4294967296' `,r=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 16, 8),16) as DECIMAL) `;return`(${n} + ${r}) * 0.000000001`}sqlGenerateUUID(){return"UUID()"}sqlFieldReference(e,n,r,i,s){return n==="__row_id"?`${e}_outer.__row_id`:`${e}.${n}`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`UNNEST(${r})`}sqlCreateFunction(e,n){return`CREATE TEMPORARY FUNCTION ${e}(__param ANY TYPE) AS ((
265
265
  ${(0,hM.indent)(n)}));
266
266
  `}sqlCreateTableAsSelect(e,n){return`
267
267
  CREATE TABLE IF NOT EXISTS \`${e}\`
@@ -272,7 +272,7 @@ AS (
272
272
  ${(0,hM.indent)(n)}
273
273
  );
274
274
  `}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
275
- `}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return e}sqlNow(){return(0,wn.mkExpr)`CURRENT_TIMESTAMP()`}sqlTrunc(e,n,r){const i=rv(e),s=i?`, "${i}"`:"";return n.valueType==="date"?m2e(r)?(0,wn.mkExpr)`DATE_TRUNC(${n.value},${r})`:(0,wn.mkExpr)`TIMESTAMP(${n.value}${s})`:(0,wn.mkExpr)`TIMESTAMP_TRUNC(${n.value},${r}${s})`}sqlExtract(e,n,r){const i=y2e[r]||r,s=n.valueType==="timestamp"&&rv(e),o=s?` AT TIME ZONE '${s}'`:"";return(0,wn.mkExpr)`EXTRACT(${i} FROM ${n.value}${o})`}sqlAlterTime(e,n,r,i){let s=n.value,o=n.valueType;i!=="day"&&gM(i)?(o="timestamp",n.valueType!=="timestamp"&&(s=(0,wn.mkExpr)`TIMESTAMP(${s})`)):n.valueType==="timestamp"&&(s=(0,wn.mkExpr)`DATETIME(${s})`,o="datetime");const u=o.toUpperCase()+(e==="+"?"_ADD":"_SUB"),a=(0,wn.mkExpr)`${u}(${s}, INTERVAL ${r} ${i})`;return o===n.valueType?a:(0,wn.mkExpr)`${n.valueType.toUpperCase()}(${a})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=rv(e);if(r==="timestamp::date"&&i)return(0,wn.mkExpr)`DATE(${n.expr},'${i}')`;if(r==="date::timestamp"&&i)return(0,wn.mkExpr)`TIMESTAMP(${n.expr}, '${i}')`;if(n.srcType!==n.dstType){const s=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw,o=n.safe?"SAFE_CAST":"CAST";return(0,wn.mkExpr)`${o}(${n.expr} AS ${s})`}return n.expr}sqlRegexpMatch(e,n){return(0,wn.mkExpr)`REGEXP_CONTAINS(${e}, ${n})`}sqlLiteralTime(e,n,r,i){if(r==="date")return`DATE('${n}')`;if(r==="timestamp"){let s=`'${n}'`;const o=i||rv(e);return o&&o!=="UTC"&&(s+=`,'${o}'`),`TIMESTAMP(${s})`}else throw new Error(`Unsupported Literal time format ${r}`)}sqlMeasureTime(e,n,r){const i={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}};let s=e.value,o=n.value;if(i[r]){const{use:u,ratio:a}=i[r];if(!gM(u))throw new Error(`Measure in '${u} not implemented`);if(e.valueType!==n.valueType)throw new Error("Can't measure difference between different types");e.valueType==="date"&&(s=(0,wn.mkExpr)`TIMESTAMP(${s})`,o=(0,wn.mkExpr)`TIMESTAMP(${o})`);let l=(0,wn.mkExpr)`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=(0,wn.mkExpr)`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${r} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,wn.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,wn.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,wn.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 g2e.TRINO_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"BIGINT":"DOUBLE":e.type==="string"?"VARCHAR":e.type}sqlTypeToMalloyType(e){}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}nv.TrinoDialect=A2e,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(nv,t)}(YR);var bu={};Object.defineProperty(bu,"__esModule",{value:!0}),bu.getDialectFunction=bu.registerDialect=bu.getDialect=void 0;const v2e=QR,S2e=zR,_2e=WR,C2e=NR,b2e=YR,KR=new Map;function T2e(t){const e=KR.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}bu.getDialect=T2e;function ih(t){KR.set(t.name,t)}bu.registerDialect=ih,ih(new S2e.PostgresDialect),ih(new C2e.StandardSQLDialect),ih(new v2e.DuckDBDialect),ih(new _2e.SnowflakeDialect),ih(new b2e.TrinoDialect);function mM(t,e){return t.params.length===e.params.length&&t.params.every((n,r)=>{const i=e.params[r];return n.isVariadic===i.isVariadic&&n.name===i.name&&n.allowedTypes.length===i.allowedTypes.length&&n.allowedTypes.every(s=>i.allowedTypes.some(o=>s.dataType===o.dataType&&s.expressionType===o.expressionType))})}function R2e(t,e){return mM(t,e)}function O2e(t,e){return t.returnType.dataType===e.returnType.dataType&&t.returnType.expressionType===e.returnType.expressionType}function N2e(t){const e={type:"function",name:t,overloads:[]};let n=!1;for(const r of KR.values()){const i=r.getGlobalFunctionDef(t);if(i){for(const s of i){let o=!1;for(const u of e.overloads)if(R2e(s,u)){if(!mM(s,u))throw new Error("params are compatible but not equal");if(!O2e(s,u))throw new Error("params match but return types differ!");u.dialect[r.name]={e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit},o=!0}o||e.overloads.push({returnType:s.returnType,params:s.params,dialect:{[r.name]:{e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit}},needsWindowOrderBy:s.needsWindowOrderBy,between:s.between,isSymmetric:s.isSymmetric})}n=!0}}return n?e:void 0}bu.getDialectFunction=N2e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FUNCTIONS=t.getDialectFunction=t.registerDialect=t.getDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.params=t.param=t.sqlFragment=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=Se;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"sqlFragment",{enumerable:!0,get:function(){return e.sqlFragment}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"params",{enumerable:!0,get:function(){return e.params}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var n=ef;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return n.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return n.qtz}});var r=NR;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return r.StandardSQLDialect}});var i=zR;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return i.PostgresDialect}});var s=QR;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}});var o=WR;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return o.SnowflakeDialect}});var u=YR;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return u.TrinoDialect}});var a=bu;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return a.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return a.registerDialect}}),Object.defineProperty(t,"getDialectFunction",{enumerable:!0,get:function(){return a.getDialectFunction}});var l=tf;Object.defineProperty(t,"FUNCTIONS",{enumerable:!0,get:function(){return l.FUNCTIONS}})}(BE);var Tu={},vf={};Object.defineProperty(vf,"__esModule",{value:!0}),vf.QueryModel=vf.Segment=void 0;const D2e=BE,F2e=U1,je=ne,Tr=Wt;function yM(t){return t.map(e=>encodeURIComponent(e)).join("/")}function XR(t){return`'${t}'`}function EM(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}class w2e extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class ep{constructor(e=!0,n){this.parent=n,this.withs=[],this.udfs=[],this.pdts=[],this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Tr.indent)(`
275
+ `}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return'"'+e+'"'}sqlNow(){return(0,wn.mkExpr)`CURRENT_TIMESTAMP()`}sqlTrunc(e,n,r){const i=rv(e),s=i?`, "${i}"`:"";return n.valueType==="date"?m2e(r)?(0,wn.mkExpr)`DATE_TRUNC(${n.value},${r})`:(0,wn.mkExpr)`TIMESTAMP(${n.value}${s})`:(0,wn.mkExpr)`TIMESTAMP_TRUNC(${n.value},${r}${s})`}sqlExtract(e,n,r){const i=y2e[r]||r,s=n.valueType==="timestamp"&&rv(e),o=s?` AT TIME ZONE '${s}'`:"";return(0,wn.mkExpr)`EXTRACT(${i} FROM ${n.value}${o})`}sqlAlterTime(e,n,r,i){let s=n.value,o=n.valueType;i!=="day"&&gM(i)?(o="timestamp",n.valueType!=="timestamp"&&(s=(0,wn.mkExpr)`TIMESTAMP(${s})`)):n.valueType==="timestamp"&&(s=(0,wn.mkExpr)`DATETIME(${s})`,o="datetime");const u=o.toUpperCase()+(e==="+"?"_ADD":"_SUB"),a=(0,wn.mkExpr)`${u}(${s}, INTERVAL ${r} ${i})`;return o===n.valueType?a:(0,wn.mkExpr)`${n.valueType.toUpperCase()}(${a})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=rv(e);if(r==="timestamp::date"&&i)return(0,wn.mkExpr)`DATE(${n.expr},'${i}')`;if(r==="date::timestamp"&&i)return(0,wn.mkExpr)`TIMESTAMP(${n.expr}, '${i}')`;if(n.srcType!==n.dstType){const s=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw,o=n.safe?"SAFE_CAST":"CAST";return(0,wn.mkExpr)`${o}(${n.expr} AS ${s})`}return n.expr}sqlRegexpMatch(e,n){return(0,wn.mkExpr)`REGEXP_LIKE(${e}, ${n})`}sqlLiteralTime(e,n,r,i){if(r==="date")return`DATE('${n}')`;if(r==="timestamp"){let s=`'${n}'`;const o=i||rv(e);return o&&o!=="UTC"&&(s+=`,'${o}'`),`TIMESTAMP(${s})`}else throw new Error(`Unsupported Literal time format ${r}`)}sqlMeasureTime(e,n,r){const i={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}};let s=e.value,o=n.value;if(i[r]){const{use:u,ratio:a}=i[r];if(!gM(u))throw new Error(`Measure in '${u} not implemented`);if(e.valueType!==n.valueType)throw new Error("Can't measure difference between different types");e.valueType==="date"&&(s=(0,wn.mkExpr)`TIMESTAMP(${s})`,o=(0,wn.mkExpr)`TIMESTAMP(${o})`);let l=(0,wn.mkExpr)`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=(0,wn.mkExpr)`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${r} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,wn.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,wn.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,wn.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 g2e.TRINO_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"BIGINT":"DOUBLE":e.type==="string"?"VARCHAR":e.type}sqlTypeToMalloyType(e){}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}nv.TrinoDialect=A2e,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(nv,t)}(YR);var bu={};Object.defineProperty(bu,"__esModule",{value:!0}),bu.getDialectFunction=bu.registerDialect=bu.getDialect=void 0;const v2e=QR,S2e=zR,_2e=WR,C2e=NR,b2e=YR,KR=new Map;function T2e(t){const e=KR.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}bu.getDialect=T2e;function ih(t){KR.set(t.name,t)}bu.registerDialect=ih,ih(new S2e.PostgresDialect),ih(new C2e.StandardSQLDialect),ih(new v2e.DuckDBDialect),ih(new _2e.SnowflakeDialect),ih(new b2e.TrinoDialect);function mM(t,e){return t.params.length===e.params.length&&t.params.every((n,r)=>{const i=e.params[r];return n.isVariadic===i.isVariadic&&n.name===i.name&&n.allowedTypes.length===i.allowedTypes.length&&n.allowedTypes.every(s=>i.allowedTypes.some(o=>s.dataType===o.dataType&&s.expressionType===o.expressionType))})}function R2e(t,e){return mM(t,e)}function O2e(t,e){return t.returnType.dataType===e.returnType.dataType&&t.returnType.expressionType===e.returnType.expressionType}function N2e(t){const e={type:"function",name:t,overloads:[]};let n=!1;for(const r of KR.values()){const i=r.getGlobalFunctionDef(t);if(i){for(const s of i){let o=!1;for(const u of e.overloads)if(R2e(s,u)){if(!mM(s,u))throw new Error("params are compatible but not equal");if(!O2e(s,u))throw new Error("params match but return types differ!");u.dialect[r.name]={e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit},o=!0}o||e.overloads.push({returnType:s.returnType,params:s.params,dialect:{[r.name]:{e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit}},needsWindowOrderBy:s.needsWindowOrderBy,between:s.between,isSymmetric:s.isSymmetric})}n=!0}}return n?e:void 0}bu.getDialectFunction=N2e,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FUNCTIONS=t.getDialectFunction=t.registerDialect=t.getDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.params=t.param=t.sqlFragment=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=Se;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"sqlFragment",{enumerable:!0,get:function(){return e.sqlFragment}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"params",{enumerable:!0,get:function(){return e.params}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var n=ef;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return n.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return n.qtz}});var r=NR;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return r.StandardSQLDialect}});var i=zR;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return i.PostgresDialect}});var s=QR;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}});var o=WR;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return o.SnowflakeDialect}});var u=YR;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return u.TrinoDialect}});var a=bu;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return a.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return a.registerDialect}}),Object.defineProperty(t,"getDialectFunction",{enumerable:!0,get:function(){return a.getDialectFunction}});var l=tf;Object.defineProperty(t,"FUNCTIONS",{enumerable:!0,get:function(){return l.FUNCTIONS}})}(BE);var Tu={},vf={};Object.defineProperty(vf,"__esModule",{value:!0}),vf.QueryModel=vf.Segment=void 0;const D2e=BE,F2e=U1,je=ne,Tr=Wt;function yM(t){return t.map(e=>encodeURIComponent(e)).join("/")}function XR(t){return`'${t}'`}function EM(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}class w2e extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class ep{constructor(e=!0,n){this.parent=n,this.withs=[],this.udfs=[],this.pdts=[],this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,Tr.indent)(`
276
276
  (${e})
277
277
  `))}addUDF(e,n,r){let{sql:i,lastStageName:s}=e.combineStages(!0);if(s===void 0)throw new Error("Internal Error: no stage to combine");i+=n.sqlCreateFunctionCombineLastStage(s,r);const o=`${n.udfPrefix}${this.root().udfs.length}`;return i=n.sqlCreateFunction(o,i),this.root().udfs.push(i),o}addPDT(e,n){const r=this.combineStages(!1).sql+this.withs[this.withs.length-1],i="scratch."+e+(0,Tr.generateHash)(r);return this.root().pdts.push(n.sqlCreateTableAsSelect(i,r)),i}combineStages(e){if(!this.useCTE)return{sql:this.withs[0],lastStageName:this.withs[0]};let n=this.getName(0),r="WITH ",i="";for(let s=0;s<this.withs.length-(e?0:1);s++){const o=this.withs[s];if(n=this.getName(s),o===void 0)throw new Error(`Expected sql WITH to be present for stage ${n}.`);i+=`${r}${n} AS (
278
278
  ${(0,Tr.indent)(o)})
@@ -303,7 +303,7 @@ ${(0,Tr.indent)(f)}) AS ${n.alias}
303
303
  ON ${a}
304
304
  `,r}}else if(s.type==="nested"){if(i.parent===void 0||n.parent===void 0)throw new Error("Internal Error, nested structure with no parent.");const u=this.parent.dialect.sqlFieldReference(i.parent.getSQLIdentifier(),s.fieldName,"struct",i.parent.fieldDef.structRelationship.type==="nested",this.parent.fieldDef.structRelationship.type==="nested"&&this.parent.fieldDef.structRelationship.isArray);r+=`${this.parent.dialect.sqlUnnestAlias(u,n.alias,n.getDialectFieldList(),n.makeUniqueKey,s.isArray,this.inNestedPipeline())}
305
305
  `}else throw s.type==="inline"?new Error("Internal Error: inline structs should never appear in join trees"):new Error(`Join type not implemented ${JSON.stringify(i.fieldDef.structRelationship)}`);for(const u of n.children)r+=this.generateSQLJoinBlock(e,u);return r}generateSQLPassthroughKeys(e){let n="";if(e.dialect.name==="standardsql"){const r=["_TABLE_SUFFIX","_PARTITIONDATE","_PARTITIONTIME"].filter(i=>e.getChildByName(i)!==void 0);r.length>0&&(n=", "+r.join(", "))}return n}generateSQLJoins(e){let n="";const[[,r]]=this.rootResult.joins,i=r.queryStruct;let s=i.structSourceSQL(e);if((0,je.isIndexSegment)(this.firstSegment)&&(s=this.parent.dialect.sqlSampleTable(s,this.firstSegment.sample),this.firstSegment.sample&&(s=e.addStage(`SELECT * from ${s} as x limit 100000 `))),i.fieldDef.structRelationship.type==="basetable"){if(r.makeUniqueKey){const u=this.generateSQLPassthroughKeys(i);s=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${u} FROM ${s} as x)`}n+=`FROM ${s} as ${r.alias}
306
- `}else throw new Error("Internal Error, queries must start from a basetable");for(const u of r.children)n+=this.generateSQLJoinBlock(e,u);return n}genereateSQLOrderBy(e,n){let r="";if(this.firstSegment.type==="project"&&!e.orderBy||this.fieldDef.pipeline.length>1&&e.limit===void 0||n.getRepeatedResultType()==="inline_all_numbers"||this.isJoinedSubquery&&this.fieldDef.pipeline.length===1&&e.limit===void 0)return"";const i=e.orderBy||n.calculateDefaultOrderBy(),s=[];for(const o of i)if(typeof o.field=="string"){const u=n.getField(o.field);if(u&&u.fieldUsage.type==="result")this.parent.dialect.orderByClause==="ordinal"?s.push(`${u.fieldUsage.resultIndex} ${o.dir||"ASC"}`):this.parent.dialect.orderByClause==="output_name"&&s.push(`${o.field}${o.dir||"ASC"}`);else throw new Error(`Unknown field in ORDER BY ${o.field}`)}else if(this.parent.dialect.orderByClause==="ordinal")s.push(`${o.field} ${o.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="output_name"){const u=n.getFieldByNumber(o.field);s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(u.name)} ${o.dir||"ASC"}`)}return s.length>0&&(r=this.parent.dialect.sqlOrderBy(s)+`
306
+ `}else throw new Error("Internal Error, queries must start from a basetable");for(const u of r.children)n+=this.generateSQLJoinBlock(e,u);return n}genereateSQLOrderBy(e,n){let r="";if(this.firstSegment.type==="project"&&!e.orderBy||this.fieldDef.pipeline.length>1&&e.limit===void 0||n.getRepeatedResultType()==="inline_all_numbers"||this.isJoinedSubquery&&this.fieldDef.pipeline.length===1&&e.limit===void 0)return"";const i=e.orderBy||n.calculateDefaultOrderBy(),s=[];for(const o of i)if(typeof o.field=="string"){const u=n.getField(o.field);if(u&&u.fieldUsage.type==="result")this.parent.dialect.orderByClause==="ordinal"?s.push(`${u.fieldUsage.resultIndex} ${o.dir||"ASC"}`):this.parent.dialect.orderByClause==="output_name"&&s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(o.field)} ${o.dir||"ASC"}`);else throw new Error(`Unknown field in ORDER BY ${o.field}`)}else if(this.parent.dialect.orderByClause==="ordinal")s.push(`${o.field} ${o.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="output_name"){const u=n.getFieldByNumber(o.field);s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(u.name)} ${o.dir||"ASC"}`)}return s.length>0&&(r=this.parent.dialect.sqlOrderBy(s)+`
307
307
  `),r}generateSimpleSQL(e){let n="";n+=`SELECT
308
308
  `;const r=[];for(const[i,s]of this.rootResult.allFields){const o=s,u=this.parent.dialect.sqlMaybeQuoteIdentifier(i);o.fieldUsage.type==="result"&&r.push(` ${o.f.generateExpression(this.rootResult)} as ${u}`)}if(n+=(0,Tr.indent)(r.join(`,
309
309
  `))+`
@@ -4531,7 +4531,7 @@ const vde = {
4531
4531
  };
4532
4532
  class _de extends eP.Dialect {
4533
4533
  constructor() {
4534
- super(...arguments), this.name = "trino", this.defaultNumberType = "DOUBLE", this.defaultDecimalType = "DECIMAL", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, this.unnestWithNumbers = !1, this.defaultSampling = { enable: !1 }, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !0, this.supportsQualify = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.cantPartitionWindowFunctionsOnExpressions = !0, this.orderByClause = "output_name", this.keywords = `
4534
+ super(...arguments), this.name = "trino", this.defaultNumberType = "DOUBLE", this.defaultDecimalType = "DECIMAL", this.udfPrefix = "__udf", this.hasFinalStage = !1, this.divisionIsInteger = !0, this.supportsSumDistinctFunction = !1, this.unnestWithNumbers = !1, this.defaultSampling = { enable: !1 }, this.supportUnnestArrayAgg = !1, this.supportsAggDistinct = !1, this.supportsCTEinCoorelatedSubQueries = !1, this.dontUnionIndex = !0, this.supportsQualify = !0, this.supportsSafeCast = !0, this.supportsNesting = !0, this.cantPartitionWindowFunctionsOnExpressions = !1, this.orderByClause = "output_name", this.keywords = `
4535
4535
  ALL
4536
4536
  AND
4537
4537
  ANY
@@ -4682,7 +4682,8 @@ class _de extends eP.Dialect {
4682
4682
  // BigQuery will allocate more resources if we use a CROSS JOIN so we do that instead.
4683
4683
  //
4684
4684
  sqlUnnestAlias(e, n, r, i, s, o) {
4685
- return s ? i ? `LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}` : `LEFT JOIN UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}` : i ? `LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, * FROM UNNEST(${e})))) as ${n}` : `LEFT JOIN UNNEST(${e}) as ${n}`;
4685
+ const u = r.map((a) => this.sqlMaybeQuoteIdentifier(a.sqlOutputName));
4686
+ return s ? i ? `,UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}` : `,UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}` : i ? `,UNNEST(zip_with(a, SEQUENCE(1,cardinality(a)), (r,__row_id) -> (r, __row_id))) as ${n}_outer(${n},__row_id)` : `,UNNEST(${e}) as ${n}(${u.join(", ")})`;
4686
4687
  }
4687
4688
  sqlSumDistinctHashedKey(e) {
4688
4689
  e = `CAST(${e} AS VARCHAR)`;
@@ -4690,10 +4691,10 @@ class _de extends eP.Dialect {
4690
4691
  return `(${n} + ${r}) * 0.000000001`;
4691
4692
  }
4692
4693
  sqlGenerateUUID() {
4693
- return "GENERATE_UUID()";
4694
+ return "UUID()";
4694
4695
  }
4695
4696
  sqlFieldReference(e, n, r, i, s) {
4696
- return `${e}.${n}`;
4697
+ return n === "__row_id" ? `${e}_outer.__row_id` : `${e}.${n}`;
4697
4698
  }
4698
4699
  sqlUnnestPipelineHead(e, n) {
4699
4700
  let r = n;
@@ -4723,7 +4724,7 @@ ${(0, Z7.indent)(n)}
4723
4724
  return `(SELECT AS STRUCT ${e}.*)`;
4724
4725
  }
4725
4726
  sqlMaybeQuoteIdentifier(e) {
4726
- return e;
4727
+ return '"' + e + '"';
4727
4728
  }
4728
4729
  sqlNow() {
4729
4730
  return (0, Nn.mkExpr)`CURRENT_TIMESTAMP()`;
@@ -4758,7 +4759,7 @@ ${(0, Z7.indent)(n)}
4758
4759
  return n.expr;
4759
4760
  }
4760
4761
  sqlRegexpMatch(e, n) {
4761
- return (0, Nn.mkExpr)`REGEXP_CONTAINS(${e}, ${n})`;
4762
+ return (0, Nn.mkExpr)`REGEXP_LIKE(${e}, ${n})`;
4762
4763
  }
4763
4764
  sqlLiteralTime(e, n, r, i) {
4764
4765
  if (r === "date")
@@ -6221,7 +6222,7 @@ ${(0, vr.indent)(f)}) AS ${n.alias}
6221
6222
  if (typeof o.field == "string") {
6222
6223
  const u = n.getField(o.field);
6223
6224
  if (u && u.fieldUsage.type === "result")
6224
- this.parent.dialect.orderByClause === "ordinal" ? s.push(`${u.fieldUsage.resultIndex} ${o.dir || "ASC"}`) : this.parent.dialect.orderByClause === "output_name" && s.push(`${o.field}${o.dir || "ASC"}`);
6225
+ this.parent.dialect.orderByClause === "ordinal" ? s.push(`${u.fieldUsage.resultIndex} ${o.dir || "ASC"}`) : this.parent.dialect.orderByClause === "output_name" && s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(o.field)} ${o.dir || "ASC"}`);
6225
6226
  else
6226
6227
  throw new Error(`Unknown field in ORDER BY ${o.field}`);
6227
6228
  } else if (this.parent.dialect.orderByClause === "ordinal")
@@ -163,7 +163,7 @@ ${(0,hde.indent)(n)}
163
163
  EXTRACT('epoch_${i}', ${n.value}) - EXTRACT('epoch_${i}', ${e.value}),
164
164
  '1970-01-01 00:00:00'::TIMESTAMP_NTZ
165
165
  )
166
- )`}sqlRegexpMatch(e,n){return(0,ir.mkExpr)`(REGEXP_INSTR(${e}, ${n}) != 0)`}sqlSampleTable(e,n){if(n!==void 0){if((0,ir.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,ir.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,ir.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.percent}))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return QP.SNOWFLAKE_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^([\w\s]+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return gde[i.trim().toLowerCase()]}castToString(e){return`TO_VARCHAR(${e})`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}}$A.SnowflakeDialect=mde,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($A,t)}(iD);var oD={},GA={},GP={},WP={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;const e=zc;t.TRINO_FUNCTIONS=e.FUNCTIONS.clone(),t.TRINO_FUNCTIONS.seal()})(WP),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;var e=WP;Object.defineProperty(t,"TRINO_FUNCTIONS",{enumerable:!0,get:function(){return e.TRINO_FUNCTIONS}})}(GP),Object.defineProperty(GA,"__esModule",{value:!0}),GA.TrinoDialect=void 0;const VP=Gt,Nn=ne,yde=GP,YP=Hc;function XP(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function Ede(t){return["day","week","month","quarter","year"].includes(t)}const Ade={day_of_week:"dayofweek",day_of_year:"dayofyear"};function WA(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const Sde={string:"VARCHAR",number:"DOUBLE"};class vde extends YP.Dialect{constructor(){super(...arguments),this.name="trino",this.defaultNumberType="DOUBLE",this.defaultDecimalType="DECIMAL",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!0,this.orderByClause="output_name",this.keywords=`
166
+ )`}sqlRegexpMatch(e,n){return(0,ir.mkExpr)`(REGEXP_INSTR(${e}, ${n}) != 0)`}sqlSampleTable(e,n){if(n!==void 0){if((0,ir.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,ir.isSamplingRows)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.rows} ROWS))`;if((0,ir.isSamplingPercent)(n))return`(SELECT * FROM ${e} TABLESAMPLE (${n.percent}))`}return e}sqlOrderBy(e){return`ORDER BY ${e.map(n=>`${n} NULLS LAST`).join(",")}`}sqlLiteralString(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}sqlLiteralRegexp(e){return"'"+e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"}getGlobalFunctionDef(e){return QP.SNOWFLAKE_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"integer":"double":e.type}sqlTypeToMalloyType(e){var n,r;const i=(r=(n=e.match(/^([\w\s]+)/))===null||n===void 0?void 0:n.at(0))!==null&&r!==void 0?r:e;return gde[i.trim().toLowerCase()]}castToString(e){return`TO_VARCHAR(${e})`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),[\]0-9]*$/)!==null}}$A.SnowflakeDialect=mde,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($A,t)}(iD);var oD={},GA={},GP={},WP={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;const e=zc;t.TRINO_FUNCTIONS=e.FUNCTIONS.clone(),t.TRINO_FUNCTIONS.seal()})(WP),function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.TRINO_FUNCTIONS=void 0;var e=WP;Object.defineProperty(t,"TRINO_FUNCTIONS",{enumerable:!0,get:function(){return e.TRINO_FUNCTIONS}})}(GP),Object.defineProperty(GA,"__esModule",{value:!0}),GA.TrinoDialect=void 0;const VP=Gt,Nn=ne,yde=GP,YP=Hc;function XP(t){return["microsecond","millisecond","second","minute","hour","day"].includes(t)}function Ede(t){return["day","week","month","quarter","year"].includes(t)}const Ade={day_of_week:"dayofweek",day_of_year:"dayofyear"};function WA(t){const e=t.queryTimezone;if(e&&e!=="UTC")return e}const Sde={string:"VARCHAR",number:"DOUBLE"};class vde extends YP.Dialect{constructor(){super(...arguments),this.name="trino",this.defaultNumberType="DOUBLE",this.defaultDecimalType="DECIMAL",this.udfPrefix="__udf",this.hasFinalStage=!1,this.divisionIsInteger=!0,this.supportsSumDistinctFunction=!1,this.unnestWithNumbers=!1,this.defaultSampling={enable:!1},this.supportUnnestArrayAgg=!1,this.supportsAggDistinct=!1,this.supportsCTEinCoorelatedSubQueries=!1,this.dontUnionIndex=!0,this.supportsQualify=!0,this.supportsSafeCast=!0,this.supportsNesting=!0,this.cantPartitionWindowFunctionsOnExpressions=!1,this.orderByClause="output_name",this.keywords=`
167
167
  ALL
168
168
  AND
169
169
  ANY
@@ -261,7 +261,7 @@ ${(0,hde.indent)(n)}
261
261
  WITHIN`.split(/\s/)}quoteTablePath(e){return e}sqlGroupSetTable(e){return`CROSS JOIN (SELECT row_number() OVER() -1 group_set FROM UNNEST(SEQUENCE(0,${e})))`}dialectExpr(e,n){switch(n.function){case"div":return(0,Nn.mkExpr)`CAST(${n.numerator} AS DOUBLE)/${n.denominator}`}return super.dialectExpr(e,n)}sqlAnyValue(e,n){return`ANY_VALUE(CASE WHEN group_set=${e} THEN ${n} END)`}buildTypeExpression(e){const n=[];for(const r of e)if((0,YP.isDialectFieldStruct)(r)){let i=`ROW(${this.buildTypeExpression(r.nestedStruct)})`;r.isArray&&(i=`array(${i})`),n.push(i)}else n.push(`${r.sqlOutputName} ${Sde[r.type]||r.type}`);return n.join(`,
262
262
  `)}sqlAggregateTurtle(e,n,r,i){const s=n.map(a=>a.sqlExpression).join(`,
263
263
  `),o=this.buildTypeExpression(n);let u=`ARRAY_AGG(CASE WHEN group_set=${e} THEN CAST(ROW(${s}) AS ROW(${o})) END ${r})`;return i!==void 0&&(u=`SLICE(${u}, 1, ${i})`),u}sqlAnyValueTurtle(e,n){const r=n.map(i=>`
264
- '${i.sqlOutputName}' VALUE ${i.sqlExpression}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN JSON_OBJECT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`ANY_VALUE(CASE WHEN group_set=${n} THEN ${e} END) as ${r}`}sqlCoaleseMeasuresInline(e,n){const r=n.map(s=>`${s.sqlExpression} as ${s.sqlOutputName}`).join(", "),i=n.map(s=>`NULL as ${s.sqlOutputName}`).join(", ");return`COALESCE(ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}) END), STRUCT(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){return s?i?`LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}`:`LEFT JOIN UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}`:i?`LEFT JOIN UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, * FROM UNNEST(${e})))) as ${n}`:`LEFT JOIN UNNEST(${e}) as ${n}`}sqlSumDistinctHashedKey(e){e=`CAST(${e} AS VARCHAR)`;const n=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 1, 15),16) as DECIMAL) * DECIMAL '4294967296' `,r=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 16, 8),16) as DECIMAL) `;return`(${n} + ${r}) * 0.000000001`}sqlGenerateUUID(){return"GENERATE_UUID()"}sqlFieldReference(e,n,r,i,s){return`${e}.${n}`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`UNNEST(${r})`}sqlCreateFunction(e,n){return`CREATE TEMPORARY FUNCTION ${e}(__param ANY TYPE) AS ((
264
+ '${i.sqlOutputName}' VALUE ${i.sqlExpression}`).join(", ");return`ANY_VALUE(CASE WHEN group_set=${e} THEN JSON_OBJECT(${r}))`}sqlAnyValueLastTurtle(e,n,r){return`ANY_VALUE(CASE WHEN group_set=${n} THEN ${e} END) as ${r}`}sqlCoaleseMeasuresInline(e,n){const r=n.map(s=>`${s.sqlExpression} as ${s.sqlOutputName}`).join(", "),i=n.map(s=>`NULL as ${s.sqlOutputName}`).join(", ");return`COALESCE(ANY_VALUE(CASE WHEN group_set=${e} THEN STRUCT(${r}) END), STRUCT(${i}))`}sqlUnnestAlias(e,n,r,i,s,o){const u=r.map(a=>this.sqlMaybeQuoteIdentifier(a.sqlOutputName));return s?i?`,UNNEST(ARRAY(( SELECT AS STRUCT row_number() over() as __row_id, value FROM UNNEST(${e}) value))) as ${n}`:`,UNNEST(ARRAY((SELECT AS STRUCT value FROM unnest(${e}) value))) as ${n}`:i?`,UNNEST(zip_with(a, SEQUENCE(1,cardinality(a)), (r,__row_id) -> (r, __row_id))) as ${n}_outer(${n},__row_id)`:`,UNNEST(${e}) as ${n}(${u.join(", ")})`}sqlSumDistinctHashedKey(e){e=`CAST(${e} AS VARCHAR)`;const n=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 1, 15),16) as DECIMAL) * DECIMAL '4294967296' `,r=`cast(from_base(substr(to_hex(md5(to_utf8(${e}))), 16, 8),16) as DECIMAL) `;return`(${n} + ${r}) * 0.000000001`}sqlGenerateUUID(){return"UUID()"}sqlFieldReference(e,n,r,i,s){return n==="__row_id"?`${e}_outer.__row_id`:`${e}.${n}`}sqlUnnestPipelineHead(e,n){let r=n;return e&&(r=`[${r}]`),`UNNEST(${r})`}sqlCreateFunction(e,n){return`CREATE TEMPORARY FUNCTION ${e}(__param ANY TYPE) AS ((
265
265
  ${(0,VP.indent)(n)}));
266
266
  `}sqlCreateTableAsSelect(e,n){return`
267
267
  CREATE TABLE IF NOT EXISTS \`${e}\`
@@ -272,7 +272,7 @@ AS (
272
272
  ${(0,VP.indent)(n)}
273
273
  );
274
274
  `}sqlCreateFunctionCombineLastStage(e){return`SELECT ARRAY((SELECT AS STRUCT * FROM ${e}))
275
- `}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return e}sqlNow(){return(0,Nn.mkExpr)`CURRENT_TIMESTAMP()`}sqlTrunc(e,n,r){const i=WA(e),s=i?`, "${i}"`:"";return n.valueType==="date"?Ede(r)?(0,Nn.mkExpr)`DATE_TRUNC(${n.value},${r})`:(0,Nn.mkExpr)`TIMESTAMP(${n.value}${s})`:(0,Nn.mkExpr)`TIMESTAMP_TRUNC(${n.value},${r}${s})`}sqlExtract(e,n,r){const i=Ade[r]||r,s=n.valueType==="timestamp"&&WA(e),o=s?` AT TIME ZONE '${s}'`:"";return(0,Nn.mkExpr)`EXTRACT(${i} FROM ${n.value}${o})`}sqlAlterTime(e,n,r,i){let s=n.value,o=n.valueType;i!=="day"&&XP(i)?(o="timestamp",n.valueType!=="timestamp"&&(s=(0,Nn.mkExpr)`TIMESTAMP(${s})`)):n.valueType==="timestamp"&&(s=(0,Nn.mkExpr)`DATETIME(${s})`,o="datetime");const u=o.toUpperCase()+(e==="+"?"_ADD":"_SUB"),a=(0,Nn.mkExpr)`${u}(${s}, INTERVAL ${r} ${i})`;return o===n.valueType?a:(0,Nn.mkExpr)`${n.valueType.toUpperCase()}(${a})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=WA(e);if(r==="timestamp::date"&&i)return(0,Nn.mkExpr)`DATE(${n.expr},'${i}')`;if(r==="date::timestamp"&&i)return(0,Nn.mkExpr)`TIMESTAMP(${n.expr}, '${i}')`;if(n.srcType!==n.dstType){const s=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw,o=n.safe?"SAFE_CAST":"CAST";return(0,Nn.mkExpr)`${o}(${n.expr} AS ${s})`}return n.expr}sqlRegexpMatch(e,n){return(0,Nn.mkExpr)`REGEXP_CONTAINS(${e}, ${n})`}sqlLiteralTime(e,n,r,i){if(r==="date")return`DATE('${n}')`;if(r==="timestamp"){let s=`'${n}'`;const o=i||WA(e);return o&&o!=="UTC"&&(s+=`,'${o}'`),`TIMESTAMP(${s})`}else throw new Error(`Unsupported Literal time format ${r}`)}sqlMeasureTime(e,n,r){const i={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}};let s=e.value,o=n.value;if(i[r]){const{use:u,ratio:a}=i[r];if(!XP(u))throw new Error(`Measure in '${u} not implemented`);if(e.valueType!==n.valueType)throw new Error("Can't measure difference between different types");e.valueType==="date"&&(s=(0,Nn.mkExpr)`TIMESTAMP(${s})`,o=(0,Nn.mkExpr)`TIMESTAMP(${o})`);let l=(0,Nn.mkExpr)`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=(0,Nn.mkExpr)`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${r} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,Nn.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,Nn.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,Nn.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.TRINO_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"BIGINT":"DOUBLE":e.type==="string"?"VARCHAR":e.type}sqlTypeToMalloyType(e){}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}GA.TrinoDialect=vde,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(GA,t)}(oD);var mu={};Object.defineProperty(mu,"__esModule",{value:!0}),mu.getDialectFunction=mu.registerDialect=mu.getDialect=void 0;const _de=nD,Cde=eD,bde=iD,Tde=jN,Rde=oD,uD=new Map;function Ode(t){const e=uD.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}mu.getDialect=Ode;function Wd(t){uD.set(t.name,t)}mu.registerDialect=Wd,Wd(new Cde.PostgresDialect),Wd(new Tde.StandardSQLDialect),Wd(new _de.DuckDBDialect),Wd(new bde.SnowflakeDialect),Wd(new Rde.TrinoDialect);function KP(t,e){return t.params.length===e.params.length&&t.params.every((n,r)=>{const i=e.params[r];return n.isVariadic===i.isVariadic&&n.name===i.name&&n.allowedTypes.length===i.allowedTypes.length&&n.allowedTypes.every(s=>i.allowedTypes.some(o=>s.dataType===o.dataType&&s.expressionType===o.expressionType))})}function Nde(t,e){return KP(t,e)}function Dde(t,e){return t.returnType.dataType===e.returnType.dataType&&t.returnType.expressionType===e.returnType.expressionType}function Fde(t){const e={type:"function",name:t,overloads:[]};let n=!1;for(const r of uD.values()){const i=r.getGlobalFunctionDef(t);if(i){for(const s of i){let o=!1;for(const u of e.overloads)if(Nde(s,u)){if(!KP(s,u))throw new Error("params are compatible but not equal");if(!Dde(s,u))throw new Error("params match but return types differ!");u.dialect[r.name]={e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit},o=!0}o||e.overloads.push({returnType:s.returnType,params:s.params,dialect:{[r.name]:{e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit}},needsWindowOrderBy:s.needsWindowOrderBy,between:s.between,isSymmetric:s.isSymmetric})}n=!0}}return n?e:void 0}mu.getDialectFunction=Fde,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FUNCTIONS=t.getDialectFunction=t.registerDialect=t.getDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.params=t.param=t.sqlFragment=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=ve;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"sqlFragment",{enumerable:!0,get:function(){return e.sqlFragment}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"params",{enumerable:!0,get:function(){return e.params}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var n=Hc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return n.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return n.qtz}});var r=jN;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return r.StandardSQLDialect}});var i=eD;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return i.PostgresDialect}});var s=nD;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}});var o=iD;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return o.SnowflakeDialect}});var u=oD;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return u.TrinoDialect}});var a=mu;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return a.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return a.registerDialect}}),Object.defineProperty(t,"getDialectFunction",{enumerable:!0,get:function(){return a.getDialectFunction}});var l=zc;Object.defineProperty(t,"FUNCTIONS",{enumerable:!0,get:function(){return l.FUNCTIONS}})}(T3);var yu={},cf={};Object.defineProperty(cf,"__esModule",{value:!0}),cf.QueryModel=cf.Segment=void 0;const wde=T3,Lde=D2,je=ne,vr=Gt;function JP(t){return t.map(e=>encodeURIComponent(e)).join("/")}function aD(t){return`'${t}'`}function ZP(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}class Ide extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class H2{constructor(e=!0,n){this.parent=n,this.withs=[],this.udfs=[],this.pdts=[],this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,vr.indent)(`
275
+ `}sqlSelectAliasAsStruct(e){return`(SELECT AS STRUCT ${e}.*)`}sqlMaybeQuoteIdentifier(e){return'"'+e+'"'}sqlNow(){return(0,Nn.mkExpr)`CURRENT_TIMESTAMP()`}sqlTrunc(e,n,r){const i=WA(e),s=i?`, "${i}"`:"";return n.valueType==="date"?Ede(r)?(0,Nn.mkExpr)`DATE_TRUNC(${n.value},${r})`:(0,Nn.mkExpr)`TIMESTAMP(${n.value}${s})`:(0,Nn.mkExpr)`TIMESTAMP_TRUNC(${n.value},${r}${s})`}sqlExtract(e,n,r){const i=Ade[r]||r,s=n.valueType==="timestamp"&&WA(e),o=s?` AT TIME ZONE '${s}'`:"";return(0,Nn.mkExpr)`EXTRACT(${i} FROM ${n.value}${o})`}sqlAlterTime(e,n,r,i){let s=n.value,o=n.valueType;i!=="day"&&XP(i)?(o="timestamp",n.valueType!=="timestamp"&&(s=(0,Nn.mkExpr)`TIMESTAMP(${s})`)):n.valueType==="timestamp"&&(s=(0,Nn.mkExpr)`DATETIME(${s})`,o="datetime");const u=o.toUpperCase()+(e==="+"?"_ADD":"_SUB"),a=(0,Nn.mkExpr)`${u}(${s}, INTERVAL ${r} ${i})`;return o===n.valueType?a:(0,Nn.mkExpr)`${n.valueType.toUpperCase()}(${a})`}ignoreInProject(e){return e==="_PARTITIONTIME"}sqlCast(e,n){const r=`${n.srcType}::${n.dstType}`,i=WA(e);if(r==="timestamp::date"&&i)return(0,Nn.mkExpr)`DATE(${n.expr},'${i}')`;if(r==="date::timestamp"&&i)return(0,Nn.mkExpr)`TIMESTAMP(${n.expr}, '${i}')`;if(n.srcType!==n.dstType){const s=typeof n.dstType=="string"?this.malloyTypeToSQLType({type:n.dstType}):n.dstType.raw,o=n.safe?"SAFE_CAST":"CAST";return(0,Nn.mkExpr)`${o}(${n.expr} AS ${s})`}return n.expr}sqlRegexpMatch(e,n){return(0,Nn.mkExpr)`REGEXP_LIKE(${e}, ${n})`}sqlLiteralTime(e,n,r,i){if(r==="date")return`DATE('${n}')`;if(r==="timestamp"){let s=`'${n}'`;const o=i||WA(e);return o&&o!=="UTC"&&(s+=`,'${o}'`),`TIMESTAMP(${s})`}else throw new Error(`Unsupported Literal time format ${r}`)}sqlMeasureTime(e,n,r){const i={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}};let s=e.value,o=n.value;if(i[r]){const{use:u,ratio:a}=i[r];if(!XP(u))throw new Error(`Measure in '${u} not implemented`);if(e.valueType!==n.valueType)throw new Error("Can't measure difference between different types");e.valueType==="date"&&(s=(0,Nn.mkExpr)`TIMESTAMP(${s})`,o=(0,Nn.mkExpr)`TIMESTAMP(${o})`);let l=(0,Nn.mkExpr)`TIMESTAMP_DIFF(${o},${s},${u})`;return a!==1&&(l=(0,Nn.mkExpr)`FLOOR(${l}/${a.toString()}.0)`),l}throw new Error(`Measure '${r} not implemented`)}sqlSampleTable(e,n){if(n!==void 0){if((0,Nn.isSamplingEnable)(n)&&n.enable&&(n=this.defaultSampling),(0,Nn.isSamplingRows)(n))throw new Error("StandardSQL doesn't support sampling by rows only percent");if((0,Nn.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.TRINO_FUNCTIONS.get(e)}malloyTypeToSQLType(e){return e.type==="number"?e.numberType==="integer"?"BIGINT":"DOUBLE":e.type==="string"?"VARCHAR":e.type}sqlTypeToMalloyType(e){}castToString(e){return`CAST(${e} as VARCHAR)`}concat(...e){return e.join(" || ")}validateTypeName(e){return e.match(/^[A-Za-z\s(),<>0-9]*$/)!==null}}GA.TrinoDialect=vde,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(GA,t)}(oD);var mu={};Object.defineProperty(mu,"__esModule",{value:!0}),mu.getDialectFunction=mu.registerDialect=mu.getDialect=void 0;const _de=nD,Cde=eD,bde=iD,Tde=jN,Rde=oD,uD=new Map;function Ode(t){const e=uD.get(t);if(e===void 0)throw new Error(`Unknown Dialect ${t}`);return e}mu.getDialect=Ode;function Wd(t){uD.set(t.name,t)}mu.registerDialect=Wd,Wd(new Cde.PostgresDialect),Wd(new Tde.StandardSQLDialect),Wd(new _de.DuckDBDialect),Wd(new bde.SnowflakeDialect),Wd(new Rde.TrinoDialect);function KP(t,e){return t.params.length===e.params.length&&t.params.every((n,r)=>{const i=e.params[r];return n.isVariadic===i.isVariadic&&n.name===i.name&&n.allowedTypes.length===i.allowedTypes.length&&n.allowedTypes.every(s=>i.allowedTypes.some(o=>s.dataType===o.dataType&&s.expressionType===o.expressionType))})}function Nde(t,e){return KP(t,e)}function Dde(t,e){return t.returnType.dataType===e.returnType.dataType&&t.returnType.expressionType===e.returnType.expressionType}function Fde(t){const e={type:"function",name:t,overloads:[]};let n=!1;for(const r of uD.values()){const i=r.getGlobalFunctionDef(t);if(i){for(const s of i){let o=!1;for(const u of e.overloads)if(Nde(s,u)){if(!KP(s,u))throw new Error("params are compatible but not equal");if(!Dde(s,u))throw new Error("params match but return types differ!");u.dialect[r.name]={e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit},o=!0}o||e.overloads.push({returnType:s.returnType,params:s.params,dialect:{[r.name]:{e:s.e,supportsOrderBy:s.supportsOrderBy,defaultOrderByArgIndex:s.defaultOrderByArgIndex,supportsLimit:s.supportsLimit}},needsWindowOrderBy:s.needsWindowOrderBy,between:s.between,isSymmetric:s.isSymmetric})}n=!0}}return n?e:void 0}mu.getDialectFunction=Fde,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.FUNCTIONS=t.getDialectFunction=t.registerDialect=t.getDialect=t.TrinoDialect=t.SnowflakeDialect=t.DuckDBDialect=t.PostgresDialect=t.StandardSQLDialect=t.qtz=t.Dialect=t.sql=t.literal=t.params=t.param=t.sqlFragment=t.spread=t.maxScalar=t.minAggregate=t.minScalar=t.overload=t.makeParam=t.anyExprType=t.arg=void 0;var e=ve;Object.defineProperty(t,"arg",{enumerable:!0,get:function(){return e.arg}}),Object.defineProperty(t,"anyExprType",{enumerable:!0,get:function(){return e.anyExprType}}),Object.defineProperty(t,"makeParam",{enumerable:!0,get:function(){return e.makeParam}}),Object.defineProperty(t,"overload",{enumerable:!0,get:function(){return e.overload}}),Object.defineProperty(t,"minScalar",{enumerable:!0,get:function(){return e.minScalar}}),Object.defineProperty(t,"minAggregate",{enumerable:!0,get:function(){return e.minAggregate}}),Object.defineProperty(t,"maxScalar",{enumerable:!0,get:function(){return e.maxScalar}}),Object.defineProperty(t,"spread",{enumerable:!0,get:function(){return e.spread}}),Object.defineProperty(t,"sqlFragment",{enumerable:!0,get:function(){return e.sqlFragment}}),Object.defineProperty(t,"param",{enumerable:!0,get:function(){return e.param}}),Object.defineProperty(t,"params",{enumerable:!0,get:function(){return e.params}}),Object.defineProperty(t,"literal",{enumerable:!0,get:function(){return e.literal}}),Object.defineProperty(t,"sql",{enumerable:!0,get:function(){return e.sql}});var n=Hc;Object.defineProperty(t,"Dialect",{enumerable:!0,get:function(){return n.Dialect}}),Object.defineProperty(t,"qtz",{enumerable:!0,get:function(){return n.qtz}});var r=jN;Object.defineProperty(t,"StandardSQLDialect",{enumerable:!0,get:function(){return r.StandardSQLDialect}});var i=eD;Object.defineProperty(t,"PostgresDialect",{enumerable:!0,get:function(){return i.PostgresDialect}});var s=nD;Object.defineProperty(t,"DuckDBDialect",{enumerable:!0,get:function(){return s.DuckDBDialect}});var o=iD;Object.defineProperty(t,"SnowflakeDialect",{enumerable:!0,get:function(){return o.SnowflakeDialect}});var u=oD;Object.defineProperty(t,"TrinoDialect",{enumerable:!0,get:function(){return u.TrinoDialect}});var a=mu;Object.defineProperty(t,"getDialect",{enumerable:!0,get:function(){return a.getDialect}}),Object.defineProperty(t,"registerDialect",{enumerable:!0,get:function(){return a.registerDialect}}),Object.defineProperty(t,"getDialectFunction",{enumerable:!0,get:function(){return a.getDialectFunction}});var l=zc;Object.defineProperty(t,"FUNCTIONS",{enumerable:!0,get:function(){return l.FUNCTIONS}})}(T3);var yu={},cf={};Object.defineProperty(cf,"__esModule",{value:!0}),cf.QueryModel=cf.Segment=void 0;const wde=T3,Lde=D2,je=ne,vr=Gt;function JP(t){return t.map(e=>encodeURIComponent(e)).join("/")}function aD(t){return`'${t}'`}function ZP(t){return t.replace(/[^a-zA-Z0-9_]/g,"_o_")}class Ide extends Set{add_use(e){if(e!==void 0)return this.add(e)}hasAsymetricFunctions(){return this.has("sum")||this.has("avg")||this.has("count")||this.has("generic_asymmetric_aggregate")}}class H2{constructor(e=!0,n){this.parent=n,this.withs=[],this.udfs=[],this.pdts=[],this.stagePrefix="__stage",this.useCTE=e}getName(e){return`${this.stagePrefix}${e}`}root(){return this.parent===void 0?this:this.parent.root()}addStage(e){return this.useCTE?(this.withs.push(e),this.getName(this.withs.length-1)):(this.withs[0]=e,(0,vr.indent)(`
276
276
  (${e})
277
277
  `))}addUDF(e,n,r){let{sql:i,lastStageName:s}=e.combineStages(!0);if(s===void 0)throw new Error("Internal Error: no stage to combine");i+=n.sqlCreateFunctionCombineLastStage(s,r);const o=`${n.udfPrefix}${this.root().udfs.length}`;return i=n.sqlCreateFunction(o,i),this.root().udfs.push(i),o}addPDT(e,n){const r=this.combineStages(!1).sql+this.withs[this.withs.length-1],i="scratch."+e+(0,vr.generateHash)(r);return this.root().pdts.push(n.sqlCreateTableAsSelect(i,r)),i}combineStages(e){if(!this.useCTE)return{sql:this.withs[0],lastStageName:this.withs[0]};let n=this.getName(0),r="WITH ",i="";for(let s=0;s<this.withs.length-(e?0:1);s++){const o=this.withs[s];if(n=this.getName(s),o===void 0)throw new Error(`Expected sql WITH to be present for stage ${n}.`);i+=`${r}${n} AS (
278
278
  ${(0,vr.indent)(o)})
@@ -303,7 +303,7 @@ ${(0,vr.indent)(f)}) AS ${n.alias}
303
303
  ON ${a}
304
304
  `,r}}else if(s.type==="nested"){if(i.parent===void 0||n.parent===void 0)throw new Error("Internal Error, nested structure with no parent.");const u=this.parent.dialect.sqlFieldReference(i.parent.getSQLIdentifier(),s.fieldName,"struct",i.parent.fieldDef.structRelationship.type==="nested",this.parent.fieldDef.structRelationship.type==="nested"&&this.parent.fieldDef.structRelationship.isArray);r+=`${this.parent.dialect.sqlUnnestAlias(u,n.alias,n.getDialectFieldList(),n.makeUniqueKey,s.isArray,this.inNestedPipeline())}
305
305
  `}else throw s.type==="inline"?new Error("Internal Error: inline structs should never appear in join trees"):new Error(`Join type not implemented ${JSON.stringify(i.fieldDef.structRelationship)}`);for(const u of n.children)r+=this.generateSQLJoinBlock(e,u);return r}generateSQLPassthroughKeys(e){let n="";if(e.dialect.name==="standardsql"){const r=["_TABLE_SUFFIX","_PARTITIONDATE","_PARTITIONTIME"].filter(i=>e.getChildByName(i)!==void 0);r.length>0&&(n=", "+r.join(", "))}return n}generateSQLJoins(e){let n="";const[[,r]]=this.rootResult.joins,i=r.queryStruct;let s=i.structSourceSQL(e);if((0,je.isIndexSegment)(this.firstSegment)&&(s=this.parent.dialect.sqlSampleTable(s,this.firstSegment.sample),this.firstSegment.sample&&(s=e.addStage(`SELECT * from ${s} as x limit 100000 `))),i.fieldDef.structRelationship.type==="basetable"){if(r.makeUniqueKey){const u=this.generateSQLPassthroughKeys(i);s=`(SELECT ${i.dialect.sqlGenerateUUID()} as ${i.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${u} FROM ${s} as x)`}n+=`FROM ${s} as ${r.alias}
306
- `}else throw new Error("Internal Error, queries must start from a basetable");for(const u of r.children)n+=this.generateSQLJoinBlock(e,u);return n}genereateSQLOrderBy(e,n){let r="";if(this.firstSegment.type==="project"&&!e.orderBy||this.fieldDef.pipeline.length>1&&e.limit===void 0||n.getRepeatedResultType()==="inline_all_numbers"||this.isJoinedSubquery&&this.fieldDef.pipeline.length===1&&e.limit===void 0)return"";const i=e.orderBy||n.calculateDefaultOrderBy(),s=[];for(const o of i)if(typeof o.field=="string"){const u=n.getField(o.field);if(u&&u.fieldUsage.type==="result")this.parent.dialect.orderByClause==="ordinal"?s.push(`${u.fieldUsage.resultIndex} ${o.dir||"ASC"}`):this.parent.dialect.orderByClause==="output_name"&&s.push(`${o.field}${o.dir||"ASC"}`);else throw new Error(`Unknown field in ORDER BY ${o.field}`)}else if(this.parent.dialect.orderByClause==="ordinal")s.push(`${o.field} ${o.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="output_name"){const u=n.getFieldByNumber(o.field);s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(u.name)} ${o.dir||"ASC"}`)}return s.length>0&&(r=this.parent.dialect.sqlOrderBy(s)+`
306
+ `}else throw new Error("Internal Error, queries must start from a basetable");for(const u of r.children)n+=this.generateSQLJoinBlock(e,u);return n}genereateSQLOrderBy(e,n){let r="";if(this.firstSegment.type==="project"&&!e.orderBy||this.fieldDef.pipeline.length>1&&e.limit===void 0||n.getRepeatedResultType()==="inline_all_numbers"||this.isJoinedSubquery&&this.fieldDef.pipeline.length===1&&e.limit===void 0)return"";const i=e.orderBy||n.calculateDefaultOrderBy(),s=[];for(const o of i)if(typeof o.field=="string"){const u=n.getField(o.field);if(u&&u.fieldUsage.type==="result")this.parent.dialect.orderByClause==="ordinal"?s.push(`${u.fieldUsage.resultIndex} ${o.dir||"ASC"}`):this.parent.dialect.orderByClause==="output_name"&&s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(o.field)} ${o.dir||"ASC"}`);else throw new Error(`Unknown field in ORDER BY ${o.field}`)}else if(this.parent.dialect.orderByClause==="ordinal")s.push(`${o.field} ${o.dir||"ASC"}`);else if(this.parent.dialect.orderByClause==="output_name"){const u=n.getFieldByNumber(o.field);s.push(`${this.parent.dialect.sqlMaybeQuoteIdentifier(u.name)} ${o.dir||"ASC"}`)}return s.length>0&&(r=this.parent.dialect.sqlOrderBy(s)+`
307
307
  `),r}generateSimpleSQL(e){let n="";n+=`SELECT
308
308
  `;const r=[];for(const[i,s]of this.rootResult.allFields){const o=s,u=this.parent.dialect.sqlMaybeQuoteIdentifier(i);o.fieldUsage.type==="result"&&r.push(` ${o.f.generateExpression(this.rootResult)} as ${u}`)}if(n+=(0,vr.indent)(r.join(`,
309
309
  `))+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.138-dev240331204754",
3
+ "version": "0.0.138-dev240401131656",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -33,7 +33,7 @@
33
33
  "build-types": "tsc --build --declaration --emitDeclarationOnly"
34
34
  },
35
35
  "dependencies": {
36
- "@malloydata/malloy": "^0.0.138-dev240331204754",
36
+ "@malloydata/malloy": "^0.0.138-dev240401131656",
37
37
  "@types/luxon": "^2.4.0",
38
38
  "component-register": "^0.8.3",
39
39
  "lodash": "^4.17.20",