@malloydata/render 0.0.264-dev250414205448 → 0.0.264

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.
@@ -123706,10 +123706,10 @@ class is extends sk {
123706
123706
  type: "result"
123707
123707
  }), this.addDependancies(e, o), n0e(o) && this.firstSegment.type === "project")
123708
123708
  throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`);
123709
- } else o instanceof Wi && e.addField(s, o, {
123709
+ } else o instanceof Wi && (o.isAtomic() && this.addDependancies(e, o), e.addField(s, o, {
123710
123710
  resultIndex: r,
123711
123711
  type: "result"
123712
- });
123712
+ }));
123713
123713
  r++;
123714
123714
  }
123715
123715
  this.expandFilters(e);
@@ -1058,7 +1058,7 @@ ${(0,Tn.indent)(u)})
1058
1058
  ))
1059
1059
  -
1060
1060
  SUM(DISTINCT ${s})
1061
- )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Ui{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return yo(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 Sa{constructor(e,r){this.turtleDef=e,this.parent=r,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,Be.isIndexSegment)(this.firstSegment)&&!(0,Be.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ui(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ui}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ui)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ui&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ui&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(Wp(r.f))return"nested";r.f instanceof fs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Sa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Be.isJoined)(i.f.fieldDef)||(0,Be.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(Aae(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Be.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new vXe(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof fs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>Wp(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class _Xe extends Sa{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new Tn.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[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class vXe{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new xXe,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Be.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new o$({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Be.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Be.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return zp(this.queryStruct.structDef)}}class CXe{static nextStructDef(e,r){const i=new Wl(e,void 0,{model:new q4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return cs.makeQuery(s,i,new Gp(!0,void 0),!1).getResultStructDef()}}Ls.Segment=CXe;function SXe(t,e){const r=new Wl(t,void 0,{model:new q4(void 0)},{});return cs.makeQuery(e,r,new Gp(!0,void 0),!1).getResultStructDef()}Ls.getResultStructDefForView=SXe;function bXe(t,e){const i=new q4(t).compileQuery(e);return i.structs[i.structs.length-1]}Ls.getResultStructDefForQuery=bXe;class cs extends s${constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new _Xe(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Be.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new Wl({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Be.isSourceDef)(l)&&l.queryTimezone&&(0,Be.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new TXe(u,o,i,s);case"project":return new RXe(u,o,i,s);case"index":return new FXe(u,o,i,s);case"raw":return new OXe(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof fs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof fs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Be.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Tn.exprWalk)(i)){if(u.node==="function_call"){(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Be.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Be.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Be.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Be.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Be.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof cs){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Sa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof Is){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),Aae(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof fs&&e.addField(s,o,{resultIndex:r,type:"result"});r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Tn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Be.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Be.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof fs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Ui){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Be.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return j4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):Wp(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Sa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Be.isRawSegment)(o)?void 0:o.limit;let a;if((0,Be.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Sa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new Gp(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Ui&&l.fieldUsage.type==="result"){Wp(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Be.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Be.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Be.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new o$({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1061
+ )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Ui{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return yo(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 Sa{constructor(e,r){this.turtleDef=e,this.parent=r,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,Be.isIndexSegment)(this.firstSegment)&&!(0,Be.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Ui(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Ui}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Ui)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Ui&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Ui&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(Wp(r.f))return"nested";r.f instanceof fs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Sa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Ui&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Be.isJoined)(i.f.fieldDef)||(0,Be.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(Aae(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Be.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new vXe(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof fs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>Wp(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>yo(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class _Xe extends Sa{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new Tn.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[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class vXe{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new xXe,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Be.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new o$({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Be.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Be.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return zp(this.queryStruct.structDef)}}class CXe{static nextStructDef(e,r){const i=new Wl(e,void 0,{model:new q4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return cs.makeQuery(s,i,new Gp(!0,void 0),!1).getResultStructDef()}}Ls.Segment=CXe;function SXe(t,e){const r=new Wl(t,void 0,{model:new q4(void 0)},{});return cs.makeQuery(e,r,new Gp(!0,void 0),!1).getResultStructDef()}Ls.getResultStructDefForView=SXe;function bXe(t,e){const i=new q4(t).compileQuery(e);return i.structs[i.structs.length-1]}Ls.getResultStructDefForQuery=bXe;class cs extends s${constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new _Xe(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Be.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new Wl({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Be.isSourceDef)(l)&&l.queryTimezone&&(0,Be.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new TXe(u,o,i,s);case"project":return new RXe(u,o,i,s);case"index":return new FXe(u,o,i,s);case"raw":return new OXe(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof fs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof fs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Be.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Tn.exprWalk)(i)){if(u.node==="function_call"){(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Be.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Be.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Be.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Be.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Be.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Be.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof cs){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Sa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof Is){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),Aae(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof fs&&(o.isAtomic()&&this.addDependancies(e,o),e.addField(s,o,{resultIndex:r,type:"result"}));r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Tn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Be.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Be.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof fs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Ui){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Be.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return j4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):Wp(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Sa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Be.isRawSegment)(o)?void 0:o.limit;let a;if((0,Be.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Sa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new Gp(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Ui&&l.fieldUsage.type==="result"){Wp(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Be.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Be.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Be.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new o$({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1062
1062
  ON ${f}${x}
1063
1063
  `;else{let p=`SELECT ${r.alias}.*`,m="";for(const g of r.children)m+=this.generateSQLJoinBlock(e,g,i+1),p+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(g.alias,zp(g.queryStruct.structDef))} AS ${g.alias}`;return p+=`
