@malloydata/render 0.0.197-dev241009205116 → 0.0.197
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module/index.mjs
CHANGED
|
@@ -24998,17 +24998,10 @@ class ws extends HE {
|
|
|
24998
24998
|
break;
|
|
24999
24999
|
case "date":
|
|
25000
25000
|
case "timestamp": {
|
|
25001
|
-
const x = a.f.fieldDef.timeframe;
|
|
25002
|
-
x
|
|
25001
|
+
const x = a.f.fieldDef.timeframe, h = { type: a.f.fieldDef.type };
|
|
25002
|
+
x && (h.timeframe = x), r.push({
|
|
25003
25003
|
name: u,
|
|
25004
|
-
|
|
25005
|
-
timeframe: x,
|
|
25006
|
-
resultMetadata: l,
|
|
25007
|
-
location: c,
|
|
25008
|
-
annotation: f
|
|
25009
|
-
}) : r.push({
|
|
25010
|
-
name: u,
|
|
25011
|
-
type: "timestamp",
|
|
25004
|
+
...h,
|
|
25012
25005
|
resultMetadata: l,
|
|
25013
25006
|
location: c,
|
|
25014
25007
|
annotation: f
|
package/dist/module/index.umd.js
CHANGED
|
@@ -967,7 +967,7 @@ ${(0,an.indent)(o)})
|
|
|
967
967
|
))
|
|
968
968
|
-
|
|
969
969
|
SUM(DISTINCT ${i})
|
|
970
|
-
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class Yr{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return dr(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 Xo{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,ke.isIndexSegment)(this.firstSegment)&&!(0,ke.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new Yr(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof Yr}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof Yr)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof Yr&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof Yr&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof Yr&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(dr(n.f))return"nested";n.f instanceof Yn&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof Xo&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof Yr&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||(0,ke.isJoined)(r.f.fieldDef)||(0,ke.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(KM(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.structDef;(0,ke.isJoinedSource)(c)&&e.parent&&c.onExpression&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new hpe(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>dr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>dr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>dr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class dpe extends Xo{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new an.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.structDef.type==="array"?i=i.parent:i=void 0}}}class hpe{constructor(e,n,r){this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new upe,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this);const i=this.queryStruct.structDef;(0,ke.isSourceDef)(i)&&i.filterList&&(this.joinFilterConditions=i.filterList.map(s=>new k6({type:"boolean",name:"ignoreme",e:s.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,ke.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,ke.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return Gx(this.queryStruct.structDef)}}class tj extends LE{}class ppe{static nextStructDef(e,n){const r=new Yn(e,void 0,{model:new nj(void 0)},{}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Ts.makeQuery(i,r,new FE(!0,void 0),!1).getResultStructDef()}}Y0.Segment=ppe;class Ts extends LE{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new dpe(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.structDef;switch(r!==void 0&&(0,ke.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Yn({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model},s.prepareResultOptions),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),(0,ke.isSourceDef)(a)&&a.queryTimezone&&(0,ke.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new gpe(o,s,r,i);case"project":return new mpe(o,s,r,i);case"index":return new Ape(o,s,r,i);case"raw":return new Epe(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof LE)u=o.parent;else if(o instanceof Yn)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,an.exprWalk)(r)){if(o.node==="function_call"){(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,ke.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,ke.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,ke.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,ke.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,ke.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof tj||s instanceof Ts){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new Xo(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Vr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),KM(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new an.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,ke.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,ke.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof Yr){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=(0,ke.hasExpression)(n)?n.code:void 0,o=[i],u=e.f.referenceId,a={sourceField:i,sourceExpression:s,sourceClasses:o,referenceId:u};return IE(e.f)?(r=e.f.getFilterList(),{...a,filterList:r,fieldKind:"measure"}):dr(e.f)?{...a,filterList:r,fieldKind:"dimension"}:void 0}return}else if(e instanceof Xo){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,ke.isRawSegment)(s)?void 0:s.limit;let u;if((0,ke.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof Xo){const{structDef:c}=this.generateTurtlePipelineSQL(a,new FE(!0,void 0),"<nosource>");if(a.getRepeatedResultType()==="nested"){const f={...c,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:u,resultMetadata:l};r.push(f)}else{const f={...c,type:"record",join:"one",name:u,resultMetadata:l};r.push(f)}}else if(a instanceof Yr&&a.fieldUsage.type==="result"){dr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"date":case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={type:"query_result",name:this.resultStage||"result",fields:r,dialect:this.parent.structDef.dialect,primaryKey:i,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(o.modelAnnotation=this.parent.structDef.modelAnnotation),o}generateSQLJoinBlock(e,n){var r;let i="";const s=n.queryStruct,o=s.structDef;if((r=s.eventStream)===null||r===void 0||r.emit("join-used",{name:(0,ke.getIdentifier)(o)}),s.maybeEmitParameterizedSourceUsage(),(0,ke.isJoinedSource)(o)){let u=s.structSourceSQL(e);const a=(o.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&a==="FULL")throw new Error("FULL JOIN not supported");if(n.makeUniqueKey){const x=this.generateSQLPassthroughKeys(s);u=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${x} FROM ${u} as x)`}let l="";if(s.parent===void 0)throw new Error("Expected joined struct to have a parent.");o.onExpression?l=new k6({type:"boolean",name:"ignoreme",e:o.onExpression},s.parent).generateExpression(this.rootResult):l="1=1";let c="",f;if(n.joinFilterConditions&&(f=n.joinFilterConditions.map(x=>x.generateExpression(this.rootResult))),n.children.length===0||f===void 0||!this.parent.dialect.supportsComplexFilteredSources)f!==void 0&&f.length>=1&&(c=` AND (${f.join(" AND ")})`),i+=` ${a} JOIN ${u} AS ${n.alias}
|
|
970
|
+
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class Yr{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return dr(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 Xo{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,ke.isIndexSegment)(this.firstSegment)&&!(0,ke.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new Yr(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof Yr}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof Yr)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof Yr&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof Yr&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof Yr&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(dr(n.f))return"nested";n.f instanceof Yn&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof Xo&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof Yr&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||(0,ke.isJoined)(r.f.fieldDef)||(0,ke.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(KM(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.structDef;(0,ke.isJoinedSource)(c)&&e.parent&&c.onExpression&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new hpe(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>dr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>dr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>dr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class dpe extends Xo{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new an.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.structDef.type==="array"?i=i.parent:i=void 0}}}class hpe{constructor(e,n,r){this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new upe,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this);const i=this.queryStruct.structDef;(0,ke.isSourceDef)(i)&&i.filterList&&(this.joinFilterConditions=i.filterList.map(s=>new k6({type:"boolean",name:"ignoreme",e:s.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,ke.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,ke.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return Gx(this.queryStruct.structDef)}}class tj extends LE{}class ppe{static nextStructDef(e,n){const r=new Yn(e,void 0,{model:new nj(void 0)},{}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return Ts.makeQuery(i,r,new FE(!0,void 0),!1).getResultStructDef()}}Y0.Segment=ppe;class Ts extends LE{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new dpe(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.structDef;switch(r!==void 0&&(0,ke.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Yn({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model},s.prepareResultOptions),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),(0,ke.isSourceDef)(a)&&a.queryTimezone&&(0,ke.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new gpe(o,s,r,i);case"project":return new mpe(o,s,r,i);case"index":return new Ape(o,s,r,i);case"raw":return new Epe(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof LE)u=o.parent;else if(o instanceof Yn)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,an.exprWalk)(r)){if(o.node==="function_call"){(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,ke.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,ke.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,ke.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,ke.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,ke.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof tj||s instanceof Ts){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new Xo(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Vr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),KM(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new an.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,ke.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,ke.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof Yr){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=(0,ke.hasExpression)(n)?n.code:void 0,o=[i],u=e.f.referenceId,a={sourceField:i,sourceExpression:s,sourceClasses:o,referenceId:u};return IE(e.f)?(r=e.f.getFilterList(),{...a,filterList:r,fieldKind:"measure"}):dr(e.f)?{...a,filterList:r,fieldKind:"dimension"}:void 0}return}else if(e instanceof Xo){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,ke.isRawSegment)(s)?void 0:s.limit;let u;if((0,ke.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof Xo){const{structDef:c}=this.generateTurtlePipelineSQL(a,new FE(!0,void 0),"<nosource>");if(a.getRepeatedResultType()==="nested"){const f={...c,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:u,resultMetadata:l};r.push(f)}else{const f={...c,type:"record",join:"one",name:u,resultMetadata:l};r.push(f)}}else if(a instanceof Yr&&a.fieldUsage.type==="result"){dr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"date":case"timestamp":{const x=a.f.fieldDef.timeframe,h={type:a.f.fieldDef.type};x&&(h.timeframe=x),r.push({name:u,...h,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={type:"query_result",name:this.resultStage||"result",fields:r,dialect:this.parent.structDef.dialect,primaryKey:i,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(o.modelAnnotation=this.parent.structDef.modelAnnotation),o}generateSQLJoinBlock(e,n){var r;let i="";const s=n.queryStruct,o=s.structDef;if((r=s.eventStream)===null||r===void 0||r.emit("join-used",{name:(0,ke.getIdentifier)(o)}),s.maybeEmitParameterizedSourceUsage(),(0,ke.isJoinedSource)(o)){let u=s.structSourceSQL(e);const a=(o.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&a==="FULL")throw new Error("FULL JOIN not supported");if(n.makeUniqueKey){const x=this.generateSQLPassthroughKeys(s);u=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${x} FROM ${u} as x)`}let l="";if(s.parent===void 0)throw new Error("Expected joined struct to have a parent.");o.onExpression?l=new k6({type:"boolean",name:"ignoreme",e:o.onExpression},s.parent).generateExpression(this.rootResult):l="1=1";let c="",f;if(n.joinFilterConditions&&(f=n.joinFilterConditions.map(x=>x.generateExpression(this.rootResult))),n.children.length===0||f===void 0||!this.parent.dialect.supportsComplexFilteredSources)f!==void 0&&f.length>=1&&(c=` AND (${f.join(" AND ")})`),i+=` ${a} JOIN ${u} AS ${n.alias}
|
|
971
971
|
ON ${l}${c}
|
|
972
972
|
`;else{let x=`SELECT ${n.alias}.*`,h="";for(const p of n.children)h+=this.generateSQLJoinBlock(e,p),x+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(p.alias,Gx(p.queryStruct.structDef))} AS ${p.alias}`;return x+=`
|
|
973
973
|
FROM ${u} AS ${n.alias}
|
|
@@ -25921,17 +25921,10 @@ class Ms extends FA {
|
|
|
25921
25921
|
break;
|
|
25922
25922
|
case "date":
|
|
25923
25923
|
case "timestamp": {
|
|
25924
|
-
const x = a.f.fieldDef.timeframe;
|
|
25925
|
-
x
|
|
25924
|
+
const x = a.f.fieldDef.timeframe, h = { type: a.f.fieldDef.type };
|
|
25925
|
+
x && (h.timeframe = x), r.push({
|
|
25926
25926
|
name: u,
|
|
25927
|
-
|
|
25928
|
-
timeframe: x,
|
|
25929
|
-
resultMetadata: l,
|
|
25930
|
-
location: c,
|
|
25931
|
-
annotation: f
|
|
25932
|
-
}) : r.push({
|
|
25933
|
-
name: u,
|
|
25934
|
-
type: "timestamp",
|
|
25927
|
+
...h,
|
|
25935
25928
|
resultMetadata: l,
|
|
25936
25929
|
location: c,
|
|
25937
25930
|
annotation: f
|
|
@@ -967,7 +967,7 @@ ${(0,cn.indent)(o)})
|
|
|
967
967
|
))
|
|
968
968
|
-
|
|
969
969
|
SUM(DISTINCT ${i})
|
|
970
|
-
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class ei{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return mr(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 au{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,ke.isIndexSegment)(this.firstSegment)&&!(0,ke.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new ei(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof ei}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof ei)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof ei&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof ei&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(mr(n.f))return"nested";n.f instanceof Zn&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof au&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||(0,ke.isJoined)(r.f.fieldDef)||(0,ke.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(jj(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.structDef;(0,ke.isJoinedSource)(c)&&e.parent&&c.onExpression&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>mr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class K1e extends au{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new cn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.structDef.type==="array"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new G1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this);const i=this.queryStruct.structDef;(0,ke.isSourceDef)(i)&&i.filterList&&(this.joinFilterConditions=i.filterList.map(s=>new _R({type:"boolean",name:"ignoreme",e:s.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,ke.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,ke.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return md(this.queryStruct.structDef)}}class zj extends _A{}class ege{static nextStructDef(e,n){const r=new Zn(e,void 0,{model:new Hj(void 0)},{}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return ws.makeQuery(i,r,new SA(!0,void 0),!1).getResultStructDef()}}xc.Segment=ege;class ws extends _A{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new K1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.structDef;switch(r!==void 0&&(0,ke.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Zn({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model},s.prepareResultOptions),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),(0,ke.isSourceDef)(a)&&a.queryTimezone&&(0,ke.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tge(o,s,r,i);case"project":return new nge(o,s,r,i);case"index":return new sge(o,s,r,i);case"raw":return new ige(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof _A)u=o.parent;else if(o instanceof Zn)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,cn.exprWalk)(r)){if(o.node==="function_call"){(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,ke.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,ke.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,ke.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,ke.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,ke.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof zj||s instanceof ws){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new au(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Zr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),jj(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new cn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,ke.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,ke.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof ei){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=(0,ke.hasExpression)(n)?n.code:void 0,o=[i],u=e.f.referenceId,a={sourceField:i,sourceExpression:s,sourceClasses:o,referenceId:u};return CA(e.f)?(r=e.f.getFilterList(),{...a,filterList:r,fieldKind:"measure"}):mr(e.f)?{...a,filterList:r,fieldKind:"dimension"}:void 0}return}else if(e instanceof au){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,ke.isRawSegment)(s)?void 0:s.limit;let u;if((0,ke.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof au){const{structDef:c}=this.generateTurtlePipelineSQL(a,new SA(!0,void 0),"<nosource>");if(a.getRepeatedResultType()==="nested"){const f={...c,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:u,resultMetadata:l};r.push(f)}else{const f={...c,type:"record",join:"one",name:u,resultMetadata:l};r.push(f)}}else if(a instanceof ei&&a.fieldUsage.type==="result"){mr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"date":case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={type:"query_result",name:this.resultStage||"result",fields:r,dialect:this.parent.structDef.dialect,primaryKey:i,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(o.modelAnnotation=this.parent.structDef.modelAnnotation),o}generateSQLJoinBlock(e,n){var r;let i="";const s=n.queryStruct,o=s.structDef;if((r=s.eventStream)===null||r===void 0||r.emit("join-used",{name:(0,ke.getIdentifier)(o)}),s.maybeEmitParameterizedSourceUsage(),(0,ke.isJoinedSource)(o)){let u=s.structSourceSQL(e);const a=(o.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&a==="FULL")throw new Error("FULL JOIN not supported");if(n.makeUniqueKey){const x=this.generateSQLPassthroughKeys(s);u=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${x} FROM ${u} as x)`}let l="";if(s.parent===void 0)throw new Error("Expected joined struct to have a parent.");o.onExpression?l=new _R({type:"boolean",name:"ignoreme",e:o.onExpression},s.parent).generateExpression(this.rootResult):l="1=1";let c="",f;if(n.joinFilterConditions&&(f=n.joinFilterConditions.map(x=>x.generateExpression(this.rootResult))),n.children.length===0||f===void 0||!this.parent.dialect.supportsComplexFilteredSources)f!==void 0&&f.length>=1&&(c=` AND (${f.join(" AND ")})`),i+=` ${a} JOIN ${u} AS ${n.alias}
|
|
970
|
+
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class ei{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return mr(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 au{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,ke.isIndexSegment)(this.firstSegment)&&!(0,ke.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new ei(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof ei}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof ei)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof ei&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof ei&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(mr(n.f))return"nested";n.f instanceof Zn&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof au&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||(0,ke.isJoined)(r.f.fieldDef)||(0,ke.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(jj(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.structDef;(0,ke.isJoinedSource)(c)&&e.parent&&c.onExpression&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>mr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class K1e extends au{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new cn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.structDef.type==="array"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new G1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this);const i=this.queryStruct.structDef;(0,ke.isSourceDef)(i)&&i.filterList&&(this.joinFilterConditions=i.filterList.map(s=>new _R({type:"boolean",name:"ignoreme",e:s.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,ke.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,ke.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return md(this.queryStruct.structDef)}}class zj extends _A{}class ege{static nextStructDef(e,n){const r=new Zn(e,void 0,{model:new Hj(void 0)},{}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return ws.makeQuery(i,r,new SA(!0,void 0),!1).getResultStructDef()}}xc.Segment=ege;class ws extends _A{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new K1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.structDef;switch(r!==void 0&&(0,ke.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Zn({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model},s.prepareResultOptions),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),(0,ke.isSourceDef)(a)&&a.queryTimezone&&(0,ke.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tge(o,s,r,i);case"project":return new nge(o,s,r,i);case"index":return new sge(o,s,r,i);case"raw":return new ige(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof _A)u=o.parent;else if(o instanceof Zn)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,cn.exprWalk)(r)){if(o.node==="function_call"){(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,ke.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,ke.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,ke.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,ke.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,ke.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof zj||s instanceof ws){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new au(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Zr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),jj(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new cn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,ke.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,ke.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof ei){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=(0,ke.hasExpression)(n)?n.code:void 0,o=[i],u=e.f.referenceId,a={sourceField:i,sourceExpression:s,sourceClasses:o,referenceId:u};return CA(e.f)?(r=e.f.getFilterList(),{...a,filterList:r,fieldKind:"measure"}):mr(e.f)?{...a,filterList:r,fieldKind:"dimension"}:void 0}return}else if(e instanceof au){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,ke.isRawSegment)(s)?void 0:s.limit;let u;if((0,ke.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof au){const{structDef:c}=this.generateTurtlePipelineSQL(a,new SA(!0,void 0),"<nosource>");if(a.getRepeatedResultType()==="nested"){const f={...c,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:u,resultMetadata:l};r.push(f)}else{const f={...c,type:"record",join:"one",name:u,resultMetadata:l};r.push(f)}}else if(a instanceof ei&&a.fieldUsage.type==="result"){mr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"date":case"timestamp":{const x=a.f.fieldDef.timeframe,h={type:a.f.fieldDef.type};x&&(h.timeframe=x),r.push({name:u,...h,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={type:"query_result",name:this.resultStage||"result",fields:r,dialect:this.parent.structDef.dialect,primaryKey:i,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(o.modelAnnotation=this.parent.structDef.modelAnnotation),o}generateSQLJoinBlock(e,n){var r;let i="";const s=n.queryStruct,o=s.structDef;if((r=s.eventStream)===null||r===void 0||r.emit("join-used",{name:(0,ke.getIdentifier)(o)}),s.maybeEmitParameterizedSourceUsage(),(0,ke.isJoinedSource)(o)){let u=s.structSourceSQL(e);const a=(o.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&a==="FULL")throw new Error("FULL JOIN not supported");if(n.makeUniqueKey){const x=this.generateSQLPassthroughKeys(s);u=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${x} FROM ${u} as x)`}let l="";if(s.parent===void 0)throw new Error("Expected joined struct to have a parent.");o.onExpression?l=new _R({type:"boolean",name:"ignoreme",e:o.onExpression},s.parent).generateExpression(this.rootResult):l="1=1";let c="",f;if(n.joinFilterConditions&&(f=n.joinFilterConditions.map(x=>x.generateExpression(this.rootResult))),n.children.length===0||f===void 0||!this.parent.dialect.supportsComplexFilteredSources)f!==void 0&&f.length>=1&&(c=` AND (${f.join(" AND ")})`),i+=` ${a} JOIN ${u} AS ${n.alias}
|
|
971
971
|
ON ${l}${c}
|
|
972
972
|
`;else{let x=`SELECT ${n.alias}.*`,h="";for(const p of n.children)h+=this.generateSQLJoinBlock(e,p),x+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(p.alias,md(p.queryStruct.structDef))} AS ${p.alias}`;return x+=`
|
|
973
973
|
FROM ${u} AS ${n.alias}
|
|
@@ -25921,17 +25921,10 @@ class Ms extends FA {
|
|
|
25921
25921
|
break;
|
|
25922
25922
|
case "date":
|
|
25923
25923
|
case "timestamp": {
|
|
25924
|
-
const x = a.f.fieldDef.timeframe;
|
|
25925
|
-
x
|
|
25924
|
+
const x = a.f.fieldDef.timeframe, h = { type: a.f.fieldDef.type };
|
|
25925
|
+
x && (h.timeframe = x), r.push({
|
|
25926
25926
|
name: u,
|
|
25927
|
-
|
|
25928
|
-
timeframe: x,
|
|
25929
|
-
resultMetadata: l,
|
|
25930
|
-
location: c,
|
|
25931
|
-
annotation: f
|
|
25932
|
-
}) : r.push({
|
|
25933
|
-
name: u,
|
|
25934
|
-
type: "timestamp",
|
|
25927
|
+
...h,
|
|
25935
25928
|
resultMetadata: l,
|
|
25936
25929
|
location: c,
|
|
25937
25930
|
annotation: f
|
|
@@ -967,7 +967,7 @@ ${(0,cn.indent)(o)})
|
|
|
967
967
|
))
|
|
968
968
|
-
|
|
969
969
|
SUM(DISTINCT ${i})
|
|
970
|
-
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class ei{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return mr(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 au{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,ke.isIndexSegment)(this.firstSegment)&&!(0,ke.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new ei(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof ei}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof ei)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof ei&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof ei&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(mr(n.f))return"nested";n.f instanceof Zn&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof au&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||(0,ke.isJoined)(r.f.fieldDef)||(0,ke.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(Pj(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.structDef;(0,ke.isJoinedSource)(c)&&e.parent&&c.onExpression&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>mr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class K1e extends au{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new cn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.structDef.type==="array"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new G1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this);const i=this.queryStruct.structDef;(0,ke.isSourceDef)(i)&&i.filterList&&(this.joinFilterConditions=i.filterList.map(s=>new SR({type:"boolean",name:"ignoreme",e:s.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,ke.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,ke.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return md(this.queryStruct.structDef)}}class qj extends SA{}class ege{static nextStructDef(e,n){const r=new Zn(e,void 0,{model:new zj(void 0)},{}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return ws.makeQuery(i,r,new vA(!0,void 0),!1).getResultStructDef()}}xc.Segment=ege;class ws extends SA{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new K1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.structDef;switch(r!==void 0&&(0,ke.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Zn({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model},s.prepareResultOptions),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),(0,ke.isSourceDef)(a)&&a.queryTimezone&&(0,ke.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tge(o,s,r,i);case"project":return new nge(o,s,r,i);case"index":return new sge(o,s,r,i);case"raw":return new ige(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof SA)u=o.parent;else if(o instanceof Zn)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,cn.exprWalk)(r)){if(o.node==="function_call"){(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,ke.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,ke.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,ke.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,ke.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,ke.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof qj||s instanceof ws){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new au(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Zr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),Pj(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new cn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,ke.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,ke.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof ei){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=(0,ke.hasExpression)(n)?n.code:void 0,o=[i],u=e.f.referenceId,a={sourceField:i,sourceExpression:s,sourceClasses:o,referenceId:u};return _A(e.f)?(r=e.f.getFilterList(),{...a,filterList:r,fieldKind:"measure"}):mr(e.f)?{...a,filterList:r,fieldKind:"dimension"}:void 0}return}else if(e instanceof au){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,ke.isRawSegment)(s)?void 0:s.limit;let u;if((0,ke.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof au){const{structDef:c}=this.generateTurtlePipelineSQL(a,new vA(!0,void 0),"<nosource>");if(a.getRepeatedResultType()==="nested"){const f={...c,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:u,resultMetadata:l};r.push(f)}else{const f={...c,type:"record",join:"one",name:u,resultMetadata:l};r.push(f)}}else if(a instanceof ei&&a.fieldUsage.type==="result"){mr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"date":case"timestamp":{const x=a.f.fieldDef.timeframe;x?r.push({name:u,type:"timestamp",timeframe:x,resultMetadata:l,location:c,annotation:f}):r.push({name:u,type:"timestamp",resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={type:"query_result",name:this.resultStage||"result",fields:r,dialect:this.parent.structDef.dialect,primaryKey:i,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(o.modelAnnotation=this.parent.structDef.modelAnnotation),o}generateSQLJoinBlock(e,n){var r;let i="";const s=n.queryStruct,o=s.structDef;if((r=s.eventStream)===null||r===void 0||r.emit("join-used",{name:(0,ke.getIdentifier)(o)}),s.maybeEmitParameterizedSourceUsage(),(0,ke.isJoinedSource)(o)){let u=s.structSourceSQL(e);const a=(o.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&a==="FULL")throw new Error("FULL JOIN not supported");if(n.makeUniqueKey){const x=this.generateSQLPassthroughKeys(s);u=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${x} FROM ${u} as x)`}let l="";if(s.parent===void 0)throw new Error("Expected joined struct to have a parent.");o.onExpression?l=new SR({type:"boolean",name:"ignoreme",e:o.onExpression},s.parent).generateExpression(this.rootResult):l="1=1";let c="",f;if(n.joinFilterConditions&&(f=n.joinFilterConditions.map(x=>x.generateExpression(this.rootResult))),n.children.length===0||f===void 0||!this.parent.dialect.supportsComplexFilteredSources)f!==void 0&&f.length>=1&&(c=` AND (${f.join(" AND ")})`),i+=` ${a} JOIN ${u} AS ${n.alias}
|
|
970
|
+
)`}/(${s}*1.0))`;return u=`CAST(${u} AS ${t.defaultNumberType})`,u}class ei{constructor(e,n,r){this.f=e,this.fieldUsage=n,this.parent=r,this.type="field",this.additionalGroupSets=[]}root(){return this.parent.root()}getSQL(){let e=this.f.generateExpression(this.parent);return mr(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 au{constructor(e,n){this.turtleDef=e,this.parent=n,this.type="query",this.allFields=new Map,this.groupSet=0,this.depth=0,this.childGroups=[],this.hasHaving=!1,this.ungroupedSets=new Map,this.resultUsesUngrouped=!1,this.firstSegment=e.pipeline[0]}getQueryInfo(){if(!(0,ke.isIndexSegment)(this.firstSegment)&&!(0,ke.isRawSegment)(this.firstSegment)){const{queryTimezone:e}=this.firstSegment;if(e)return{queryTimezone:e}}return{}}addField(e,n,r){const i=this.allFields.get(e);if(i){if(i.type==="query")throw new Error(`Redefinition of field ${n.fieldDef.name} as struct`);if(i.fieldUsage.type==="result"){if(r.type!=="result")return;throw new Error(`Ambiguous output field name '${n.fieldDef.name}'.`)}}this.add(e,new ei(n,r,this))}parentGroupSet(){return this.parent?this.parent.groupSet:0}add(e,n){this.allFields.set(e,n)}hasField(e){const n=this.allFields.get(e);return n!==void 0&&n instanceof ei}getField(e){const n=this.allFields.get(e);if(n===void 0)throw new Error(`Internal Error, field Not defined ${e}`);if(n instanceof ei)return n;throw new Error(`can't use a query here ${e}`)}getFieldByNumber(e){for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"&&r.fieldUsage.resultIndex===e)return{name:n,fif:r};throw new Error(`Invalid Order By index '${e}`)}computeGroups(e,n){e===0&&this.resultUsesUngrouped&&this.root().computeOnlyGroups.push(e++);for(const[o,u]of this.ungroupedSets){const a=e++;u.groupSet=a,this.root().computeOnlyGroups.push(a)}this.groupSet=e++,this.depth=n;let r=n,i=!1,s=[this.groupSet];for(const[o,u]of this.allFields)if(u.type==="query"){const a=u;if(i=!0,a.firstSegment.type==="reduce"){const l=a.computeGroups(e,n+1);s=s.concat(l.children),e=l.nextGroupSetNumber,l.maxDepth>r&&(r=l.maxDepth)}}return this.childGroups=s,{nextGroupSetNumber:e,maxDepth:r,children:s,isComplex:i}}fields(e=void 0){const n=[];for(const r of this.allFields.values())r instanceof ei&&(e===void 0||e(r))&&n.push(r);return n}fieldNames(e){const n=[];for(const[r,i]of this.allFields)i instanceof ei&&(e===void 0||e(i))&&n.push(r);return n}getRepeatedResultType(){let e="inline_all_numbers";for(const n of this.fields())if(n.fieldUsage.type==="result"){if(mr(n.f))return"nested";n.f instanceof Zn&&(e="inline")}return e}structs(){const e=[];for(const n of this.allFields.values())n instanceof au&&e.push(n);return e}selectStructs(e,n){n(this)&&e.push(this);for(const r of this.structs())r.selectStructs(e,n);return e}calculateDefaultOrderBy(){let e;for(const[n,r]of this.allFields)if(r instanceof ei&&r.fieldUsage.type==="result"){if(r.f.fieldDef.type==="turtle"||(0,ke.isJoined)(r.f.fieldDef)||(0,ke.expressionIsAnalytic)(r.f.fieldDef.expressionType))continue;if(e||(e=r.fieldUsage.resultIndex),["date","timestamp"].indexOf(r.f.fieldDef.type)>-1)return[{dir:"desc",field:r.fieldUsage.resultIndex}];if(Pj(r.f))return[{dir:"desc",field:r.fieldUsage.resultIndex}]}return e?[{dir:"asc",field:e}]:[]}addStructToJoin(e,n,r,i){var s;const o=e.getIdentifier();if(i.indexOf(o)!==-1)return;let u;if(u=this.root().joins.get(o)){u.uniqueKeyPossibleUses.add_use(r);return}let a;const l=(s=e.parent)===null||s===void 0?void 0:s.getJoinableParent();l&&(this.addStructToJoin(l,n,void 0,i),a=this.root().joins.get(l.getIdentifier()));const c=e.structDef;(0,ke.isJoinedSource)(c)&&e.parent&&c.onExpression&&i.indexOf(o)===-1&&n.addDependantExpr(this,e.parent,c.onExpression,[...i,o]),(u=this.root().joins.get(o))||(u=new Z1e(e,o,a),this.root().joins.set(o,u)),u.uniqueKeyPossibleUses.add_use(r)}findJoins(e){for(const n of this.fields())this.addStructToJoin(n.f.getJoinableParent(),e,n.f.uniqueKeyPossibleUse(),[]);for(const n of this.structs())n.findJoins(e)}root(){if(this.parent)return this.parent.root();throw new Error("Internal Error, Null parent FieldInstanceResult")}getUngroupPartitions(e){let n=[],r=this,i=[],s=[];if(e===void 0||e.type==="all"){const u=(e==null?void 0:e.fields)||[];i=this.fields(a=>mr(a.f)&&a.fieldUsage.type==="result"&&u.indexOf(a.f.getIdentifier())===-1).map(a=>a.f.getIdentifier())}else i=e.fields;let o=!0;for(;r!==void 0;)(o||(e==null?void 0:e.type)==="exclude")&&(s=s.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result").map(u=>u.f.getIdentifier()))),n=n.concat(r.fields(u=>mr(u.f)&&u.fieldUsage.type==="result"&&i.indexOf(u.f.getIdentifier())===-1)),r=r.parent,o=!1;for(const u of(e==null?void 0:e.fields)||[])if(s.indexOf(u)===-1)throw new Error(`${e==null?void 0:e.type}(): unknown field name "${u}" or name not in scope.`);return n}assignFieldsToGroups(){for(const[e,n]of this.ungroupedSets)for(const r of this.getUngroupPartitions(n))r.additionalGroupSets.push(n.groupSet);for(const e of this.structs())e.assignFieldsToGroups()}}class K1e extends au{constructor(e){super(e,void 0),this.joins=new Map,this.havings=new cn.AndChain,this.isComplexQuery=!1,this.queryUsesPartitioning=!1,this.computeOnlyGroups=[],this.elimatedComputeGroups=!1}root(){return this}eliminateComputeGroupsSQL(){return this.elimatedComputeGroups||this.computeOnlyGroups.length===0?"":(this.elimatedComputeGroups=!0,`group_set NOT IN (${this.computeOnlyGroups.join(",")})`)}calculateSymmetricAggregates(){let e;for(const[n,r]of this.joins)if(r.parentRelationship()==="many_to_many"||r.forceAllSymmetricCalculations())e="0never";else if(e===void 0)e=n;else if(r.parentRelationship()==="one_to_many"){const s=r.queryStruct;s.parent&&s.parent.getIdentifier()===e?e=n:e="0never"}for(const[n,r]of this.joins)r.leafiest=n===e;for(const[n,r]of this.joins)if(r.leafiest&&r.parent!==void 0&&r.uniqueKeyPossibleUses.has("count")||!r.leafiest&&r.uniqueKeyPossibleUses.hasAsymetricFunctions()){let i=r;for(;i;)i.queryStruct.primaryKey()||(i.makeUniqueKey=!0),i.queryStruct.structDef.type==="array"?i=i.parent:i=void 0}}}class Z1e{constructor(e,n,r){this.queryStruct=e,this.alias=n,this.parent=r,this.uniqueKeyPossibleUses=new G1e,this.makeUniqueKey=!1,this.leafiest=!1,this.children=[],r&&r.children.push(this);const i=this.queryStruct.structDef;(0,ke.isSourceDef)(i)&&i.filterList&&(this.joinFilterConditions=i.filterList.map(s=>new SR({type:"boolean",name:"ignoreme",e:s.e},this.queryStruct)))}parentRelationship(){if(this.queryStruct.parent===void 0)return"root";const e=this.queryStruct.structDef;if((0,ke.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,ke.isJoined)(e)?e.matrixOperation==="right"||e.matrixOperation==="full":!1}getDialectFieldList(){return md(this.queryStruct.structDef)}}class qj extends SA{}class ege{static nextStructDef(e,n){const r=new Zn(e,void 0,{model:new zj(void 0)},{}),i={type:"turtle",name:"ignoreme",pipeline:[n]};return ws.makeQuery(i,r,new vA(!0,void 0),!1).getResultStructDef()}}xc.Segment=ege;class ws extends SA{constructor(e,n,r,i){super(e,n),this.prepared=!1,this.maxDepth=0,this.maxGroupSet=0,this.fieldDef=e,this.rootResult=new K1e(e),this.stageWriter=r,this.firstSegment=e.pipeline[0],this.isJoinedSubquery=i}static makeQuery(e,n,r=void 0,i){let s=n,o=n.applyStructFiltersToTurtleDef(e);const u=o.pipeline[0],a=n.structDef;switch(r!==void 0&&(0,ke.isQuerySegment)(u)&&u.extendSource!==void 0&&(s=new Zn({...a,fields:[...a.fields,...u.extendSource]},n.sourceArguments,s.parent?{struct:s}:{model:s.model},s.prepareResultOptions),o={...o,pipeline:[{...u,extendSource:void 0},...o.pipeline.slice(1)]}),(0,ke.isSourceDef)(a)&&a.queryTimezone&&(0,ke.isQuerySegment)(u)&&u.queryTimezone===void 0&&(u.queryTimezone=a.queryTimezone),u.type){case"reduce":return new tge(o,s,r,i);case"project":return new nge(o,s,r,i);case"index":return new sge(o,s,r,i);case"raw":return new ige(o,s,r,i);case"partial":throw new Error("Attempt to make query out of partial stage")}}inNestedPipeline(){return this.parent.structDef.type==="nest_source"}expandField(e){const n=e.type==="fieldref"?this.parent.getQueryFieldReference(e.path,e.annotation):this.parent.makeQueryField(e);return{as:n.getIdentifier(),field:n}}addDependantPath(e,n,r,i,s){const o=n.getFieldByName(r);let u;if(o instanceof SA)u=o.parent;else if(o instanceof Zn)u=o;else throw new Error("Internal Error: Unknown object type");e.root().addStructToJoin(u.getJoinableParent(),this,i,s)}addDependantExpr(e,n,r,i){var s;for(const o of(0,cn.exprWalk)(r)){if(o.node==="function_call"){(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&this.parent.dialect.cantPartitionWindowFunctionsOnExpressions&&(e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0);const u=(s=o.overload.isSymmetric)!==null&&s!==void 0?s:!1,l=(0,ke.expressionIsAggregate)(o.overload.returnType.expressionType)&&!u,c=l?"generic_asymmetric_aggregate":void 0;o.structPath?this.addDependantPath(e,n,o.structPath,c,i):l&&e.addStructToJoin(n,this,c,i),(0,ke.expressionIsAnalytic)(o.overload.returnType.expressionType)&&(e.root().queryUsesPartitioning=!0)}else if((o.node==="all"||o.node==="exclude")&&(e.resultUsesUngrouped=!0,e.root().isComplexQuery=!0,e.root().queryUsesPartitioning=!0,o.fields&&o.fields.length>0)){const u=o.fields.sort().join("|")+o.node;e.ungroupedSets.get(u)===void 0&&e.ungroupedSets.set(u,{type:o.node,fields:o.fields,groupSet:-1})}if(o.node==="field"){const u=n.getDimensionOrMeasureByName(o.path);(0,ke.hasExpression)(u.fieldDef)?this.addDependantExpr(e,u.parent,u.fieldDef.e,i):e.root().addStructToJoin(u.parent.getJoinableParent(),this,void 0,i)}else o.node==="aggregate"&&(0,ke.isAsymmetricExpr)(o)&&(o.structPath?this.addDependantPath(e,n,o.structPath,o.function,i):e.addStructToJoin(n,this,o.function,i))}}addDependancies(e,n){(0,ke.hasExpression)(n.fieldDef)&&this.addDependantExpr(e,n.parent,n.fieldDef.e,[])}getSegmentFields(e){const n=e.firstSegment;return n.type==="index"?n.indexFields:(0,ke.isQuerySegment)(n)?n.queryFields:[]}expandFields(e){let n=1;for(const r of this.getSegmentFields(e)){const{as:i,field:s}=this.expandField(r);if(s instanceof qj||s instanceof ws){if(this.firstSegment.type==="project")throw new Error(`Nested views cannot be used in select - '${s.fieldDef.name}'`);const o=new au(s.fieldDef,e);this.expandFields(o),e.add(i,o)}else if(s instanceof Zr&&(e.addField(i,s,{resultIndex:n,type:"result"}),this.addDependancies(e,s),Pj(s)&&this.firstSegment.type==="project"))throw new Error(`Aggregate Fields cannot be used in select - '${s.fieldDef.name}'`);n++}this.expandFilters(e)}expandFilters(e){if(e.firstSegment.filterList!==void 0){for(const n of e.firstSegment.filterList||[]){const r=this.parent;this.addDependantExpr(e,r,n.e,[])}for(const n of e.root().joins.values()||[])for(const r of n.joinFilterConditions||[])r.fieldDef.type==="boolean"&&r.fieldDef.e&&this.addDependantExpr(e,r.parent,r.fieldDef.e,[])}}generateSQLFilters(e,n){const r=new cn.AndChain,i=e.firstSegment.filterList;if(i===void 0)return r;for(const s of i||[]){const o=this.parent;if(n==="having"&&(0,ke.expressionIsCalculation)(s.expressionType)||n==="where"&&(0,ke.expressionIsScalar)(s.expressionType)){const u=this.exprToSQL(e,o,s.e,void 0);r.add(u)}}return r}prepare(e){this.prepared||(this.expandFields(this.rootResult),this.rootResult.addStructToJoin(this.parent,this,void 0,[]),this.rootResult.findJoins(this),this.rootResult.calculateSymmetricAggregates(),this.prepared=!0)}getResultMetadata(e){if(e instanceof ei){if(e.fieldUsage.type==="result"){const n=e.f.fieldDef;let r;const i=e.f.parent.getFullOutputName()+(n.name||n.as||"undefined"),s=(0,ke.hasExpression)(n)?n.code:void 0,o=[i],u=e.f.referenceId,a={sourceField:i,sourceExpression:s,sourceClasses:o,referenceId:u};return _A(e.f)?(r=e.f.getFilterList(),{...a,filterList:r,fieldKind:"measure"}):mr(e.f)?{...a,filterList:r,fieldKind:"dimension"}:void 0}return}else if(e instanceof au){const n=e.turtleDef.name||e.turtleDef.as,r=n?[n]:[],i=e.firstSegment.filterList,s=e.turtleDef.pipeline[e.turtleDef.pipeline.length-1],o=(0,ke.isRawSegment)(s)?void 0:s.limit;let u;if((0,ke.isQuerySegment)(s)&&(u=s.orderBy),n)return{sourceField:n,filterList:i,sourceClasses:r,fieldKind:"struct",limit:o,orderBy:u}}}getResultStructDef(e=this.rootResult,n=!0){const r=[];let i;this.prepare(void 0);let s=0;for(const[u,a]of e.allFields){const l=this.getResultMetadata(a);if(a instanceof au){const{structDef:c}=this.generateTurtlePipelineSQL(a,new vA(!0,void 0),"<nosource>");if(a.getRepeatedResultType()==="nested"){const f={...c,type:"array",elementTypeDef:{type:"record_element"},join:"many",name:u,resultMetadata:l};r.push(f)}else{const f={...c,type:"record",join:"one",name:u,resultMetadata:l};r.push(f)}}else if(a instanceof ei&&a.fieldUsage.type==="result"){mr(a.f)&&(s===0&&n?i=u:i=void 0,s++);const c=a.f.fieldDef.location,f=a.f.fieldDef.annotation;switch(a.f.fieldDef.type){case"boolean":case"json":case"string":r.push({name:u,type:a.f.fieldDef.type,resultMetadata:l,location:c,annotation:f});break;case"date":case"timestamp":{const x=a.f.fieldDef.timeframe,h={type:a.f.fieldDef.type};x&&(h.timeframe=x),r.push({name:u,...h,resultMetadata:l,location:c,annotation:f});break}case"number":r.push({name:u,numberType:a.f.fieldDef.numberType,type:"number",resultMetadata:l,location:c,annotation:f});break;case"sql native":r.push({...a.f.fieldDef,resultMetadata:l,location:c});break;default:throw new Error(`unknown Field Type in query ${JSON.stringify(a.f.fieldDef)}`)}}}const o={type:"query_result",name:this.resultStage||"result",fields:r,dialect:this.parent.structDef.dialect,primaryKey:i,connection:this.parent.connectionName,resultMetadata:this.getResultMetadata(this.rootResult),queryTimezone:e.getQueryInfo().queryTimezone};return this.parent.structDef.modelAnnotation&&(o.modelAnnotation=this.parent.structDef.modelAnnotation),o}generateSQLJoinBlock(e,n){var r;let i="";const s=n.queryStruct,o=s.structDef;if((r=s.eventStream)===null||r===void 0||r.emit("join-used",{name:(0,ke.getIdentifier)(o)}),s.maybeEmitParameterizedSourceUsage(),(0,ke.isJoinedSource)(o)){let u=s.structSourceSQL(e);const a=(o.matrixOperation||"left").toUpperCase();if(!this.parent.dialect.supportsFullJoin&&a==="FULL")throw new Error("FULL JOIN not supported");if(n.makeUniqueKey){const x=this.generateSQLPassthroughKeys(s);u=`(SELECT ${s.dialect.sqlGenerateUUID()} as ${s.dialect.sqlMaybeQuoteIdentifier("__distinct_key")}, x.* ${x} FROM ${u} as x)`}let l="";if(s.parent===void 0)throw new Error("Expected joined struct to have a parent.");o.onExpression?l=new SR({type:"boolean",name:"ignoreme",e:o.onExpression},s.parent).generateExpression(this.rootResult):l="1=1";let c="",f;if(n.joinFilterConditions&&(f=n.joinFilterConditions.map(x=>x.generateExpression(this.rootResult))),n.children.length===0||f===void 0||!this.parent.dialect.supportsComplexFilteredSources)f!==void 0&&f.length>=1&&(c=` AND (${f.join(" AND ")})`),i+=` ${a} JOIN ${u} AS ${n.alias}
|
|
971
971
|
ON ${l}${c}
|
|
972
972
|
`;else{let x=`SELECT ${n.alias}.*`,h="";for(const p of n.children)h+=this.generateSQLJoinBlock(e,p),x+=`, ${this.parent.dialect.sqlSelectAliasAsStruct(p.alias,md(p.queryStruct.structDef))} AS ${p.alias}`;return x+=`
|
|
973
973
|
FROM ${u} AS ${n.alias}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@malloydata/render",
|
|
3
|
-
"version": "0.0.197
|
|
3
|
+
"version": "0.0.197",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"main": "dist/module/index.umd.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"build-types": "tsc --build --declaration --emitDeclarationOnly"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@malloydata/malloy": "^0.0.197
|
|
35
|
+
"@malloydata/malloy": "^0.0.197",
|
|
36
36
|
"@tanstack/solid-virtual": "^3.10.4",
|
|
37
37
|
"component-register": "^0.8.6",
|
|
38
38
|
"lodash": "^4.17.20",
|