1064
1064
  FROM ${l} AS ${r.alias}
@@ -127518,10 +127518,10 @@ class xs extends Sk {
127518
127518
  type: "result"
127519
127519
  }), this.addDependancies(e, o), rce(o) && this.firstSegment.type === "project")
127520
127520
  throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`);
127521
- } else o instanceof ts && e.addField(s, o, {
127521
+ } else o instanceof ts && (o.isAtomic() && this.addDependancies(e, o), e.addField(s, o, {
127522
127522
  resultIndex: r,
127523
127523
  type: "result"
127524
- });
127524
+ }));
127525
127525
  r++;
127526
127526
  }
127527
127527
  this.expandFilters(e);
@@ -1453,7 +1453,7 @@ ${(0,Fn.indent)(u)})
1453
1453
  ))
1454
1454
  -
1455
1455
  SUM(DISTINCT ${s})
1456
- )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Vi{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return To(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 Pa{constructor(e,r){this.turtleDef=e,this.parent=r,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,Me.isIndexSegment)(this.firstSegment)&&!(0,Me.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Vi(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Vi}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Vi)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Vi&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Vi&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(S2(r.f))return"nested";r.f instanceof gs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Pa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Me.isJoined)(i.f.fieldDef)||(0,Me.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(_le(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Me.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new mtt(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof gs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>S2(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class ptt extends Pa{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[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class mtt{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new ott,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Me.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new TB({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Me.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Me.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return v2(this.queryStruct.structDef)}}class gtt{static nextStructDef(e,r){const i=new p0(e,void 0,{model:new M4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return ms.makeQuery(s,i,new C2(!0,void 0),!1).getResultStructDef()}}js.Segment=gtt;function ytt(t,e){const r=new p0(t,void 0,{model:new M4(void 0)},{});return ms.makeQuery(e,r,new C2(!0,void 0),!1).getResultStructDef()}js.getResultStructDefForView=ytt;function Ett(t,e){const i=new M4(t).compileQuery(e);return i.structs[i.structs.length-1]}js.getResultStructDefForQuery=Ett;class ms extends bB{constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new ptt(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Me.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new p0({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Me.isSourceDef)(l)&&l.queryTimezone&&(0,Me.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new Att(u,o,i,s);case"project":return new _tt(u,o,i,s);case"index":return new Stt(u,o,i,s);case"raw":return new Ctt(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof gs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof gs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Me.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Fn.exprWalk)(i)){if(u.node==="function_call"){(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Me.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Me.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Me.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Me.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Me.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof ms){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Pa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof qs){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),_le(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof gs&&e.addField(s,o,{resultIndex:r,type:"result"});r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Fn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Me.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Me.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof gs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Vi){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Me.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return k4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):S2(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Pa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Me.isRawSegment)(o)?void 0:o.limit;let a;if((0,Me.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Pa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new C2(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Vi&&l.fieldUsage.type==="result"){S2(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Me.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Me.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Me.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new TB({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1456
+ )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Vi{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return To(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 Pa{constructor(e,r){this.turtleDef=e,this.parent=r,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,Me.isIndexSegment)(this.firstSegment)&&!(0,Me.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Vi(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Vi}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Vi)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Vi&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Vi&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(S2(r.f))return"nested";r.f instanceof gs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Pa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Me.isJoined)(i.f.fieldDef)||(0,Me.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(_le(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Me.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new mtt(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof gs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>S2(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class ptt extends Pa{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[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class mtt{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new ott,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Me.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new TB({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Me.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Me.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return v2(this.queryStruct.structDef)}}class gtt{static nextStructDef(e,r){const i=new p0(e,void 0,{model:new M4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return ms.makeQuery(s,i,new C2(!0,void 0),!1).getResultStructDef()}}js.Segment=gtt;function ytt(t,e){const r=new p0(t,void 0,{model:new M4(void 0)},{});return ms.makeQuery(e,r,new C2(!0,void 0),!1).getResultStructDef()}js.getResultStructDefForView=ytt;function Ett(t,e){const i=new M4(t).compileQuery(e);return i.structs[i.structs.length-1]}js.getResultStructDefForQuery=Ett;class ms extends bB{constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new ptt(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Me.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new p0({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Me.isSourceDef)(l)&&l.queryTimezone&&(0,Me.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new Att(u,o,i,s);case"project":return new _tt(u,o,i,s);case"index":return new Stt(u,o,i,s);case"raw":return new Ctt(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof gs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof gs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Me.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Fn.exprWalk)(i)){if(u.node==="function_call"){(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Me.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Me.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Me.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Me.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Me.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof ms){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Pa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof qs){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),_le(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof gs&&(o.isAtomic()&&this.addDependancies(e,o),e.addField(s,o,{resultIndex:r,type:"result"}));r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Fn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Me.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Me.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof gs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Vi){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Me.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return k4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):S2(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Pa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Me.isRawSegment)(o)?void 0:o.limit;let a;if((0,Me.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Pa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new C2(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Vi&&l.fieldUsage.type==="result"){S2(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Me.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Me.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Me.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new TB({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1457
1457
  ON ${f}${x}
1458
1458
  `;else{let p=`SELECT ${r.alias}.*`,m="";for(const g of r.children)m+=this.generateSQLJoinBlock(e,g,i+1),p+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(g.alias,v2(g.queryStruct.structDef))} AS ${g.alias}`;return p+=`
1459
1459
  FROM ${l} AS ${r.alias}
@@ -127518,10 +127518,10 @@ class xs extends Sk {
127518
127518
  type: "result"
127519
127519
  }), this.addDependancies(e, o), rce(o) && this.firstSegment.type === "project")
127520
127520
  throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`);
127521
- } else o instanceof ts && e.addField(s, o, {
127521
+ } else o instanceof ts && (o.isAtomic() && this.addDependancies(e, o), e.addField(s, o, {
127522
127522
  resultIndex: r,
127523
127523
  type: "result"
127524
- });
127524
+ }));
127525
127525
  r++;
127526
127526
  }
127527
127527
  this.expandFilters(e);
@@ -1453,7 +1453,7 @@ ${(0,Fn.indent)(u)})
1453
1453
  ))
1454
1454
  -
1455
1455
  SUM(DISTINCT ${s})
1456
- )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Vi{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return To(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 Pa{constructor(e,r){this.turtleDef=e,this.parent=r,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,Me.isIndexSegment)(this.firstSegment)&&!(0,Me.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Vi(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Vi}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Vi)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Vi&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Vi&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(S2(r.f))return"nested";r.f instanceof gs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Pa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Me.isJoined)(i.f.fieldDef)||(0,Me.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(Ale(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Me.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new mtt(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof gs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>S2(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class ptt extends Pa{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[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class mtt{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new ott,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Me.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new bB({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Me.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Me.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return v2(this.queryStruct.structDef)}}class gtt{static nextStructDef(e,r){const i=new p0(e,void 0,{model:new k4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return ms.makeQuery(s,i,new C2(!0,void 0),!1).getResultStructDef()}}js.Segment=gtt;function ytt(t,e){const r=new p0(t,void 0,{model:new k4(void 0)},{});return ms.makeQuery(e,r,new C2(!0,void 0),!1).getResultStructDef()}js.getResultStructDefForView=ytt;function Ett(t,e){const i=new k4(t).compileQuery(e);return i.structs[i.structs.length-1]}js.getResultStructDefForQuery=Ett;class ms extends SB{constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new ptt(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Me.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new p0({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Me.isSourceDef)(l)&&l.queryTimezone&&(0,Me.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new Att(u,o,i,s);case"project":return new _tt(u,o,i,s);case"index":return new Stt(u,o,i,s);case"raw":return new Ctt(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof gs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof gs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Me.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Fn.exprWalk)(i)){if(u.node==="function_call"){(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Me.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Me.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Me.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Me.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Me.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof ms){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Pa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof qs){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),Ale(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof gs&&e.addField(s,o,{resultIndex:r,type:"result"});r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Fn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Me.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Me.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof gs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Vi){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Me.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return B4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):S2(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Pa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Me.isRawSegment)(o)?void 0:o.limit;let a;if((0,Me.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Pa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new C2(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Vi&&l.fieldUsage.type==="result"){S2(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Me.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Me.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Me.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new bB({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1456
+ )`}/(${o}*1.0))`;return a=`CAST(${a} AS ${t.defaultNumberType})`,a}class Vi{constructor(e,r,i){this.f=e,this.fieldUsage=r,this.parent=i,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return To(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 Pa{constructor(e,r){this.turtleDef=e,this.parent=r,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,Me.isIndexSegment)(this.firstSegment)&&!(0,Me.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,r,i){const s=this.allFields.get(e);if(s){if(s.type==="query")throw new Error(`Redefinition of field ${r.fieldDef.name} as struct`);if(s.fieldUsage.type==="result"){if(i.type!=="result")return;throw new Error(`Ambiguous output field name '${r.fieldDef.name}'.`)}}this.add(e,new Vi(r,i,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,r){this.allFields.set(e,r)}hasField(e){const r=this.allFields.get(e);return r!==void 0&&r instanceof Vi}getField(e){const r=this.allFields.get(e);if(r===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(r instanceof Vi)return r;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"&&i.fieldUsage.resultIndex===e)return{name:r,fif:i};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,r){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[u,a]of this.ungroupedSets){const l=e++;a.groupSet=l,this.root().computeOnlyGroups.push(l)}this.groupSet=e++,this.depth=r;let i=r,s=!1,o=[this.groupSet];for(const[u,a]of this.allFields)if(a.type==="query"){const l=a;if(s=!0,l.firstSegment.type==="reduce"){const c=l.computeGroups(e,r+1);o=o.concat(c.children),e=c.nextGroupSetNumber,c.maxDepth>i&&(i=c.maxDepth)}}return this.childGroups=o,{nextGroupSetNumber:e,maxDepth:i,children:o,isComplex:s}}fields(e=void 0){const r=[];for(const i of this.allFields.values())i instanceof Vi&&(e===void 0||e(i))&&r.push(i);return r}fieldNames(e){const r=[];for(const[i,s]of this.allFields)s instanceof Vi&&(e===void 0||e(s))&&r.push(i);return r}getRepeatedResultType(){let e="inline_all_numbers";for(const r of this.fields())if(r.fieldUsage.type==="result"){if(S2(r.f))return"nested";r.f instanceof gs&&(e="inline")}return e}structs(){const e=[];for(const r of this.allFields.values())r instanceof Pa&&e.push(r);return e}selectStructs(e,r){r(this)&&e.push(this);for(const i of this.structs())i.selectStructs(e,r);return e}calculateDefaultOrderBy(){let e;for(const[r,i]of this.allFields)if(i instanceof Vi&&i.fieldUsage.type==="result"){if(i.f.fieldDef.type==="turtle"||(0,Me.isJoined)(i.f.fieldDef)||(0,Me.expressionIsAnalytic)(i.f.fieldDef.expressionType))continue;if(e||(e=i.fieldUsage.resultIndex),["date","timestamp"].indexOf(i.f.fieldDef.type)>-1)return[{dir:"desc",field:i.fieldUsage.resultIndex}];if(Ale(i.f))return[{dir:"desc",field:i.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,r,i,s){var o;const u=e.getIdentifier();if(s.indexOf(u)!==-1)return;let a;if(a=this.root().joins.get(u)){a.uniqueKeyPossibleUses.add_use(i);return}let l;const c=(o=e.parent)===null||o===void 0?void 0:o.getJoinableParent();c&&(this.addStructToJoin(c,r,void 0,s),l=this.root().joins.get(c.getIdentifier()));const f=e.structDef;(0,Me.isJoinedSource)(f)&&e.parent&&f.onExpression&&s.indexOf(u)===-1&&r.addDependantExpr(this,e.parent,f.onExpression,[...s,u]),(a=this.root().joins.get(u))||(a=new mtt(e,u,l),this.root().joins.set(u,a)),a.uniqueKeyPossibleUses.add_use(i)}findJoins(e){for(const r of this.fields())r.f instanceof gs||this.addStructToJoin(r.f.getJoinableParent(),e,r.f.uniqueKeyPossibleUse(),[]);for(const r of this.structs())r.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let r=[],i=this,s=[],o=[];if(e===void 0||e.type==="all"){const a=(e==null?void 0:e.fields)||[];s=this.fields(l=>S2(l.f)&&l.fieldUsage.type==="result"&&a.indexOf(l.f.getIdentifier())===-1).map(l=>l.f.getIdentifier())}else s=e.fields;let u=!0;for(;i!==void 0;)(u||(e==null?void 0:e.type)==="exclude")&&(o=o.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result").map(a=>a.f.getIdentifier()))),r=r.concat(i.fields(a=>To(a.f)&&a.fieldUsage.type==="result"&&s.indexOf(a.f.getIdentifier())===-1)),i=i.parent,u=!1;for(const a of(e==null?void 0:e.fields)||[])if(o.indexOf(a)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${a}" or name not in scope.`);return r}assignFieldsToGroups(){for(const[e,r]of this.ungroupedSets)for(const i of this.getUngroupPartitions(r))i.additionalGroupSets.push(r.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class ptt extends Pa{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[r,i]of this.joins)if(i.parentRelationship()==="many_to_many"||i.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=r;else if(i.parentRelationship()==="one_to_many"){const o=i.queryStruct;o.parent&&o.parent.getIdentifier()===e?e=r:e="0never"}for(const[r,i]of this.joins)i.leafiest=r===e;for(const[r,i]of this.joins)if(i.leafiest&&i.parent!==void 0&&i.uniqueKeyPossibleUses.has("count")||!i.leafiest&&i.uniqueKeyPossibleUses.hasAsymetricFunctions()){let s=i;for(;s;)s.queryStruct.primaryKey()||(s.makeUniqueKey=!0),s.queryStruct.structDef.type==="array"?s=s.parent:s=void 0}}}class mtt{constructor(e,r,i){this.queryStruct=e,this.alias=r,this.parent=i,this.uniqueKeyPossibleUses=new ott,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],i&&i.children.push(this);const s=this.queryStruct.structDef;(0,Me.isSourceDef)(s)&&s.filterList&&(this.joinFilterConditions=s.filterList.map(o=>new bB({type:"boolean",name:"ignoreme",e:o.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,Me.isJoined)(e))switch(e.join){case"one":return"many_to_one";case"cross":return"many_to_many";case"many":return"one_to_many"}throw new Error(`Internal error unknown relationship type to parent for ${this.queryStruct.structDef.name}`)}forceAllSymmetricCalculations(){if(this.queryStruct.parent===void 0)return!1;const e=this.queryStruct.structDef;return(0,Me.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return v2(this.queryStruct.structDef)}}class gtt{static nextStructDef(e,r){const i=new p0(e,void 0,{model:new k4(void 0)},{}),s={type:"turtle",name:"ignoreme",pipeline:[r]};return ms.makeQuery(s,i,new C2(!0,void 0),!1).getResultStructDef()}}js.Segment=gtt;function ytt(t,e){const r=new p0(t,void 0,{model:new k4(void 0)},{});return ms.makeQuery(e,r,new C2(!0,void 0),!1).getResultStructDef()}js.getResultStructDefForView=ytt;function Ett(t,e){const i=new k4(t).compileQuery(e);return i.structs[i.structs.length-1]}js.getResultStructDefForQuery=Ett;class ms extends SB{constructor(e,r,i,s){super(e,r),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new ptt(e),this.stageWriter=i,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=s}static makeQuery(e,r,i=void 0,s){let o=r,u=r.applyStructFiltersToTurtleDef(e);const a=u.pipeline[0],l=r.structDef;switch(i!==void 0&&(0,Me.isQuerySegment)(a)&&a.extendSource!==void 0&&(o=new p0({...l,fields:[...l.fields,...a.extendSource]},r.sourceArguments,o.parent?{struct:o}:{model:o.model},o.prepareResultOptions),u={...u,pipeline:[{...a,extendSource:void 0},...u.pipeline.slice(1)]}),(0,Me.isSourceDef)(l)&&l.queryTimezone&&(0,Me.isQuerySegment)(a)&&a.queryTimezone===void 0&&(a.queryTimezone=l.queryTimezone),a.type){case"reduce":return new Att(u,o,i,s);case"project":return new _tt(u,o,i,s);case"index":return new Stt(u,o,i,s);case"raw":return new Ctt(u,o,i,s);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const r=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:r.getIdentifier(),field:r}}addDependantPath(e,r,i,s,o){if(i.length===0)return;const u=r.getFieldByName(i),a=u instanceof gs?u.queryStruct.getJoinableParent():u.parent.getJoinableParent();e.root().addStructToJoin(a,this,s,o)}findRecordAliases(e,r){for(const i of r){const s=e.getFieldByName([i]);if(s instanceof gs){const o=s.queryStruct;o.structDef.type==="record"&&(0,Me.hasExpression)(o.structDef)&&o.parent&&o.informOfAliasValue(this.exprToSQL(this.rootResult,o.parent,o.structDef.e)),e=o}}}addDependantExpr(e,r,i,s){var o;for(const u of(0,Fn.exprWalk)(i)){if(u.node==="function_call"){(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const a=(o=u.overload.isSymmetric)!==null&&o!==void 0?o:!1,c=(0,Me.expressionIsAggregate)(u.overload.returnType.expressionType)&&!a,f=c?"generic_asymmetric_aggregate":void 0;u.structPath?this.addDependantPath(e,r,u.structPath,f,s):c&&e.addStructToJoin(r,this,f,s),(0,Me.expressionIsAnalytic)(u.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((u.node==="all"||u.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,u.fields&&u.fields.length>0)){const a=u.fields.sort().join("|")+u.node;e.ungroupedSets.get(a)===void 0&&e.ungroupedSets.set(a,{type:u.node,fields:u.fields,groupSet:-1})}if(u.node==="field"){this.findRecordAliases(r,u.path);const a=r.getDimensionOrMeasureByName(u.path);(0,Me.hasExpression)(a.fieldDef)?this.addDependantExpr(e,a.parent,a.fieldDef.e,s):e.root().addStructToJoin(a.parent.getJoinableParent(),this,void 0,s)}else u.node==="aggregate"&&(0,Me.isAsymmetricExpr)(u)&&(u.structPath?(this.findRecordAliases(r,u.structPath),this.addDependantPath(e,r,u.structPath,u.function,s)):e.addStructToJoin(r,this,u.function,s))}}addDependancies(e,r){(0,Me.hasExpression)(r.fieldDef)&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}getSegmentFields(e){const r=e.firstSegment;return r.type==="index"?r.indexFields:(0,Me.isQuerySegment)(r)?r.queryFields:[]}expandFields(e){let r=1;for(const i of this.getSegmentFields(e)){const{as:s,field:o}=this.expandField(i);if(o instanceof ms){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${o.fieldDef.name}'`);const u=new Pa(o.fieldDef,e);this.expandFields(u),e.add(s,u)}else if(o instanceof qs){if(e.addField(s,o,{resultIndex:r,type:"result"}),this.addDependancies(e,o),Ale(o)&&this.firstSegment.type==="project")throw new Error(`Aggregate Fields cannot be used in select - '${o.fieldDef.name}'`)}else o instanceof gs&&(o.isAtomic()&&this.addDependancies(e,o),e.addField(s,o,{resultIndex:r,type:"result"}));r++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const r of e.firstSegment.filterList||[]){const i=this.parent;this.addDependantExpr(e,i,r.e,[])}for(const r of e.root().joins.values()||[])for(const i of r.joinFilterConditions||[])i.fieldDef.type==="boolean"&&i.fieldDef.e&&this.addDependantExpr(e,i.parent,i.fieldDef.e,[])}}generateSQLFilters(e,r){const i=new Fn.AndChain,s=e.firstSegment.filterList;if(s===void 0)return i;for(const o of s||[]){const u=this.parent;if(r==="having"&&(0,Me.expressionIsCalculation)(o.expressionType)||r==="where"&&(0,Me.expressionIsScalar)(o.expressionType)){const a=this.exprToSQL(e,u,o.e,void 0);i.add(a)}}return i}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.addAlwaysJoins(this.rootResult),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}addAlwaysJoins(e){var r;const i=this.fieldDef.pipeline[0];if(i.type!=="raw"){const s=(r=i.alwaysJoins)!==null&&r!==void 0?r:[];for(const o of s){const u=this.parent.getChildByName(o);u instanceof gs&&e.addStructToJoin(u.queryStruct,this,void 0,[])}}}getResultMetadata(e){if(e instanceof Vi){if(e.fieldUsage.type==="result"){const r=e.f.fieldDef;let i;const s=e.f.parent.getFullOutputName()+(r.name||r.as||"undefined"),o=(0,Me.hasExpression)(r)?r.code:void 0,u=[s],a=e.f.referenceId,l={sourceField:s,sourceExpression:o,sourceClasses:u,referenceId:a};return B4(e.f)?(i=e.f.getFilterList(),{...l,filterList:i,fieldKind:"measure"}):S2(e.f)?{...l,filterList:i,fieldKind:"dimension"}:void 0}return}else if(e instanceof Pa){const r=e.turtleDef.name||e.turtleDef.as,i=r?[r]:[],s=e.firstSegment.filterList,o=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],u=(0,Me.isRawSegment)(o)?void 0:o.limit;let a;if((0,Me.isQuerySegment)(o)&&(a=o.orderBy),r)return{sourceField:r,filterList:s,sourceClasses:i,fieldKind:"struct",limit:u,orderBy:a}}}getResultStructDef(e=this.rootResult,r=!0){const i=[];let s;this.prepare(void 0);let o=0;for(const[a,l]of e.allFields){const c=this.getResultMetadata(l);if(l instanceof Pa){const{structDef:f,repeatedResultType:x}=this.generateTurtlePipelineSQL(l,new C2(!0,void 0),"<nosource>");if(x==="nested"){const h={...f,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:a,resultMetadata:c};i.push(h)}else{const h={...f,type:"record",join:"one",name:a,resultMetadata:c};i.push(h)}}else if(l instanceof Vi&&l.fieldUsage.type==="result"){S2(l.f)&&(o===0&&r?s=a:s=void 0,o++);let f=l.f.fieldDef;(0,Me.hasExpression)(f)&&(f={...f},delete f.e,delete f.code,delete f.expressionType);const x=f.location,h=f.annotation;switch(f.type){case"boolean":case"json":case"string":i.push({name:a,type:f.type,resultMetadata:c,location:x,annotation:h});break;case"date":case"timestamp":{const p=f.timeframe,m={type:f.type};p&&(m.timeframe=p),i.push({name:a,...m,resultMetadata:c,location:x,annotation:h});break}case"number":i.push({name:a,numberType:f.numberType,type:"number",resultMetadata:c,location:x,annotation:h});break;case"sql native":case"record":case"array":{i.push({...f,resultMetadata:c});break}default:throw new Error(`unknown Field Type in query ${JSON.stringify(f)}`)}}}const u={type:"query_result",name:this.resultStage||"result",fields:i,dialect:this.parent.dialect.name,primaryKey:s,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(u.modelAnnotation=this.parent.structDef.modelAnnotation),u}generateSQLJoinBlock(e,r,i){var s;let o="";const u=r.queryStruct,a=u.structDef;if((s=u.eventStream)===null||s===void 0||s.emit("join-used",{name:(0,Me.getIdentifier)(a)}),u.maybeEmitParameterizedSourceUsage(),(0,Me.isJoinedSource)(a)){let l=u.structSourceSQL(e);const c=(a.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&c==="FULL")throw new Error("FULL JOIN not supported");if(r.makeUniqueKey){const p=this.generateSQLPassthroughKeys(u);l=`(SELECT ${u.dialect.sqlGenerateUUID()} as ${u.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${p} FROM ${l} as x)`}let f="";if(u.parent===void 0)throw new Error("Expected joined struct to have a parent.");a.onExpression?f=new bB({type:"boolean",name:"ignoreme",e:a.onExpression},u.parent).generateExpression(this.rootResult):f="1=1";let x="",h;if(r.joinFilterConditions&&(h=r.joinFilterConditions.map(p=>p.generateExpression(this.rootResult))),r.children.length===0||h===void 0||!this.parent.dialect.supportsComplexFilteredSources)h!==void 0&&h.length>=1&&(x=` AND (${h.join(" AND ")})`),o+=` ${c} JOIN ${l} AS ${r.alias}
1457
1457
  ON ${f}${x}
1458
1458
  `;else{let p=`SELECT ${r.alias}.*`,m="";for(const g of r.children)m+=this.generateSQLJoinBlock(e,g,i+1),p+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(g.alias,v2(g.queryStruct.structDef))} AS ${g.alias}`;return p+=`
1459
1459
  FROM ${l} AS ${r.alias}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@malloydata/render",
3
- "version": "0.0.264-dev250414205448",
3
+ "version": "0.0.264",
4
4
  "license": "MIT",
5
5
  "main": "dist/module/index.umd.js",
6
6
  "types": "dist/index.d.ts",
@@ -41,9 +41,9 @@
41
41
  "generate-flow": "ts-node ../../scripts/gen-flow.ts"
42
42
  },
43
43
  "dependencies": {
44
- "@malloydata/malloy": "^0.0.264-dev250414205448",
45
- "@malloydata/malloy-interfaces": "^0.0.264-dev250414205448",
46
- "@malloydata/malloy-tag": "^0.0.264-dev250414205448",
44
+ "@malloydata/malloy": "^0.0.264",
45
+ "@malloydata/malloy-interfaces": "^0.0.264",
46
+ "@malloydata/malloy-tag": "^0.0.264",
47
47
  "@tanstack/solid-virtual": "^3.10.4",
48
48
  "component-register": "^0.8.6",
49
49
  "lodash": "^4.17.20",
@@ -56,7 +56,7 @@
56
56
  "vega-lite": "^5.2.0"
57
57
  },
58
58
  "devDependencies": {
59
- "@malloydata/db-duckdb": "^0.0.264-dev250414205448",
59
+ "@malloydata/db-duckdb": "^0.0.264",
60
60
  "@storybook/addon-essentials": "^8.5.8",
61
61
  "@storybook/addon-interactions": "^8.5.8",
62
62
  "@storybook/addon-links": "^8.5.8",