drizzle-cube 0.4.2 → 0.4.3
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/adapters/express/index.cjs +1 -1
- package/dist/adapters/express/index.js +1 -1
- package/dist/adapters/fastify/index.cjs +1 -1
- package/dist/adapters/fastify/index.js +1 -1
- package/dist/adapters/hono/index.cjs +1 -1
- package/dist/adapters/hono/index.js +1 -1
- package/dist/adapters/mcp-transport-BqLo4hKi.cjs +257 -0
- package/dist/adapters/{mcp-transport-Dmolep14.js → mcp-transport-YHDZWKOi.js} +1727 -1624
- package/dist/adapters/nextjs/index.cjs +1 -1
- package/dist/adapters/nextjs/index.js +1 -1
- package/dist/client/chunks/{DashboardEditModal-D6TDeTBa.js → DashboardEditModal-BGDhxKg1.js} +1322 -1318
- package/dist/client/chunks/{DashboardEditModal-D6TDeTBa.js.map → DashboardEditModal-BGDhxKg1.js.map} +1 -1
- package/dist/client/chunks/{analysis-builder-CIuNLos1.js → analysis-builder-BlCXpnDL.js} +3 -3
- package/dist/client/chunks/{analysis-builder-CIuNLos1.js.map → analysis-builder-BlCXpnDL.js.map} +1 -1
- package/dist/client/chunks/{analysis-builder-shared-gky0SKQH.js → analysis-builder-shared-BOYNJQY8.js} +2 -2
- package/dist/client/chunks/{analysis-builder-shared-gky0SKQH.js.map → analysis-builder-shared-BOYNJQY8.js.map} +1 -1
- package/dist/client/components.js +1 -1
- package/dist/client/index.js +2 -2
- package/dist/client-bundle-stats.html +1 -1
- package/dist/server/index.cjs +83 -83
- package/dist/server/index.d.ts +26 -2
- package/dist/server/index.js +3034 -2931
- package/package.json +1 -1
- package/dist/adapters/mcp-transport-h__yKJm9.cjs +0 -257
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"use strict";const Y=require("./utils.cjs"),x=Symbol.for("drizzle:entityKind");function I(d,e){if(!d||typeof d!="object")return!1;if(d instanceof e)return!0;if(!Object.prototype.hasOwnProperty.call(e,x))throw new Error(`Class "${e.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let t=Object.getPrototypeOf(d).constructor;if(t)for(;t;){if(x in t&&t[x]===e[x])return!0;t=Object.getPrototypeOf(t)}return!1}class se{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity}static[x]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}const Ce=Symbol.for("drizzle:Name"),Be=Symbol.for("drizzle:isPgEnum");function wt(d){return!!d&&typeof d=="function"&&Be in d&&d[Be]===!0}class it{static[x]="Subquery";constructor(e,t,n,i=!1,s=[]){this._={brand:"Subquery",sql:e,selectedFields:t,alias:n,isWith:i,usedTables:s}}}const $t={startActiveSpan(d,e){return e()}},ie=Symbol.for("drizzle:ViewBaseConfig"),we=Symbol.for("drizzle:Schema"),ke=Symbol.for("drizzle:Columns"),xe=Symbol.for("drizzle:ExtraConfigColumns"),$e=Symbol.for("drizzle:OriginalName"),Te=Symbol.for("drizzle:BaseName"),ce=Symbol.for("drizzle:IsAlias"),Ue=Symbol.for("drizzle:ExtraConfigBuilder"),Tt=Symbol.for("drizzle:IsDrizzleTable");class Q{static[x]="Table";static Symbol={Name:Ce,Schema:we,OriginalName:$e,Columns:ke,ExtraConfigColumns:xe,BaseName:Te,IsAlias:ce,ExtraConfigBuilder:Ue};[Ce];[$e];[we];[ke];[xe];[Te];[ce]=!1;[Tt]=!0;[Ue]=void 0;constructor(e,t,n){this[Ce]=this[$e]=e,this[we]=t,this[Te]=n}}function st(d){return d!=null&&typeof d.getSQL=="function"}function Et(d){const e={sql:"",params:[]};for(const t of d)e.sql+=t.sql,e.params.push(...t.params),t.typings?.length&&(e.typings||(e.typings=[]),e.typings.push(...t.typings));return e}class P{static[x]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new O([this])}}class O{constructor(e){this.queryChunks=e;for(const t of e)if(I(t,Q)){const n=t[Q.Symbol.Schema];this.usedTables.push(n===void 0?t[Q.Symbol.Name]:n+"."+t[Q.Symbol.Name])}}static[x]="SQL";decoder=rt;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return $t.startActiveSpan("drizzle.buildSQL",t=>{const n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,t){const n=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{casing:i,escapeName:s,escapeParam:r,prepareTyping:a,inlineParams:u,paramStartIndex:c}=n;return Et(e.map(l=>{if(I(l,P))return{sql:l.value.join(""),params:[]};if(I(l,ve))return{sql:s(l.value),params:[]};if(l===void 0)return{sql:"",params:[]};if(Array.isArray(l)){const m=[new P("(")];for(const[p,f]of l.entries())m.push(f),p<l.length-1&&m.push(new P(", "));return m.push(new P(")")),this.buildQueryFromSourceParams(m,n)}if(I(l,O))return this.buildQueryFromSourceParams(l.queryChunks,{...n,inlineParams:u||l.shouldInlineParams});if(I(l,Q)){const m=l[Q.Symbol.Schema],p=l[Q.Symbol.Name];return{sql:m===void 0||l[ce]?s(p):s(m)+"."+s(p),params:[]}}if(I(l,se)){const m=i.getColumnCasing(l);if(t.invokeSource==="indexes")return{sql:s(m),params:[]};const p=l.table[Q.Symbol.Schema];return{sql:l.table[ce]||p===void 0?s(l.table[Q.Symbol.Name])+"."+s(m):s(p)+"."+s(l.table[Q.Symbol.Name])+"."+s(m),params:[]}}if(I(l,at)){const m=l[ie].schema,p=l[ie].name;return{sql:m===void 0||l[ie].isAlias?s(p):s(m)+"."+s(p),params:[]}}if(I(l,de)){if(I(l.value,me))return{sql:r(c.value++,l),params:[l],typings:["none"]};const m=l.value===null?null:l.encoder.mapToDriverValue(l.value);if(I(m,O))return this.buildQueryFromSourceParams([m],n);if(u)return{sql:this.mapInlineParam(m,n),params:[]};let p=["none"];return a&&(p=[a(l.encoder)]),{sql:r(c.value++,m),params:[m],typings:p}}return I(l,me)?{sql:r(c.value++,l),params:[l],typings:["none"]}:I(l,O.Aliased)&&l.fieldAlias!==void 0?{sql:s(l.fieldAlias),params:[]}:I(l,it)?l._.isWith?{sql:s(l._.alias),params:[]}:this.buildQueryFromSourceParams([new P("("),l._.sql,new P(") "),new ve(l._.alias)],n):wt(l)?l.schema?{sql:s(l.schema)+"."+s(l.enumName),params:[]}:{sql:s(l.enumName),params:[]}:st(l)?l.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([l.getSQL()],n):this.buildQueryFromSourceParams([new P("("),l.getSQL(),new P(")")],n):u?{sql:this.mapInlineParam(l,n),params:[]}:{sql:r(c.value++,l),params:[l],typings:["none"]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return"null";if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="string")return t(e);if(typeof e=="object"){const n=e.toString();return t(n==="[object Object]"?JSON.stringify(e):n)}throw new Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return e===void 0?this:new O.Aliased(this,e)}mapWith(e){return this.decoder=typeof e=="function"?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class ve{constructor(e){this.value=e}static[x]="Name";brand;getSQL(){return new O([this])}}function St(d){return typeof d=="object"&&d!==null&&"mapToDriverValue"in d&&typeof d.mapToDriverValue=="function"}const rt={mapFromDriverValue:d=>d},ot={mapToDriverValue:d=>d};({...rt,...ot});class de{constructor(e,t=ot){this.value=e,this.encoder=t}static[x]="Param";brand;getSQL(){return new O([this])}}function o(d,...e){const t=[];(e.length>0||d.length>0&&d[0]!=="")&&t.push(new P(d[0]));for(const[n,i]of e.entries())t.push(i,new P(d[n+1]));return new O(t)}(d=>{function e(){return new O([])}d.empty=e;function t(u){return new O(u)}d.fromList=t;function n(u){return new O([new P(u)])}d.raw=n;function i(u,c){const l=[];for(const[m,p]of u.entries())m>0&&c!==void 0&&l.push(c),l.push(p);return new O(l)}d.join=i;function s(u){return new ve(u)}d.identifier=s;function r(u){return new me(u)}d.placeholder=r;function a(u,c){return new de(u,c)}d.param=a})(o||(o={}));(d=>{class e{constructor(n,i){this.sql=n,this.fieldAlias=i}static[x]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}}d.Aliased=e})(O||(O={}));class me{constructor(e){this.name=e}static[x]="Placeholder";getSQL(){return new O([this])}}const Dt=Symbol.for("drizzle:IsDrizzleView");class at{static[x]="View";[ie];[Dt]=!0;constructor({name:e,schema:t,selectedFields:n,query:i}){this[ie]={name:e,originalName:e,schema:t,selectedFields:n,query:i,isExisting:!i,isAlias:!1}}getSQL(){return new O([this])}}se.prototype.getSQL=function(){return new O([this])};Q.prototype.getSQL=function(){return new O([this])};it.prototype.getSQL=function(){return new O([this])};function B(d,e){return St(e)&&!st(d)&&!I(d,de)&&!I(d,me)&&!I(d,se)&&!I(d,Q)&&!I(d,at)?new de(d,e):d}const k=(d,e)=>o`${d} = ${B(e,d)}`,Qe=(d,e)=>o`${d} <> ${B(e,d)}`;function A(...d){const e=d.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new O(e):new O([new P("("),o.join(e,new P(" and ")),new P(")")])}function oe(...d){const e=d.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?new O(e):new O([new P("("),o.join(e,new P(" or ")),new P(")")])}const Ee=(d,e)=>o`${d} > ${B(e,d)}`,ee=(d,e)=>o`${d} >= ${B(e,d)}`,Se=(d,e)=>o`${d} < ${B(e,d)}`,te=(d,e)=>o`${d} <= ${B(e,d)}`;function De(d,e){return Array.isArray(e)?e.length===0?o`false`:o`${d} in ${e.map(t=>B(t,d))}`:o`${d} in ${B(e,d)}`}function Ke(d,e){return Array.isArray(e)?e.length===0?o`true`:o`${d} not in ${e.map(t=>B(t,d))}`:o`${d} not in ${B(e,d)}`}function We(d){return o`${d} is null`}function Je(d){return o`${d} is not null`}function Nt(d,e){if(Array.isArray(e)){if(e.length===0)throw new Error("arrayContains requires at least one value");const t=o`${B(e,d)}`;return o`${d} @> ${t}`}return o`${d} @> ${B(e,d)}`}function At(d,e){if(Array.isArray(e)){if(e.length===0)throw new Error("arrayContained requires at least one value");const t=o`${B(e,d)}`;return o`${d} <@ ${t}`}return o`${d} <@ ${B(e,d)}`}function _t(d,e){if(Array.isArray(e)){if(e.length===0)throw new Error("arrayOverlaps requires at least one value");const t=o`${B(e,d)}`;return o`${d} && ${t}`}return o`${d} && ${B(e,d)}`}function ze(d){return o`${d} asc`}function vt(d){return o`${d} desc`}function Re(d){return o`count(${d||o.raw("*")})`.mapWith(Number)}function Rt(d){return o`count(distinct ${d})`.mapWith(Number)}function V(d){return o`sum(${d})`.mapWith(String)}function H(d){return o`max(${d})`.mapWith(I(d,se)?d:String)}function ae(d){return o`min(${d})`.mapWith(I(d,se)?d:String)}class he{preprocessCalculatedTemplate(e){return e}buildPattern(e,t){switch(e){case"contains":case"notContains":return`%${t}%`;case"startsWith":return`${t}%`;case"endsWith":return`%${t}`;default:return t}}parseISODuration(e){const t={years:0,months:0,days:0,hours:0,minutes:0,seconds:0},n=/^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/,i=e.match(n);if(!i)throw new Error(`Invalid ISO 8601 duration format: ${e}`);return t.years=parseInt(i[1]||"0",10),t.months=parseInt(i[2]||"0",10),t.days=parseInt(i[3]||"0",10),t.hours=parseInt(i[4]||"0",10),t.minutes=parseInt(i[5]||"0",10),t.seconds=parseFloat(i[6]||"0"),t}durationToSeconds(e){const t=this.parseISODuration(e);return t.years*365*24*60*60+t.months*30*24*60*60+t.days*24*60*60+t.hours*60*60+t.minutes*60+t.seconds}}class Ft extends he{getEngineType(){return"postgres"}supportsLateralJoins(){return!0}buildIntervalFromISO(e){const t=this.parseISODuration(e),n=[];t.years&&n.push(`${t.years} years`),t.months&&n.push(`${t.months} months`),t.days&&n.push(`${t.days} days`),t.hours&&n.push(`${t.hours} hours`),t.minutes&&n.push(`${t.minutes} minutes`),t.seconds&&n.push(`${t.seconds} seconds`);const i=n.join(" ")||"0 seconds";return o`INTERVAL '${o.raw(i)}'`}buildTimeDifferenceSeconds(e,t){return o`EXTRACT(EPOCH FROM (${e} - ${t}))`}buildDateAddInterval(e,t){const n=this.buildIntervalFromISO(t);return o`(${e} + ${n})`}buildConditionalAggregation(e,t,n){const i=e.toUpperCase();return e==="count"&&!t?o`COUNT(*) FILTER (WHERE ${n})`:o`${o.raw(i)}(${t}) FILTER (WHERE ${n})`}buildDateDiffPeriods(e,t,n){switch(n){case"day":return o`(${t}::date - ${e}::date)`;case"week":return o`FLOOR((${t}::date - ${e}::date) / 7)`;case"month":return o`(EXTRACT(YEAR FROM AGE(${t}::timestamp, ${e}::timestamp)) * 12 + EXTRACT(MONTH FROM AGE(${t}::timestamp, ${e}::timestamp)))::integer`;default:throw new Error(`Unsupported date diff unit: ${n}`)}}buildPeriodSeriesSubquery(e){return o`(SELECT generate_series(0, ${e}) as period_number) p`}buildTimeDimension(e,t){switch(e){case"year":return o`DATE_TRUNC('year', ${t}::timestamp)`;case"quarter":return o`DATE_TRUNC('quarter', ${t}::timestamp)`;case"month":return o`DATE_TRUNC('month', ${t}::timestamp)`;case"week":return o`DATE_TRUNC('week', ${t}::timestamp)`;case"day":return o`DATE_TRUNC('day', ${t}::timestamp)::timestamp`;case"hour":return o`DATE_TRUNC('hour', ${t}::timestamp)`;case"minute":return o`DATE_TRUNC('minute', ${t}::timestamp)`;case"second":return o`DATE_TRUNC('second', ${t}::timestamp)`;default:return t}}buildStringCondition(e,t,n){switch(t){case"contains":return o`${e} ILIKE ${`%${n}%`}`;case"notContains":return o`${e} NOT ILIKE ${`%${n}%`}`;case"startsWith":return o`${e} ILIKE ${`${n}%`}`;case"endsWith":return o`${e} ILIKE ${`%${n}`}`;case"like":return o`${e} LIKE ${n}`;case"notLike":return o`${e} NOT LIKE ${n}`;case"ilike":return o`${e} ILIKE ${n}`;case"regex":return o`${e} ~* ${n}`;case"notRegex":return o`${e} !~* ${n}`;default:throw new Error(`Unsupported string operator: ${t}`)}}castToType(e,t){switch(t){case"timestamp":return o`${e}::timestamp`;case"decimal":return o`${e}::decimal`;case"integer":return o`${e}::integer`;default:throw new Error(`Unsupported cast type: ${t}`)}}buildAvg(e){return o`COALESCE(AVG(${e}), 0)`}buildCaseWhen(e,t){const n=e.map(i=>o`WHEN ${i.when} THEN ${i.then}`).reduce((i,s)=>o`${i} ${s}`);return t!==void 0?o`CASE ${n} ELSE ${t} END`:o`CASE ${n} END`}buildBooleanLiteral(e){return e?o`TRUE`:o`FALSE`}convertFilterValue(e){return e}prepareDateValue(e){return e}isTimestampInteger(){return!1}convertTimeDimensionResult(e){return e}getCapabilities(){return{supportsStddev:!0,supportsVariance:!0,supportsPercentile:!0,supportsWindowFunctions:!0,supportsFrameClause:!0,supportsLateralJoins:!0,supportsPercentileSubqueries:!0}}buildStddev(e,t=!1){const n=t?"STDDEV_SAMP":"STDDEV_POP";return o`COALESCE(${o.raw(n)}(${e}), 0)`}buildVariance(e,t=!1){const n=t?"VAR_SAMP":"VAR_POP";return o`COALESCE(${o.raw(n)}(${e}), 0)`}buildPercentile(e,t){const n=t/100;return o`PERCENTILE_CONT(${n}) WITHIN GROUP (ORDER BY ${e})`}buildWindowFunction(e,t,n,i,s){const r=n&&n.length>0?o`PARTITION BY ${o.join(n,o`, `)}`:o``,a=i&&i.length>0?o`ORDER BY ${o.join(i.map(p=>p.direction==="desc"?o`${p.field} DESC`:o`${p.field} ASC`),o`, `)}`:o``;let u=o``;if(s?.frame){const{type:p,start:f,end:h}=s.frame,g=p.toUpperCase(),y=f==="unbounded"?"UNBOUNDED PRECEDING":typeof f=="number"?`${f} PRECEDING`:"CURRENT ROW",b=h==="unbounded"?"UNBOUNDED FOLLOWING":h==="current"?"CURRENT ROW":typeof h=="number"?`${h} FOLLOWING`:"CURRENT ROW";u=o`${o.raw(g)} BETWEEN ${o.raw(y)} AND ${o.raw(b)}`}const c=[];n&&n.length>0&&c.push(r),i&&i.length>0&&c.push(a),s?.frame&&c.push(u);const l=c.length>0?o.join(c,o` `):o``,m=o`OVER (${l})`;switch(e){case"lag":return o`LAG(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"lead":return o`LEAD(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"rank":return o`RANK() ${m}`;case"denseRank":return o`DENSE_RANK() ${m}`;case"rowNumber":return o`ROW_NUMBER() ${m}`;case"ntile":return o`NTILE(${s?.nTile??4}) ${m}`;case"firstValue":return o`FIRST_VALUE(${t}) ${m}`;case"lastValue":return o`LAST_VALUE(${t}) ${m}`;case"movingAvg":return o`AVG(${t}) ${m}`;case"movingSum":return o`SUM(${t}) ${m}`;default:throw new Error(`Unsupported window function: ${e}`)}}}class ut extends he{getEngineType(){return"mysql"}supportsLateralJoins(){return!0}buildIntervalFromISO(e){const t=this.parseISODuration(e),n=[];t.years&&n.push(`${t.years} YEAR`),t.months&&n.push(`${t.months} MONTH`),t.days&&n.push(`${t.days} DAY`),t.hours&&n.push(`${t.hours} HOUR`),t.minutes&&n.push(`${t.minutes} MINUTE`),t.seconds&&n.push(`${t.seconds} SECOND`);const i=this.durationToSeconds(e);return o`${i}`}buildTimeDifferenceSeconds(e,t){return o`TIMESTAMPDIFF(SECOND, ${t}, ${e})`}buildDateAddInterval(e,t){const n=this.parseISODuration(t);let i=e;return n.years&&(i=o`DATE_ADD(${i}, INTERVAL ${n.years} YEAR)`),n.months&&(i=o`DATE_ADD(${i}, INTERVAL ${n.months} MONTH)`),n.days&&(i=o`DATE_ADD(${i}, INTERVAL ${n.days} DAY)`),n.hours&&(i=o`DATE_ADD(${i}, INTERVAL ${n.hours} HOUR)`),n.minutes&&(i=o`DATE_ADD(${i}, INTERVAL ${n.minutes} MINUTE)`),n.seconds&&(i=o`DATE_ADD(${i}, INTERVAL ${n.seconds} SECOND)`),i}buildConditionalAggregation(e,t,n){const i=e.toUpperCase();return e==="count"&&!t?o`COUNT(CASE WHEN ${n} THEN 1 END)`:o`${o.raw(i)}(CASE WHEN ${n} THEN ${t} END)`}buildDateDiffPeriods(e,t,n){const i=n.toUpperCase();return o`TIMESTAMPDIFF(${o.raw(i)}, ${e}, ${t})`}buildPeriodSeriesSubquery(e){return o`(
|
|
2
|
+
WITH RECURSIVE periods(period_number) AS (
|
|
3
|
+
SELECT 0
|
|
4
|
+
UNION ALL
|
|
5
|
+
SELECT period_number + 1 FROM periods WHERE period_number < ${e}
|
|
6
|
+
)
|
|
7
|
+
SELECT period_number FROM periods
|
|
8
|
+
) p`}buildTimeDimension(e,t){const n={year:"%Y-01-01 00:00:00",quarter:"%Y-%q-01 00:00:00",month:"%Y-%m-01 00:00:00",week:"%Y-%u-01 00:00:00",day:"%Y-%m-%d 00:00:00",hour:"%Y-%m-%d %H:00:00",minute:"%Y-%m-%d %H:%i:00",second:"%Y-%m-%d %H:%i:%s"};switch(e){case"quarter":return o`DATE_ADD(MAKEDATE(YEAR(${t}), 1), INTERVAL (QUARTER(${t}) - 1) * 3 MONTH)`;case"week":return o`DATE_SUB(${t}, INTERVAL WEEKDAY(${t}) DAY)`;default:{const i=n[e];return i?o`STR_TO_DATE(DATE_FORMAT(${t}, ${i}), '%Y-%m-%d %H:%i:%s')`:t}}}buildStringCondition(e,t,n){switch(t){case"contains":return o`LOWER(${e}) LIKE ${`%${n.toLowerCase()}%`}`;case"notContains":return o`LOWER(${e}) NOT LIKE ${`%${n.toLowerCase()}%`}`;case"startsWith":return o`LOWER(${e}) LIKE ${`${n.toLowerCase()}%`}`;case"endsWith":return o`LOWER(${e}) LIKE ${`%${n.toLowerCase()}`}`;case"like":return o`${e} LIKE ${n}`;case"notLike":return o`${e} NOT LIKE ${n}`;case"ilike":return o`LOWER(${e}) LIKE ${n.toLowerCase()}`;case"regex":return o`${e} REGEXP ${n}`;case"notRegex":return o`${e} NOT REGEXP ${n}`;default:throw new Error(`Unsupported string operator: ${t}`)}}castToType(e,t){switch(t){case"timestamp":return o`CAST(${e} AS DATETIME)`;case"decimal":return o`CAST(${e} AS DECIMAL(10,2))`;case"integer":return o`CAST(${e} AS SIGNED INTEGER)`;default:throw new Error(`Unsupported cast type: ${t}`)}}buildAvg(e){return o`IFNULL(AVG(${e}), 0)`}buildCaseWhen(e,t){const n=e.map(i=>o`WHEN ${i.when} THEN ${i.then}`).reduce((i,s)=>o`${i} ${s}`);return t!==void 0?o`CASE ${n} ELSE ${t} END`:o`CASE ${n} END`}buildBooleanLiteral(e){return e?o`TRUE`:o`FALSE`}convertFilterValue(e){return e}prepareDateValue(e){return e}isTimestampInteger(){return!1}convertTimeDimensionResult(e){return e}getCapabilities(){return{supportsStddev:!0,supportsVariance:!0,supportsPercentile:!1,supportsWindowFunctions:!0,supportsFrameClause:!0,supportsLateralJoins:!0,supportsPercentileSubqueries:!1}}buildStddev(e,t=!1){const n=t?"STDDEV_SAMP":"STDDEV_POP";return o`IFNULL(${o.raw(n)}(${e}), 0)`}buildVariance(e,t=!1){const n=t?"VAR_SAMP":"VAR_POP";return o`IFNULL(${o.raw(n)}(${e}), 0)`}buildPercentile(e,t){return null}buildWindowFunction(e,t,n,i,s){const r=n&&n.length>0?o`PARTITION BY ${o.join(n,o`, `)}`:o``,a=i&&i.length>0?o`ORDER BY ${o.join(i.map(p=>p.direction==="desc"?o`${p.field} DESC`:o`${p.field} ASC`),o`, `)}`:o``;let u=o``;if(s?.frame){const{type:p,start:f,end:h}=s.frame,g=p.toUpperCase(),y=f==="unbounded"?"UNBOUNDED PRECEDING":typeof f=="number"?`${f} PRECEDING`:"CURRENT ROW",b=h==="unbounded"?"UNBOUNDED FOLLOWING":h==="current"?"CURRENT ROW":typeof h=="number"?`${h} FOLLOWING`:"CURRENT ROW";u=o`${o.raw(g)} BETWEEN ${o.raw(y)} AND ${o.raw(b)}`}const c=[];n&&n.length>0&&c.push(r),i&&i.length>0&&c.push(a),s?.frame&&c.push(u);const l=c.length>0?o.join(c,o` `):o``,m=o`OVER (${l})`;switch(e){case"lag":return o`LAG(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"lead":return o`LEAD(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"rank":return o`RANK() ${m}`;case"denseRank":return o`DENSE_RANK() ${m}`;case"rowNumber":return o`ROW_NUMBER() ${m}`;case"ntile":return o`NTILE(${s?.nTile??4}) ${m}`;case"firstValue":return o`FIRST_VALUE(${t}) ${m}`;case"lastValue":return o`LAST_VALUE(${t}) ${m}`;case"movingAvg":return o`AVG(${t}) ${m}`;case"movingSum":return o`SUM(${t}) ${m}`;default:throw new Error(`Unsupported window function: ${e}`)}}}class Mt extends he{getEngineType(){return"sqlite"}supportsLateralJoins(){return!1}buildIntervalFromISO(e){const t=this.durationToSeconds(e);return o`${t}`}buildTimeDifferenceSeconds(e,t){return o`(${e} - ${t})`}buildDateAddInterval(e,t){const n=this.durationToSeconds(t);return o`(${e} + ${n})`}buildConditionalAggregation(e,t,n){const i=e.toUpperCase();return e==="count"&&!t?o`COUNT(CASE WHEN ${n} THEN 1 END)`:o`${o.raw(i)}(CASE WHEN ${n} THEN ${t} END)`}buildDateDiffPeriods(e,t,n){switch(n){case"day":return o`CAST((julianday(datetime(${t}, 'unixepoch')) - julianday(datetime(${e}, 'unixepoch'))) AS INTEGER)`;case"week":return o`CAST((julianday(datetime(${t}, 'unixepoch')) - julianday(datetime(${e}, 'unixepoch'))) / 7 AS INTEGER)`;case"month":return o`((CAST(strftime('%Y', datetime(${t}, 'unixepoch')) AS INTEGER) - CAST(strftime('%Y', datetime(${e}, 'unixepoch')) AS INTEGER)) * 12 + (CAST(strftime('%m', datetime(${t}, 'unixepoch')) AS INTEGER) - CAST(strftime('%m', datetime(${e}, 'unixepoch')) AS INTEGER)))`;default:throw new Error(`Unsupported date diff unit for SQLite: ${n}`)}}buildPeriodSeriesSubquery(e){return o`(
|
|
9
|
+
WITH RECURSIVE periods(period_number) AS (
|
|
10
|
+
SELECT 0
|
|
11
|
+
UNION ALL
|
|
12
|
+
SELECT period_number + 1 FROM periods WHERE period_number < ${e}
|
|
13
|
+
)
|
|
14
|
+
SELECT period_number FROM periods
|
|
15
|
+
) p`}buildTimeDimension(e,t){switch(e){case"year":return o`datetime(${t}, 'unixepoch', 'start of year')`;case"quarter":{const n=o`datetime(${t}, 'unixepoch')`;return o`datetime(${n}, 'start of year',
|
|
16
|
+
'+' || (((CAST(strftime('%m', ${n}) AS INTEGER) - 1) / 3) * 3) || ' months')`}case"month":return o`datetime(${t}, 'unixepoch', 'start of month')`;case"week":return o`date(datetime(${t}, 'unixepoch'), 'weekday 1', '-6 days')`;case"day":return o`datetime(${t}, 'unixepoch', 'start of day')`;case"hour":{const n=o`datetime(${t}, 'unixepoch')`;return o`datetime(strftime('%Y-%m-%d %H:00:00', ${n}))`}case"minute":{const n=o`datetime(${t}, 'unixepoch')`;return o`datetime(strftime('%Y-%m-%d %H:%M:00', ${n}))`}case"second":{const n=o`datetime(${t}, 'unixepoch')`;return o`datetime(strftime('%Y-%m-%d %H:%M:%S', ${n}))`}default:return o`datetime(${t}, 'unixepoch')`}}buildStringCondition(e,t,n){switch(t){case"contains":return o`LOWER(${e}) LIKE ${`%${n.toLowerCase()}%`}`;case"notContains":return o`LOWER(${e}) NOT LIKE ${`%${n.toLowerCase()}%`}`;case"startsWith":return o`LOWER(${e}) LIKE ${`${n.toLowerCase()}%`}`;case"endsWith":return o`LOWER(${e}) LIKE ${`%${n.toLowerCase()}`}`;case"like":return o`${e} LIKE ${n}`;case"notLike":return o`${e} NOT LIKE ${n}`;case"ilike":return o`LOWER(${e}) LIKE ${n.toLowerCase()}`;case"regex":return o`${e} GLOB ${n}`;case"notRegex":return o`${e} NOT GLOB ${n}`;default:throw new Error(`Unsupported string operator: ${t}`)}}castToType(e,t){switch(t){case"timestamp":return o`datetime(${e} / 1000, 'unixepoch')`;case"decimal":return o`CAST(${e} AS REAL)`;case"integer":return o`CAST(${e} AS INTEGER)`;default:throw new Error(`Unsupported cast type: ${t}`)}}buildAvg(e){return o`IFNULL(AVG(${e}), 0)`}buildCaseWhen(e,t){const n=e.map(i=>i.then&&typeof i.then=="object"&&(i.then.queryChunks||i.then._||i.then.sql)?o`WHEN ${i.when} THEN ${o.raw("(")}${i.then}${o.raw(")")}`:o`WHEN ${i.when} THEN ${i.then}`).reduce((i,s)=>o`${i} ${s}`);return t!==void 0?t&&typeof t=="object"&&(t.queryChunks||t._||t.sql)?o`CASE ${n} ELSE ${o.raw("(")}${t}${o.raw(")")} END`:o`CASE ${n} ELSE ${t} END`:o`CASE ${n} END`}buildBooleanLiteral(e){return e?o`1`:o`0`}preprocessCalculatedTemplate(e){const t=/(\{[^}]+\})\s*\/\s*/g;return e.replace(t,(n,i)=>`${i.replace(/\{([^}]+)\}/,"CAST({$1} AS REAL)")} / `)}convertFilterValue(e){return typeof e=="boolean"?e?1:0:e instanceof Date?e.getTime():Array.isArray(e)?e.map(t=>this.convertFilterValue(t)):e}prepareDateValue(e){if(!(e instanceof Date)){if(typeof e=="number")return e;if(typeof e=="string")return new Date(e).getTime();throw new Error(`prepareDateValue expects a Date object, got ${typeof e}`)}return e.getTime()}isTimestampInteger(){return!0}convertTimeDimensionResult(e){return e}getCapabilities(){return{supportsStddev:!1,supportsVariance:!1,supportsPercentile:!1,supportsWindowFunctions:!0,supportsFrameClause:!0,supportsLateralJoins:!1,supportsPercentileSubqueries:!1}}buildStddev(e,t=!1){return null}buildVariance(e,t=!1){return null}buildPercentile(e,t){return null}buildWindowFunction(e,t,n,i,s){const r=n&&n.length>0?o`PARTITION BY ${o.join(n,o`, `)}`:o``,a=i&&i.length>0?o`ORDER BY ${o.join(i.map(p=>p.direction==="desc"?o`${p.field} DESC`:o`${p.field} ASC`),o`, `)}`:o``;let u=o``;if(s?.frame){const{type:p,start:f,end:h}=s.frame,g=p.toUpperCase(),y=f==="unbounded"?"UNBOUNDED PRECEDING":typeof f=="number"?`${f} PRECEDING`:"CURRENT ROW",b=h==="unbounded"?"UNBOUNDED FOLLOWING":h==="current"?"CURRENT ROW":typeof h=="number"?`${h} FOLLOWING`:"CURRENT ROW";u=o`${o.raw(g)} BETWEEN ${o.raw(y)} AND ${o.raw(b)}`}const c=[];n&&n.length>0&&c.push(r),i&&i.length>0&&c.push(a),s?.frame&&c.push(u);const l=c.length>0?o.join(c,o` `):o``,m=o`OVER (${l})`;switch(e){case"lag":return o`LAG(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"lead":return o`LEAD(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"rank":return o`RANK() ${m}`;case"denseRank":return o`DENSE_RANK() ${m}`;case"rowNumber":return o`ROW_NUMBER() ${m}`;case"ntile":return o`NTILE(${s?.nTile??4}) ${m}`;case"firstValue":return o`FIRST_VALUE(${t}) ${m}`;case"lastValue":return o`LAST_VALUE(${t}) ${m}`;case"movingAvg":return o`AVG(${t}) ${m}`;case"movingSum":return o`SUM(${t}) ${m}`;default:throw new Error(`Unsupported window function: ${e}`)}}}class Ot extends ut{getEngineType(){return"singlestore"}}class jt extends he{getEngineType(){return"duckdb"}supportsLateralJoins(){return!1}buildIntervalFromISO(e){const t=this.parseISODuration(e),n=[];t.years&&n.push(`${t.years} years`),t.months&&n.push(`${t.months} months`),t.days&&n.push(`${t.days} days`),t.hours&&n.push(`${t.hours} hours`),t.minutes&&n.push(`${t.minutes} minutes`),t.seconds&&n.push(`${t.seconds} seconds`);const i=n.join(" ")||"0 seconds";return o`INTERVAL '${o.raw(i)}'`}buildTimeDifferenceSeconds(e,t){return o`(EPOCH(${e}) - EPOCH(${t}))`}buildDateAddInterval(e,t){const n=this.buildIntervalFromISO(t);return o`(${e} + ${n})`}buildConditionalAggregation(e,t,n){const i=e.toUpperCase();return e==="count"&&!t?o`COUNT(*) FILTER (WHERE ${n})`:o`${o.raw(i)}(${t}) FILTER (WHERE ${n})`}buildDateDiffPeriods(e,t,n){return o`DATE_DIFF('${o.raw(n)}', ${e}::timestamp, ${t}::timestamp)`}buildPeriodSeriesSubquery(e){return o`(SELECT UNNEST(generate_series(0, ${e})) as period_number) p`}buildTimeDimension(e,t){switch(e){case"year":return o`DATE_TRUNC('year', ${t}::timestamp)`;case"quarter":return o`DATE_TRUNC('quarter', ${t}::timestamp)`;case"month":return o`DATE_TRUNC('month', ${t}::timestamp)`;case"week":return o`DATE_TRUNC('week', ${t}::timestamp)`;case"day":return o`DATE_TRUNC('day', ${t}::timestamp)::timestamp`;case"hour":return o`DATE_TRUNC('hour', ${t}::timestamp)`;case"minute":return o`DATE_TRUNC('minute', ${t}::timestamp)`;case"second":return o`DATE_TRUNC('second', ${t}::timestamp)`;default:return t}}buildStringCondition(e,t,n){switch(t){case"contains":return o`${e} ILIKE ${`%${n}%`}`;case"notContains":return o`${e} NOT ILIKE ${`%${n}%`}`;case"startsWith":return o`${e} ILIKE ${`${n}%`}`;case"endsWith":return o`${e} ILIKE ${`%${n}`}`;case"like":return o`${e} LIKE ${n}`;case"notLike":return o`${e} NOT LIKE ${n}`;case"ilike":return o`${e} ILIKE ${n}`;case"regex":return o`regexp_matches(${e}, ${n})`;case"notRegex":return o`NOT regexp_matches(${e}, ${n})`;default:throw new Error(`Unsupported string operator: ${t}`)}}castToType(e,t){switch(t){case"timestamp":return o`${e}::timestamp`;case"decimal":return o`${e}::decimal`;case"integer":return o`${e}::integer`;default:throw new Error(`Unsupported cast type: ${t}`)}}buildAvg(e){return o`COALESCE(AVG(${e}), 0)`}buildCaseWhen(e,t){const n=e.map(i=>o`WHEN ${i.when} THEN ${i.then}`).reduce((i,s)=>o`${i} ${s}`);return t!==void 0?o`CASE ${n} ELSE ${t} END`:o`CASE ${n} END`}buildBooleanLiteral(e){return e?o`TRUE`:o`FALSE`}convertFilterValue(e){return e}prepareDateValue(e){return e}isTimestampInteger(){return!1}convertTimeDimensionResult(e){return e}getCapabilities(){return{supportsStddev:!0,supportsVariance:!0,supportsPercentile:!0,supportsWindowFunctions:!0,supportsFrameClause:!0,supportsLateralJoins:!1,supportsPercentileSubqueries:!1}}buildStddev(e,t=!1){const n=t?"STDDEV_SAMP":"STDDEV_POP";return o`COALESCE(${o.raw(n)}(${e}), 0)`}buildVariance(e,t=!1){const n=t?"VAR_SAMP":"VAR_POP";return o`COALESCE(${o.raw(n)}(${e}), 0)`}buildPercentile(e,t){const n=t/100;return o`QUANTILE_CONT(${e}, ${n})`}buildWindowFunction(e,t,n,i,s){const r=n&&n.length>0?o`PARTITION BY ${o.join(n,o`, `)}`:o``,a=i&&i.length>0?o`ORDER BY ${o.join(i.map(p=>p.direction==="desc"?o`${p.field} DESC`:o`${p.field} ASC`),o`, `)}`:o``;let u=o``;if(s?.frame){const{type:p,start:f,end:h}=s.frame,g=p.toUpperCase(),y=f==="unbounded"?"UNBOUNDED PRECEDING":typeof f=="number"?`${f} PRECEDING`:"CURRENT ROW",b=h==="unbounded"?"UNBOUNDED FOLLOWING":h==="current"?"CURRENT ROW":typeof h=="number"?`${h} FOLLOWING`:"CURRENT ROW";u=o`${o.raw(g)} BETWEEN ${o.raw(y)} AND ${o.raw(b)}`}const c=[];n&&n.length>0&&c.push(r),i&&i.length>0&&c.push(a),s?.frame&&c.push(u);const l=c.length>0?o.join(c,o` `):o``,m=o`OVER (${l})`;switch(e){case"lag":return o`LAG(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"lead":return o`LEAD(${t}, ${s?.offset??1}${s?.defaultValue!==void 0?o`, ${s.defaultValue}`:o``}) ${m}`;case"rank":return o`RANK() ${m}`;case"denseRank":return o`DENSE_RANK() ${m}`;case"rowNumber":return o`ROW_NUMBER() ${m}`;case"ntile":return o`NTILE(${s?.nTile??4}) ${m}`;case"firstValue":return o`FIRST_VALUE(${t}) ${m}`;case"lastValue":return o`LAST_VALUE(${t}) ${m}`;case"movingAvg":return o`AVG(${t}) ${m}`;case"movingSum":return o`SUM(${t}) ${m}`;default:throw new Error(`Unsupported window function: ${e}`)}}}function It(d){switch(d){case"postgres":return new Ft;case"mysql":return new ut;case"sqlite":return new Mt;case"singlestore":return new Ot;case"duckdb":return new jt;default:throw new Error(`Unsupported database engine: ${d}`)}}class ge{constructor(e,t,n){this.db=e,this.schema=t;const i=n||this.getEngineType();this.databaseAdapter=It(i)}databaseAdapter}function Lt(d,e){const t=[],n=[];let i=!1,s,r,a;const u=[];for(const l of d){const m=l.match(/Planning Time:\s*([\d.]+)\s*ms/i);if(m){s=parseFloat(m[1]);continue}const p=l.match(/Execution Time:\s*([\d.]+)\s*ms/i);if(p){r=parseFloat(p[1]);continue}const f=Pt(l);if(f){f.type.includes("Seq Scan")&&(i=!0),f.index&&n.push(f.index),t.length===0&&f.estimatedCost!==void 0&&(a=f.estimatedCost);const h=l.search(/\S/);for(;u.length>0&&u[u.length-1].indent>=h;)u.pop();if(u.length===0)t.push(f);else{const g=u[u.length-1].op;g.children||(g.children=[]),g.children.push(f)}u.push({indent:h,op:f})}}const c={database:"postgres",planningTime:s,executionTime:r,totalCost:a,hasSequentialScans:i,usedIndexes:[...new Set(n)]};return{operations:t,summary:c,raw:d.join(`
|
|
17
|
+
`),sql:e}}function Pt(d){const e=d.replace(/^[\s->]+/,"").trim();if(!e)return null;const t=e.match(/^([A-Za-z][A-Za-z0-9 ]+?)(?:\s+using\s+(\S+))?(?:\s+on\s+(\S+))?(?:\s+\w+)?(?:\s+\(cost=([\d.]+)\.\.([\d.]+)\s+rows=(\d+)(?:\s+width=\d+)?\))?(?:\s+\(actual time=([\d.]+)\.\.([\d.]+)\s+rows=(\d+)\s+loops=(\d+)\))?/i);if(!t)return e.match(/^Filter:\s*(.+)$/i)||e.match(/^(Hash Cond|Join Filter|Index Cond):\s*(.+)$/i),null;const n=t[1].trim(),i=t[2]||void 0,s=t[3]||void 0,r=t[5]?parseFloat(t[5]):void 0,a=t[6]?parseInt(t[6],10):void 0,u=t[9]?parseInt(t[9],10):void 0,c={type:n,table:s,index:i,estimatedRows:a,estimatedCost:r};u!==void 0&&(c.actualRows=u);const l=d.match(/Filter:\s*(.+?)(?:\)|$)/i);return l&&(c.filter=l[1].trim()),c}class Bt extends ge{async execute(e,t){if(e&&typeof e=="object"&&typeof e.execute=="function"){const i=await e.execute();return Array.isArray(i)?i.map(s=>this.convertNumericFields(s,t)):i}if(!this.db.execute)throw new Error("PostgreSQL database instance must have an execute method");const n=await this.db.execute(e);return Array.isArray(n)?n.map(i=>this.convertNumericFields(i,t)):n}convertNumericFields(e,t){if(!e||typeof e!="object")return e;const n={};for(const[i,s]of Object.entries(e))t&&t.includes(i)?n[i]=this.coerceToNumber(s):n[i]=s;return n}coerceToNumber(e){if(e==null||typeof e=="number")return e;if(typeof e=="bigint")return Number(e);if(e&&typeof e=="object"){if(typeof e.toString=="function"){const t=e.toString();if(/^-?\d+(\.\d+)?$/.test(t))return t.includes(".")?parseFloat(t):parseInt(t,10)}if(e.constructor?.name==="Numeric"||e.constructor?.name==="Decimal"||"digits"in e||"sign"in e){const t=e.toString();return parseFloat(t)}return e}if(typeof e=="string"){if(/^-?\d+(\.\d+)?$/.test(e))return e.includes(".")?parseFloat(e):parseInt(e,10);if(!isNaN(parseFloat(e))&&isFinite(parseFloat(e)))return parseFloat(e)}return e}getEngineType(){return"postgres"}async explainQuery(e,t,n){const i=n?.analyze?"EXPLAIN ANALYZE":"EXPLAIN";if(!this.db.execute)throw new Error("PostgreSQL database instance must have an execute method");const s=await this.db.execute(o`${o.raw(i)} ${o.raw(e.replace(/\$(\d+)/g,(a,u)=>{const c=parseInt(u,10)-1,l=t[c];return l===null?"NULL":typeof l=="number"?String(l):typeof l=="boolean"?l?"TRUE":"FALSE":l instanceof Date?`'${l.toISOString()}'`:`'${String(l).replace(/'/g,"''")}'`}))}`),r=[];if(Array.isArray(s)){for(const a of s)if(a&&typeof a=="object"){const u=a["QUERY PLAN"]||a["query plan"]||a.queryplan;typeof u=="string"&&r.push(u)}}return Lt(r,{sql:e,params:t})}async getTableIndexes(e){if(!e||e.length===0)return[];if(!this.db.execute)throw new Error("PostgreSQL database instance must have an execute method");try{const t=e.map(i=>`'${i.toLowerCase()}'`).join(","),n=await this.db.execute(o`
|
|
18
|
+
SELECT
|
|
19
|
+
t.relname as table_name,
|
|
20
|
+
i.relname as index_name,
|
|
21
|
+
array_to_string(array_agg(a.attname ORDER BY k.n), ',') as columns,
|
|
22
|
+
ix.indisunique as is_unique,
|
|
23
|
+
ix.indisprimary as is_primary
|
|
24
|
+
FROM pg_index ix
|
|
25
|
+
JOIN pg_class t ON t.oid = ix.indrelid
|
|
26
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
27
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
28
|
+
JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, n) ON true
|
|
29
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
30
|
+
WHERE n.nspname = 'public'
|
|
31
|
+
AND t.relname IN (${o.raw(t)})
|
|
32
|
+
GROUP BY t.relname, i.relname, ix.indisunique, ix.indisprimary
|
|
33
|
+
ORDER BY t.relname, i.relname
|
|
34
|
+
`);return Array.isArray(n)?n.map(i=>({table_name:i.table_name,index_name:i.index_name,columns:i.columns.split(","),is_unique:i.is_unique,is_primary:i.is_primary})):[]}catch(t){return console.warn("Failed to get table indexes:",t),[]}}}function qe(d,e){return new Bt(d,e,"postgres")}function kt(d,e){const t=e?.toLowerCase()||"";switch(d.toLowerCase()){case"all":return"Seq Scan";case"index":return t.includes("using index")?"Index Only Scan":"Index Scan";case"range":return"Index Range Scan";case"ref":case"eq_ref":return"Index Lookup";case"const":case"system":return"Const Lookup";case"null":return"No Table";default:return`MySQL ${d}`}}function xt(d,e){const t=[],n=[];let i=!1,s=0;for(const u of d){const c=kt(u.type,u.Extra);u.type.toLowerCase()==="all"&&(i=!0),u.key&&n.push(u.key);const l={type:c,table:u.table||void 0,index:u.key||void 0,estimatedRows:u.rows,estimatedCost:u.rows};if(u.Extra){const m=[];u.Extra.includes("Using where")&&m.push("WHERE filter applied"),u.Extra.includes("Using filesort")&&m.push("Filesort required"),u.Extra.includes("Using temporary")&&m.push("Temporary table required"),u.Extra.includes("Using join buffer")&&m.push("Join buffer used"),m.length>0&&(l.details=m.join("; ")),l.filter=u.Extra}t.push(l),s+=u.rows}const r={database:"mysql",planningTime:void 0,executionTime:void 0,totalCost:s,hasSequentialScans:i,usedIndexes:[...new Set(n)]},a=["id select_type table type possible_keys key rows Extra",...d.map(u=>`${u.id} ${u.select_type} ${u.table||"NULL"} ${u.type} ${u.possible_keys||"NULL"} ${u.key||"NULL"} ${u.rows} ${u.Extra||""}`)];return{operations:t,summary:r,raw:a.join(`
|
|
35
|
+
`),sql:e}}class lt extends ge{async execute(e,t){if(e&&typeof e=="object"&&typeof e.execute=="function"){const i=await e.execute();return Array.isArray(i)?i.map(s=>this.convertNumericFields(s,t)):i}if(!this.db.execute)throw new Error("MySQL database instance must have an execute method");const n=await this.db.execute(e);return Array.isArray(n)?n.map(i=>this.convertNumericFields(i,t)):n}convertNumericFields(e,t){if(!e||typeof e!="object")return e;const n={};for(const[i,s]of Object.entries(e))t&&t.includes(i)?n[i]=this.coerceToNumber(s):n[i]=s;return n}coerceToNumber(e){if(e==null||typeof e=="number")return e;if(typeof e=="string"){if(/^-?\d+(\.\d+)?$/.test(e))return e.includes(".")?parseFloat(e):parseInt(e,10);if(!isNaN(parseFloat(e))&&isFinite(parseFloat(e)))return parseFloat(e)}return e}getEngineType(){return"mysql"}async explainQuery(e,t,n){let i=e,s=0;i=i.replace(/\?/g,()=>{const c=t[s++];return c===null?"NULL":typeof c=="number"?String(c):typeof c=="boolean"?c?"1":"0":c instanceof Date?`'${c.toISOString().slice(0,19).replace("T"," ")}'`:`'${String(c).replace(/'/g,"''")}'`});const r=n?.analyze?"EXPLAIN ANALYZE":"EXPLAIN";if(!this.db.execute)throw new Error("MySQL database instance must have an execute method");const a=await this.db.execute(o.raw(`${r} ${i}`)),u=[];if(Array.isArray(a))for(const c of a)c&&typeof c=="object"&&u.push({id:c.id||1,select_type:c.select_type||"SIMPLE",table:c.table||null,partitions:c.partitions||null,type:c.type||"ALL",possible_keys:c.possible_keys||null,key:c.key||null,key_len:c.key_len||null,ref:c.ref||null,rows:Number(c.rows)||0,filtered:Number(c.filtered)||100,Extra:c.Extra||null});return xt(u,{sql:e,params:t})}async getTableIndexes(e){if(!e||e.length===0)return[];if(!this.db.execute)throw new Error("MySQL database instance must have an execute method");try{const t=e.map(i=>`'${i.toLowerCase()}'`).join(","),n=await this.db.execute(o`
|
|
36
|
+
SELECT
|
|
37
|
+
TABLE_NAME as table_name,
|
|
38
|
+
INDEX_NAME as index_name,
|
|
39
|
+
GROUP_CONCAT(COLUMN_NAME ORDER BY SEQ_IN_INDEX) as columns,
|
|
40
|
+
CASE WHEN NON_UNIQUE = 0 THEN TRUE ELSE FALSE END as is_unique,
|
|
41
|
+
CASE WHEN INDEX_NAME = 'PRIMARY' THEN TRUE ELSE FALSE END as is_primary
|
|
42
|
+
FROM INFORMATION_SCHEMA.STATISTICS
|
|
43
|
+
WHERE TABLE_SCHEMA = DATABASE()
|
|
44
|
+
AND LOWER(TABLE_NAME) IN (${o.raw(t)})
|
|
45
|
+
GROUP BY TABLE_NAME, INDEX_NAME, NON_UNIQUE
|
|
46
|
+
ORDER BY TABLE_NAME, INDEX_NAME
|
|
47
|
+
`);return Array.isArray(n)?n.map(i=>({table_name:i.table_name,index_name:i.index_name,columns:i.columns.split(","),is_unique:!!i.is_unique,is_primary:!!i.is_primary})):[]}catch(t){return console.warn("Failed to get table indexes:",t),[]}}}function Ut(d,e){return new lt(d,e,"mysql")}function Qt(d){const e=d.toLowerCase(),t=d.match(/^SCAN\s+(\S+)/i);if(t)return{type:"Seq Scan",table:t[1]};const n=d.match(/^SEARCH\s+(\S+)\s+USING\s+(?:COVERING\s+)?INDEX\s+(\S+)(?:\s+\((.+)\))?/i);if(n)return{type:"Index Scan",table:n[1],index:n[2],filter:n[3]};const i=d.match(/^SEARCH\s+(\S+)\s+USING\s+INTEGER\s+PRIMARY\s+KEY\s+\((.+)\)/i);if(i)return{type:"Primary Key Lookup",table:i[1],filter:i[2]};const s=d.match(/^SEARCH\s+(\S+)/i);return s?{type:"Search",table:s[1]}:e.includes("temp b-tree")?e.includes("order by")?{type:"Sort"}:e.includes("group by")?{type:"Group"}:e.includes("distinct")?{type:"Distinct"}:{type:"Temp B-Tree"}:e.includes("compound")?{type:"Compound Query"}:e.includes("subquery")?{type:"Subquery"}:e.includes("co-routine")?{type:"Coroutine"}:{type:d}}function Kt(d,e){const t=[],n=[];let i=!1;const s=new Map;for(const u of d){const c=Qt(u.detail);c.type==="Seq Scan"&&(i=!0),c.index&&n.push(c.index);const l={type:c.type,table:c.table,index:c.index,filter:c.filter,details:u.detail};if(s.set(u.id,l),u.parent===0)t.push(l);else{const m=s.get(u.parent);m?(m.children||(m.children=[]),m.children.push(l)):t.push(l)}}const r={database:"sqlite",planningTime:void 0,executionTime:void 0,totalCost:void 0,hasSequentialScans:i,usedIndexes:[...new Set(n)]},a=["id parent detail",...d.map(u=>`${u.id} ${u.parent} ${u.detail}`)];return{operations:t,summary:r,raw:a.join(`
|
|
48
|
+
`),sql:e}}class Wt extends ge{async execute(e,t){if(e&&typeof e=="object"&&typeof e.execute=="function"){const n=await e.execute();return Array.isArray(n)?n.map(i=>this.convertNumericFields(i,t)):n}try{if(this.db.all){const n=this.db.all(e);return Array.isArray(n)?n.map(i=>this.convertNumericFields(i,t)):n}else{if(this.db.run)return this.db.run(e);throw new Error("SQLite database instance must have an all() or run() method")}}catch(n){throw new Error(`SQLite execution failed: ${n instanceof Error?n.message:"Unknown error"}`)}}convertNumericFields(e,t){if(!e||typeof e!="object")return e;const n={};for(const[i,s]of Object.entries(e))t&&t.includes(i)?n[i]=this.coerceToNumber(s):n[i]=s;return n}coerceToNumber(e){if(e==null||typeof e=="number")return e;if(typeof e=="string"){if(/^-?\d+(\.\d+)?$/.test(e))return e.includes(".")?parseFloat(e):parseInt(e,10);if(!isNaN(parseFloat(e))&&isFinite(parseFloat(e)))return parseFloat(e)}return e}getEngineType(){return"sqlite"}async explainQuery(e,t,n){let i=e,s=0;i=i.replace(/\?/g,()=>{const c=t[s++];return c===null?"NULL":typeof c=="number"?String(c):typeof c=="boolean"?c?"1":"0":c instanceof Date?`'${c.toISOString()}'`:`'${String(c).replace(/'/g,"''")}'`});const r=`EXPLAIN QUERY PLAN ${i}`;let a=[];if(this.db.all)a=this.db.all(o.raw(r));else throw new Error("SQLite database instance must have an all() method for EXPLAIN");const u=[];if(Array.isArray(a))for(const c of a)c&&typeof c=="object"&&u.push({id:Number(c.id)||0,parent:Number(c.parent)||0,notused:Number(c.notused)||0,detail:String(c.detail||"")});return Kt(u,{sql:e,params:t})}async getTableIndexes(e){if(!e||e.length===0)return[];if(!this.db.all)throw new Error("SQLite database instance must have an all() method");try{const t=[];for(const n of e){const i=this.db.all(o.raw(`SELECT name, "unique", origin FROM pragma_index_list('${n.toLowerCase()}')`));if(Array.isArray(i))for(const s of i){const r=s.name,a=!!s.unique,u=s.origin,c=this.db.all(o.raw(`SELECT name FROM pragma_index_info('${r}') ORDER BY seqno`)),l=[];if(Array.isArray(c))for(const m of c){const p=m.name;typeof p=="string"&&l.push(p)}t.push({table_name:n.toLowerCase(),index_name:r,columns:l,is_unique:a,is_primary:u==="pk"})}}return t}catch(t){return console.warn("Failed to get table indexes:",t),[]}}}function Ve(d,e){return new Wt(d,e,"sqlite")}class Jt extends lt{getEngineType(){return"singlestore"}}function zt(d,e){return new Jt(d,e)}function qt(d,e){const t=[],n=[];let i=!1,s;const r=[];for(const u of d){if(/^[┌├└│─┐┤┘]+$/.test(u.trim())||/EXPLANATION|QUERY PLAN/i.test(u))continue;const c=Gt(u);if(c){(c.type.includes("SEQ_SCAN")||c.type.includes("TABLE_SCAN"))&&(i=!0),c.type.includes("INDEX_SCAN")&&c.index&&n.push(c.index),t.length===0&&c.estimatedCost!==void 0&&(s=c.estimatedCost);const l=Vt(u);for(;r.length>0&&r[r.length-1].indent>=l;)r.pop();if(r.length===0)t.push(c);else{const m=r[r.length-1].op;m.children||(m.children=[]),m.children.push(c)}r.push({indent:l,op:c})}}const a={database:"duckdb",planningTime:void 0,executionTime:void 0,totalCost:s,hasSequentialScans:i,usedIndexes:[...new Set(n)]};return{operations:t,summary:a,raw:d.join(`
|
|
49
|
+
`),sql:e}}function Vt(d){let e=0;for(const t of d)if(t===" "||t==="│"||t==="├"||t==="└"||t==="─")e++;else break;return e}function Gt(d){const e=d.replace(/[┌├└│─┐┤┘]/g,"").replace(/^\s*/,"").trim();if(!e||e.match(/^\(cost=([\d.]+)\s+rows=(\d+)\)$/i))return null;const n=e.match(/^([A-Z_]+)(?:\s+(\S+))?(?:\s+on\s+(\S+))?(?:\s+\(cost=([\d.]+)\s+rows=(\d+)\))?/i);if(!n){const l=e.match(/^FILTER\s+(.+)$/i);return l?{type:"FILTER",filter:l[1]}:null}const i=n[1].toUpperCase();let s=n[2]||void 0,r=n[3]||void 0;const a=n[4]?parseFloat(n[4]):void 0,u=n[5]?parseInt(n[5],10):void 0;if(i==="INDEX_SCAN"){const l=s,m=r;r=l,s=m}return{type:i,table:s,index:r,estimatedRows:u,estimatedCost:a}}class Ht extends ge{async execute(e,t){if(e&&typeof e=="object"&&typeof e.execute=="function")try{const n=await e.execute();return Array.isArray(n)?n.map(i=>this.convertNumericFields(i,t)):n}catch(n){const i=this.extractSqlFromQuery(e);throw console.error("[DuckDB] Query execution failed:",{error:n instanceof Error?n.message:String(n),sql:i.sql,params:i.params}),n}if(!this.db.execute)throw new Error("DuckDB database instance must have an execute method");try{const n=await this.db.execute(e);return Array.isArray(n)?n.map(i=>this.convertNumericFields(i,t)):n}catch(n){const i=this.extractSqlFromQuery(e);throw console.error("[DuckDB] Query execution failed:",{error:n instanceof Error?n.message:String(n),sql:i.sql,params:i.params}),n}}extractSqlFromQuery(e){try{if(e&&typeof e.toSQL=="function"){const{sql:t,params:n}=e.toSQL();return{sql:t,params:n}}if(e&&typeof e.getSQL=="function"){const t=e.getSQL();if(t&&typeof t.toSQL=="function"){const{sql:n,params:i}=t.toSQL();return{sql:n,params:i}}}return{sql:String(e),params:[]}}catch{return{sql:"[unable to extract SQL]",params:[]}}}convertNumericFields(e,t){if(!e||typeof e!="object")return e;const n={};for(const[i,s]of Object.entries(e))t&&t.includes(i)?n[i]=this.coerceToNumber(s):n[i]=s;return n}coerceToNumber(e){if(e==null||typeof e=="number")return e;if(typeof e=="bigint")return Number(e);if(e&&typeof e=="object"){if(typeof e.toString=="function"){const t=e.toString();if(/^-?\d+(\.\d+)?$/.test(t))return t.includes(".")?parseFloat(t):parseInt(t,10)}return e}if(typeof e=="string"){if(/^-?\d+(\.\d+)?$/.test(e))return e.includes(".")?parseFloat(e):parseInt(e,10);if(!isNaN(parseFloat(e))&&isFinite(parseFloat(e)))return parseFloat(e)}return e}getEngineType(){return"duckdb"}async explainQuery(e,t,n){const i=n?.analyze?"EXPLAIN ANALYZE":"EXPLAIN";if(!this.db.execute)throw new Error("DuckDB database instance must have an execute method");const s=await this.db.execute(o`${o.raw(i)} ${o.raw(e.replace(/\$(\d+)/g,(a,u)=>{const c=parseInt(u,10)-1,l=t[c];return l===null?"NULL":typeof l=="number"?String(l):typeof l=="boolean"?l?"TRUE":"FALSE":l instanceof Date?`'${l.toISOString()}'`:`'${String(l).replace(/'/g,"''")}'`}))}`),r=[];if(Array.isArray(s)){for(const a of s)if(a&&typeof a=="object"){const u=a.explain_value||a["QUERY PLAN"]||a.query_plan||a.Plan||Object.values(a)[0];typeof u=="string"&&r.push(u)}}return qt(r,{sql:e,params:t})}async getTableIndexes(e){if(!e||e.length===0)return[];if(!this.db.execute)throw new Error("DuckDB database instance must have an execute method");try{const t=e.map(i=>`'${i.toLowerCase()}'`).join(","),n=await this.db.execute(o`
|
|
50
|
+
SELECT
|
|
51
|
+
table_name,
|
|
52
|
+
index_name,
|
|
53
|
+
LISTAGG(column_name, ',') WITHIN GROUP (ORDER BY index_oid) as columns,
|
|
54
|
+
is_unique,
|
|
55
|
+
is_primary
|
|
56
|
+
FROM duckdb_indexes()
|
|
57
|
+
WHERE LOWER(table_name) IN (${o.raw(t)})
|
|
58
|
+
GROUP BY table_name, index_name, is_unique, is_primary
|
|
59
|
+
ORDER BY table_name, index_name
|
|
60
|
+
`);return Array.isArray(n)?n.map(i=>({table_name:i.table_name,index_name:i.index_name,columns:typeof i.columns=="string"?i.columns.split(","):[],is_unique:!!i.is_unique,is_primary:!!i.is_primary})):[]}catch(t){return console.warn("Failed to get table indexes:",t),[]}}}function Yt(d,e){return new Ht(d,e,"duckdb")}function Ge(d,e,t){if(t)switch(t){case"postgres":return qe(d,e);case"mysql":return Ut(d,e);case"sqlite":return Ve(d,e);case"singlestore":return zt(d,e);case"duckdb":return Yt(d,e)}if(d.all&&d.run)return Ve(d,e);if(d.execute)return qe(d,e);throw new Error("Unable to determine database engine type. Please specify engineType parameter.")}function K(d){return typeof d=="function"?d():d}function Ne(d){switch(d){case"belongsTo":return"hasMany";case"hasMany":return"belongsTo";case"hasOne":return"hasOne";case"belongsToMany":return"belongsToMany";default:return d}}function Fe(d,e){if(e)return e;switch(d){case"belongsTo":return"inner";case"hasOne":return"left";case"hasMany":return"left";case"belongsToMany":return"left";default:return"left"}}function Me(d){return d&&typeof d=="object"?o`${o`${d}`}`:d}function R(d,e){const t=typeof d=="function"?d(e):d;return Me(t)}function Xt(d,e){if(d.relationship!=="belongsToMany"||!d.through)throw new Error("expandBelongsToManyJoin can only be called on belongsToMany relationships with through configuration");const{table:t,sourceKey:n,targetKey:i,securitySql:s}=d.through,r=[];for(const l of n){const m=l.as||k;r.push(m(l.source,l.target))}const a=[];for(const l of i){const m=l.as||k;a.push(m(l.source,l.target))}let u;if(s){const l=s(e);u=Array.isArray(l)?l:[l]}const c=Fe("belongsToMany",d.sqlJoinType);return{junctionJoins:[{joinType:c,table:t,condition:A(...r)},{joinType:c,table:t,condition:A(...a)}],junctionSecurityConditions:u}}function fe(d){if("and"in d)return`and:[${d.and.map(fe).sort().join(",")}]`;if("or"in d)return`or:[${d.or.map(fe).sort().join(",")}]`;const e=d,t=JSON.stringify(Array.isArray(e.values)?[...e.values].sort():e.values),n=e.dateRange?`:dr:${JSON.stringify(e.dateRange)}`:"";return`${e.member}:${e.operator}:${t}${n}`}function ct(d,e){return`timeDim:${d}:${JSON.stringify(e)}`}class ne{cache=new Map;stats={hits:0,misses:0};getOrBuild(e,t){const n=this.cache.get(e);if(n!==void 0)return this.stats.hits++,n;const i=t();return i&&this.cache.set(e,i),this.stats.misses++,i}has(e){return this.cache.has(e)}get(e){const t=this.cache.get(e);return t!==void 0&&this.stats.hits++,t}preload(e){for(const{key:t,sql:n}of e)this.cache.has(t)||this.cache.set(t,n)}set(e,t){this.cache.set(e,t)}getStats(){return{...this.stats,cacheSize:this.cache.size}}clear(){this.cache.clear(),this.stats={hits:0,misses:0}}}function Oe(d){const e=[];for(const t of d)"and"in t&&t.and?e.push(...Oe(t.and)):"or"in t&&t.or?e.push(...Oe(t.or)):"member"in t&&e.push(t);return e}function Zt(d,e,t={}){const n=t.keyPrefix??"drizzle-cube:",i=en(d),s=He(JSON.stringify(i));let r=`${n}query:${s}`;if(t.includeSecurityContext!==!1){const a=t.securityContextSerializer?t.securityContextSerializer(e):JSON.stringify(pe(e)),u=He(a);r+=`:ctx:${u}`}return r}function en(d){return{measures:d.measures?[...d.measures].sort():void 0,dimensions:d.dimensions?[...d.dimensions].sort():void 0,filters:d.filters?W(d.filters):void 0,timeDimensions:d.timeDimensions?rn(d.timeDimensions):void 0,limit:d.limit,offset:d.offset,order:d.order?pe(d.order):void 0,fillMissingDatesValue:d.fillMissingDatesValue,funnel:d.funnel?tn(d.funnel):void 0,flow:d.flow?nn(d.flow):void 0,retention:d.retention?sn(d.retention):void 0}}function tn(d){return{bindingKey:d.bindingKey,timeDimension:d.timeDimension,steps:d.steps.map(e=>{const t={name:e.name,filter:e.filter?Array.isArray(e.filter)?W(e.filter):W([e.filter])[0]:void 0,timeToConvert:e.timeToConvert};return"cube"in e&&e.cube&&(t.cube=e.cube),t}),includeTimeMetrics:d.includeTimeMetrics,globalTimeWindow:d.globalTimeWindow}}function nn(d){return{bindingKey:d.bindingKey,timeDimension:d.timeDimension,eventDimension:d.eventDimension,startingStep:{name:d.startingStep.name,filter:d.startingStep.filter?Array.isArray(d.startingStep.filter)?W(d.startingStep.filter):W([d.startingStep.filter])[0]:void 0},stepsBefore:d.stepsBefore,stepsAfter:d.stepsAfter,entityLimit:d.entityLimit,outputMode:d.outputMode,joinStrategy:d.joinStrategy}}function sn(d){return{timeDimension:d.timeDimension,bindingKey:d.bindingKey,dateRange:d.dateRange,granularity:d.granularity,periods:d.periods,retentionType:d.retentionType,cohortFilters:d.cohortFilters?Array.isArray(d.cohortFilters)?W(d.cohortFilters):W([d.cohortFilters])[0]:void 0,activityFilters:d.activityFilters?Array.isArray(d.activityFilters)?W(d.activityFilters):W([d.activityFilters])[0]:void 0,breakdownDimensions:d.breakdownDimensions}}function W(d){return[...d].map(e=>{if("and"in e&&e.and)return{and:W(e.and)};if("or"in e&&e.or)return{or:W(e.or)};const t=e;return{...t,values:t.values?[...t.values].sort():t.values}}).sort((e,t)=>JSON.stringify(e).localeCompare(JSON.stringify(t)))}function rn(d){return[...d].map(e=>({dimension:e.dimension,granularity:e.granularity,dateRange:e.dateRange,fillMissingDates:e.fillMissingDates,compareDateRange:e.compareDateRange?[...e.compareDateRange].sort((t,n)=>{const i=Array.isArray(t)?t.join("-"):t,s=Array.isArray(n)?n.join("-"):n;return i.localeCompare(s)}):void 0})).sort((e,t)=>e.dimension.localeCompare(t.dimension))}function pe(d){return d===null||typeof d!="object"?d:Array.isArray(d)?d.map(pe):Object.keys(d).sort().reduce((e,t)=>(e[t]=pe(d[t]),e),{})}function He(d){let e=2166136261;for(let t=0;t<d.length;t++)e^=d.charCodeAt(t),e=e*16777619>>>0;return e.toString(16).padStart(8,"0")}class re{constructor(e){this.databaseAdapter=e}buildTimeDimensionExpression(e,t,n){const i=R(e,n);return t?this.databaseAdapter.buildTimeDimension(t,i):i instanceof O?i:o`${i}`}buildDateRangeCondition(e,t){if(!t)return null;if(Array.isArray(t)&&t.length>=2){const n=this.normalizeDate(t[0]);let i=this.normalizeDate(t[1]);if(!n||!i)return null;if(typeof t[1]=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t[1].trim())){const s=typeof i=="number"?new Date(i*(this.databaseAdapter.getEngineType()==="sqlite"?1e3:1)):new Date(i),r=new Date(s);r.setUTCHours(23,59,59,999),this.databaseAdapter.isTimestampInteger()?i=this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(r.getTime()/1e3):r.getTime():i=r.toISOString()}return A(ee(e,n),te(e,i))}if(typeof t=="string"){const n=this.parseRelativeDateRange(t);if(n){let l,m;return this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?(l=Math.floor(n.start.getTime()/1e3),m=Math.floor(n.end.getTime()/1e3)):(l=n.start.getTime(),m=n.end.getTime()):(l=n.start.toISOString(),m=n.end.toISOString()),A(ee(e,l),te(e,m))}const i=this.normalizeDate(t);if(!i)return null;const s=typeof i=="number"?new Date(i*(this.databaseAdapter.getEngineType()==="sqlite"?1e3:1)):new Date(i),r=new Date(s);r.setUTCHours(0,0,0,0);const a=new Date(s);a.setUTCHours(23,59,59,999);let u,c;return this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?(u=Math.floor(r.getTime()/1e3),c=Math.floor(a.getTime()/1e3)):(u=r.getTime(),c=a.getTime()):(u=r.toISOString(),c=a.toISOString()),A(ee(e,u),te(e,c))}return null}parseRelativeDateRange(e){const t=new Date,n=e.toLowerCase().trim(),i=t.getUTCFullYear(),s=t.getUTCMonth(),r=t.getUTCDate(),a=t.getUTCDay();if(n==="today"){const p=new Date(t);p.setUTCHours(0,0,0,0);const f=new Date(t);return f.setUTCHours(23,59,59,999),{start:p,end:f}}if(n==="yesterday"){const p=new Date(t);p.setUTCDate(r-1),p.setUTCHours(0,0,0,0);const f=new Date(t);return f.setUTCDate(r-1),f.setUTCHours(23,59,59,999),{start:p,end:f}}if(n==="this week"){const p=a===0?-6:1-a,f=new Date(t);f.setUTCDate(r+p),f.setUTCHours(0,0,0,0);const h=new Date(f);return h.setUTCDate(f.getUTCDate()+6),h.setUTCHours(23,59,59,999),{start:f,end:h}}if(n==="this month"){const p=new Date(Date.UTC(i,s,1,0,0,0,0)),f=new Date(Date.UTC(i,s+1,0,23,59,59,999));return{start:p,end:f}}if(n==="this quarter"){const p=Math.floor(s/3),f=new Date(Date.UTC(i,p*3,1,0,0,0,0)),h=new Date(Date.UTC(i,p*3+3,0,23,59,59,999));return{start:f,end:h}}if(n==="this year"){const p=new Date(Date.UTC(i,0,1,0,0,0,0)),f=new Date(Date.UTC(i,11,31,23,59,59,999));return{start:p,end:f}}const u=n.match(/^last\s+(\d+)\s+days?$/);if(u){const p=parseInt(u[1],10),f=new Date(t);f.setUTCDate(r-p+1),f.setUTCHours(0,0,0,0);const h=new Date(t);return h.setUTCHours(23,59,59,999),{start:f,end:h}}const c=n.match(/^last\s+(\d+)\s+weeks?$/);if(c){const f=parseInt(c[1],10)*7,h=new Date(t);h.setUTCDate(r-f+1),h.setUTCHours(0,0,0,0);const g=new Date(t);return g.setUTCHours(23,59,59,999),{start:h,end:g}}if(n==="last week"){const p=a===0?-13:-6-a,f=new Date(t);f.setUTCDate(r+p),f.setUTCHours(0,0,0,0);const h=new Date(f);return h.setUTCDate(f.getUTCDate()+6),h.setUTCHours(23,59,59,999),{start:f,end:h}}if(n==="last month"){const p=new Date(Date.UTC(i,s-1,1,0,0,0,0)),f=new Date(Date.UTC(i,s,0,23,59,59,999));return{start:p,end:f}}if(n==="last quarter"){const p=Math.floor(s/3),f=p===0?3:p-1,h=p===0?i-1:i,g=new Date(Date.UTC(h,f*3,1,0,0,0,0)),y=new Date(Date.UTC(h,f*3+3,0,23,59,59,999));return{start:g,end:y}}if(n==="last year"){const p=new Date(Date.UTC(i-1,0,1,0,0,0,0)),f=new Date(Date.UTC(i-1,11,31,23,59,59,999));return{start:p,end:f}}if(n==="last 12 months"){const p=new Date(Date.UTC(i,s-11,1,0,0,0,0)),f=new Date(t);return f.setUTCHours(23,59,59,999),{start:p,end:f}}const l=n.match(/^last\s+(\d+)\s+months?$/);if(l){const p=parseInt(l[1],10),f=new Date(Date.UTC(i,s-p+1,1,0,0,0,0)),h=new Date(t);return h.setUTCHours(23,59,59,999),{start:f,end:h}}const m=n.match(/^last\s+(\d+)\s+years?$/);if(m){const p=parseInt(m[1],10),f=new Date(Date.UTC(i-p,0,1,0,0,0,0)),h=new Date(t);return h.setUTCHours(23,59,59,999),{start:f,end:h}}return null}normalizeDate(e){if(!e)return null;if(e instanceof Date)return isNaN(e.getTime())?null:this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(e.getTime()/1e3):e.getTime():e.toISOString();if(typeof e=="number"){const n=e<1e10?e*1e3:e,i=new Date(n);return isNaN(i.getTime())?null:this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(n/1e3):n:i.toISOString()}if(typeof e=="string"){if(/^\d{4}-\d{2}-\d{2}$/.test(e.trim())){const i=new Date(e+"T00:00:00Z");return isNaN(i.getTime())?null:this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(i.getTime()/1e3):i.getTime():i.toISOString()}const n=new Date(e);return isNaN(n.getTime())?null:this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(n.getTime()/1e3):n.getTime():n.toISOString()}const t=new Date(e);return isNaN(t.getTime())?null:this.databaseAdapter.isTimestampInteger()?this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(t.getTime()/1e3):t.getTime():t.toISOString()}}class be{constructor(e,t){this.databaseAdapter=e,this.dateTimeBuilder=t}buildFilterCondition(e,t,n,i,s){if(s!==void 0){if(t!=="inDateRange")throw new Error(`dateRange can only be used with 'inDateRange' operator, but got '${t}'. Use explicit date values in the 'values' array for other date operators.`);if(i&&i.type!=="time")throw new Error(`dateRange can only be used on time dimensions, but field '${i.name||"unknown"}' has type '${i.type}'`);return this.dateTimeBuilder.buildDateRangeCondition(e,s)}if(!n||n.length===0)return t==="equals"?this.databaseAdapter.buildBooleanLiteral(!1):null;const r=n.filter(u=>!(u==null||u===""||typeof u=="string"&&u.includes("\0"))).map(this.databaseAdapter.convertFilterValue);if(r.length===0&&!["set","notSet"].includes(t))return t==="equals"?this.databaseAdapter.buildBooleanLiteral(!1):null;const a=r[0];switch(t){case"equals":if(r.length>1){if(i?.type==="time"){const u=r.map(c=>this.dateTimeBuilder.normalizeDate(c)||c);return De(e,u)}return De(e,r)}else if(r.length===1){const u=i?.type==="time"&&this.dateTimeBuilder.normalizeDate(a)||a;return k(e,u)}return this.databaseAdapter.buildBooleanLiteral(!1);case"notEquals":return r.length>1?Ke(e,r):r.length===1?Qe(e,a):null;case"contains":return this.databaseAdapter.buildStringCondition(e,"contains",a);case"notContains":return this.databaseAdapter.buildStringCondition(e,"notContains",a);case"startsWith":return this.databaseAdapter.buildStringCondition(e,"startsWith",a);case"endsWith":return this.databaseAdapter.buildStringCondition(e,"endsWith",a);case"gt":return Ee(e,a);case"gte":return ee(e,a);case"lt":return Se(e,a);case"lte":return te(e,a);case"set":return Je(e);case"notSet":return We(e);case"inDateRange":if(r.length>=2){const u=this.dateTimeBuilder.normalizeDate(r[0]);let c=this.dateTimeBuilder.normalizeDate(r[1]);if(u&&c){const l=n[1];if(typeof l=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(l.trim())){const m=typeof c=="number"?new Date(c*(this.databaseAdapter.getEngineType()==="sqlite"?1e3:1)):new Date(c),p=new Date(m);p.setUTCHours(23,59,59,999),this.databaseAdapter.isTimestampInteger()?c=this.databaseAdapter.getEngineType()==="sqlite"?Math.floor(p.getTime()/1e3):p.getTime():c=p.toISOString()}return A(ee(e,u),te(e,c))}}return null;case"beforeDate":{const u=this.dateTimeBuilder.normalizeDate(a);return u?Se(e,u):null}case"afterDate":{const u=this.dateTimeBuilder.normalizeDate(a);return u?Ee(e,u):null}case"between":return r.length>=2?A(ee(e,r[0]),te(e,r[1])):null;case"notBetween":return r.length>=2?oe(Se(e,r[0]),Ee(e,r[1])):null;case"in":return r.length>0?De(e,r):null;case"notIn":return r.length>0?Ke(e,r):null;case"like":return this.databaseAdapter.buildStringCondition(e,"like",a);case"notLike":return this.databaseAdapter.buildStringCondition(e,"notLike",a);case"ilike":return this.databaseAdapter.buildStringCondition(e,"ilike",a);case"regex":return this.databaseAdapter.buildStringCondition(e,"regex",a);case"notRegex":return this.databaseAdapter.buildStringCondition(e,"notRegex",a);case"isEmpty":return oe(We(e),k(e,""));case"isNotEmpty":return A(Je(e),Qe(e,""));case"arrayContains":return this.databaseAdapter.getEngineType()==="postgres"?Nt(e,r):null;case"arrayOverlaps":return this.databaseAdapter.getEngineType()==="postgres"?_t(e,r):null;case"arrayContained":return this.databaseAdapter.getEngineType()==="postgres"?At(e,r):null;default:return null}}buildLogicalFilter(e,t,n){if("and"in e&&e.and){const i=e.and.map(s=>this.buildSingleFilter(s,t,n)).filter(s=>s!==null);return i.length>0?i.length===1?i[0]:A(...i):null}if("or"in e&&e.or){const i=e.or.map(s=>this.buildSingleFilter(s,t,n)).filter(s=>s!==null);return i.length>0?i.length===1?i[0]:oe(...i):null}return null}buildSingleFilter(e,t,n){if("and"in e||"or"in e)return this.buildLogicalFilter(e,t,n);const i=e,[s,r]=i.member.split("."),a=t.get(s);if(!a)return null;const u=a.dimensions?.[r];if(!u)return null;const c=u.type==="time"?R(u.sql,n):typeof u.sql=="function"?u.sql(n):u.sql;return this.buildFilterCondition(c,i.operator,i.values,u,i.dateRange)}}class X{dependencyGraph;cubes;constructor(e){this.cubes=e instanceof Map?e:new Map([[e.name,e]]),this.dependencyGraph=new Map}extractDependencies(e){const t=/\{([^}]+)\}/g,n=e.matchAll(t),i=[];for(const s of n){const r=s[1].trim();if(r.includes(".")){const[a,u]=r.split(".");i.push({measureName:r,cubeName:a.trim(),fieldName:u.trim()})}else i.push({measureName:r,cubeName:null,fieldName:r})}return i}buildGraph(e){for(const[t,n]of Object.entries(e.measures))if(n.type==="calculated"&&n.calculatedSql){const i=`${e.name}.${t}`,s=this.extractDependencies(n.calculatedSql),r=new Set;for(const a of s){const c=`${a.cubeName||e.name}.${a.fieldName}`;r.add(c)}this.dependencyGraph.set(i,{id:i,dependencies:r,inDegree:0})}this.calculateInDegrees()}buildGraphForMultipleCubes(e){for(const t of e.values())this.buildGraph(t)}calculateInDegrees(){for(const e of this.dependencyGraph.values())e.inDegree=0;for(const e of this.dependencyGraph.values())for(const t of e.dependencies){const n=this.dependencyGraph.get(t);n&&n.inDegree++}}topologicalSort(e){const t=new Map,n=[],i=[];for(const s of e){const r=this.dependencyGraph.get(s);r&&t.set(s,{id:r.id,dependencies:new Set(r.dependencies),inDegree:0})}for(const s of t.values()){let r=0;for(const a of s.dependencies)t.has(a)&&r++;s.inDegree=r}for(const[s,r]of t)r.inDegree===0&&n.push(s);for(;n.length>0;){const s=n.shift();i.push(s);for(const[r,a]of t)a.dependencies.has(s)&&(a.inDegree--,a.inDegree===0&&n.push(r))}if(i.length<t.size){const s=this.detectCycle();throw new Error(`Circular dependency detected in calculated measures: ${s?s.join(" -> "):"unknown cycle"}`)}return i}detectCycle(){const e=new Set,t=new Set,n=[];for(const i of this.dependencyGraph.keys())if(!e.has(i)){const s=this.dfs(i,e,t,n);if(s)return s}return null}dfs(e,t,n,i){t.add(e),n.add(e),i.push(e);const s=this.dependencyGraph.get(e);if(!s)return i.pop(),n.delete(e),null;for(const r of s.dependencies)if(t.has(r)){if(n.has(r)){const a=i.indexOf(r);return[...i.slice(a),r]}}else{const a=this.dfs(r,t,n,i);if(a)return a}return i.pop(),n.delete(e),null}getAllDependencies(e){const t=new Set,n=new Set,i=s=>{if(n.has(s))return;n.add(s);const r=this.dependencyGraph.get(s);if(r)for(const a of r.dependencies)t.add(a),i(a)};return i(e),t}validateDependencies(e){for(const[t,n]of Object.entries(e.measures))if(n.type==="calculated"&&n.calculatedSql){const i=this.extractDependencies(n.calculatedSql);for(const s of i){const r=s.cubeName||e.name,a=this.cubes.get(r);if(!a)throw new Error(`Calculated measure '${e.name}.${t}' references unknown cube '${r}'`);if(!a.measures[s.fieldName])throw new Error(`Calculated measure '${e.name}.${t}' references unknown measure '${s.measureName}'`);if(r===e.name&&s.fieldName===t)throw new Error(`Calculated measure '${e.name}.${t}' cannot reference itself`)}}}populateDependencies(e){for(const[,t]of Object.entries(e.measures))if(t.type==="calculated"&&t.calculatedSql&&!t.dependencies){const n=this.extractDependencies(t.calculatedSql);t.dependencies=n.map(i=>i.measureName)}}static isCalculatedMeasure(e){return e.type==="calculated"&&!!e.calculatedSql}}function on(d,e){const{cube:t,allCubes:n,resolvedMeasures:i}=e,s=je(d),r=new Map;for(const m of s){const{originalRef:p,cubeName:f,fieldName:h}=m,g=f||t.name;if(!n.get(g))throw new Error(`Cannot substitute {${p}}: cube '${g}' not found`);const b=`${g}.${h}`,w=i.get(b);if(!w)throw new Error(`Cannot substitute {${p}}: measure '${b}' not resolved yet. Ensure measures are resolved in dependency order.`);const T=w(),S=o`${T}`;r.set(p,S)}const a=[],u=[];let c=0;for(const m of s){const p=`{${m.originalRef}}`,f=d.indexOf(p,c);if(f>=0){a.push(d.substring(c,f));const h=r.get(m.originalRef);h&&u.push(h),c=f+p.length}}if(a.push(d.substring(c)),u.length===0)return o.raw(d);const l=[];for(let m=0;m<a.length;m++)a[m]&&l.push(new P(a[m])),m<u.length&&l.push(u[m]);return o.join(l,o.raw(""))}function je(d){const e=/\{([^}]+)\}/g,t=d.matchAll(e),n=[];for(const i of t){const s=i[1].trim();if(s.includes(".")){const[r,a]=s.split(".").map(u=>u.trim());n.push({originalRef:s,cubeName:r,fieldName:a})}else n.push({originalRef:s,cubeName:null,fieldName:s})}return n}function an(d){const e=[];let t=0;for(let r=0;r<d.length;r++)if(d[r]==="{")t++;else if(d[r]==="}"&&(t--,t<0)){e.push(`Unmatched closing brace at position ${r}`);break}t>0&&e.push("Unmatched opening brace in template"),/\{\s*\}/.test(d)&&e.push("Empty member reference {} found in template"),/\{[^}]*\{/.test(d)&&e.push("Nested braces are not allowed in member references");const s=je(d);for(const r of s){const a=r.cubeName?`${r.cubeName}.${r.fieldName}`:r.fieldName;/^[a-zA-Z_][a-zA-Z0-9_.]*$/.test(a)||e.push(`Invalid member reference {${r.originalRef}}: must start with letter or underscore, and contain only letters, numbers, underscores, and dots`),a.split(".").length>2&&e.push(`Invalid member reference {${r.originalRef}}: only one dot allowed (Cube.measure format)`)}return{isValid:e.length===0,errors:e}}function Ae(d,e){const t=je(d),n=new Set;for(const i of t){const r=`${i.cubeName||e}.${i.fieldName}`;n.add(r)}return Array.from(n)}class j{constructor(e){this.databaseAdapter=e}buildResolvedMeasures(e,t,n,i){const s=new Map,r=[],a=[],u=new Set(e),c=new X(t);for(const l of t.values())c.buildGraph(l);for(const l of e){const[m,p]=l.split("."),f=t.get(m);if(f&&f.measures&&f.measures[p]){const h=f.measures[p];if(j.isPostAggregationWindow(h)){const g=j.getWindowBaseMeasure(h,m);g&&u.add(g);continue}X.isCalculatedMeasure(h)?(a.push(l),Ae(h.calculatedSql,m).forEach(b=>u.add(b)),c.getAllDependencies(l).forEach(b=>{const[w,T]=b.split("."),S=t.get(w);if(S&&S.measures[T]){const C=S.measures[T];X.isCalculatedMeasure(C)&&Ae(C.calculatedSql,w).forEach(D=>u.add(D))}})):r.push(l)}}for(const l of u){const[m,p]=l.split("."),f=t.get(m);if(f&&f.measures&&f.measures[p]){const h=f.measures[p];if(j.isPostAggregationWindow(h))continue;X.isCalculatedMeasure(h)?a.includes(l)||a.push(l):r.includes(l)||r.push(l)}}for(const l of r){const[m,p]=l.split("."),f=t.get(m),h=f.measures[p];if(i){const g=i(l,h,f);s.set(l,()=>g)}else s.set(l,()=>this.buildMeasureExpression(h,n,f))}if(a.length>0){const l=c.topologicalSort(a);for(const m of l){const[p,f]=m.split("."),h=t.get(p),g=h.measures[f];s.set(m,()=>this.buildCalculatedMeasure(g,h,t,s,n))}}return s}buildCalculatedMeasure(e,t,n,i,s){if(!e.calculatedSql)throw new Error(`Calculated measure '${t.name}.${e.name}' missing calculatedSql property`);const r=this.databaseAdapter.preprocessCalculatedTemplate(e.calculatedSql);return on(r,{cube:t,allCubes:n,resolvedMeasures:i})}buildCTECalculatedMeasure(e,t,n,i,s){if(!e.calculatedSql)throw new Error(`Calculated measure '${t.name}.${e.name||"unknown"}' missing calculatedSql property`);const r=new Map,a=Ae(e.calculatedSql,t.name);for(const u of a){const[c,l]=u.split("."),m=i.get(c);if(m&&m.measures[l]){const p=m.measures[l];if(n.measures.includes(u)){const f=o`${o.identifier(n.cteAlias)}.${o.identifier(l)}`;let h;switch(p.type){case"count":case"countDistinct":case"sum":h=V(f);break;case"avg":h=this.databaseAdapter.buildAvg(f);break;case"min":h=ae(f);break;case"max":h=H(f);break;case"number":h=V(f);break;default:h=V(f)}r.set(u,()=>h)}}}return this.buildCalculatedMeasure(e,t,i,r,s)}buildHavingMeasureExpression(e,t,n,i,s){if(s&&s.preAggregationCTEs){const r=s.preAggregationCTEs.find(a=>a.cube.name===e);if(r&&r.measures.includes(`${e}.${t}`))if(n.type==="calculated"&&n.calculatedSql){const a=s.primaryCube.name===e?s.primaryCube:s.joinCubes?.find(c=>c.cube.name===e)?.cube;if(!a)throw new Error(`Cube ${e} not found in query plan`);const u=new Map([[s.primaryCube.name,s.primaryCube]]);if(s.joinCubes)for(const c of s.joinCubes)u.set(c.cube.name,c.cube);return this.buildCTECalculatedMeasure(n,a,r,u,i)}else{const a=o`${o.identifier(r.cteAlias)}.${o.identifier(t)}`;switch(n.type){case"count":case"countDistinct":case"sum":return V(a);case"avg":return this.databaseAdapter.buildAvg(a);case"min":return ae(a);case"max":return H(a);case"number":return V(a);default:return V(a)}}}return this.buildMeasureExpression(n,i)}buildMeasureExpression(e,t,n){if(e.type==="calculated")throw new Error(`Cannot build calculated measure '${e.name}' directly. Use buildCalculatedMeasure instead.`);if(j.isPostAggregationWindow(e))throw new Error(`Post-aggregation window measure '${e.name}' should be built via buildPostAggregationWindowExpression, not buildMeasureExpression.`);if(!e.sql)throw new Error(`Measure '${e.name}' of type '${e.type}' is missing required 'sql' property. Only calculated measures and post-aggregation window functions can omit 'sql'.`);let i=R(e.sql,t);if(e.filters&&e.filters.length>0){const s=e.filters.map(r=>{const a=r(t);return a?o`(${a})`:void 0}).filter(Boolean);if(s.length>0){const r=s.length===1?s[0]:A(...s);i=this.databaseAdapter.buildCaseWhen([{when:r,then:i}])}}switch(e.type){case"count":return Re(i);case"countDistinct":return Rt(i);case"sum":return V(i);case"avg":return this.databaseAdapter.buildAvg(i);case"min":return ae(i);case"max":return H(i);case"number":return i;case"stddev":case"stddevSamp":{const s=e.type==="stddevSamp"||e.statisticalConfig?.useSample,r=this.databaseAdapter.buildStddev(i,s);return r===null?(console.warn(`[drizzle-cube] ${e.type} not supported on ${this.databaseAdapter.getEngineType()}, returning NULL`),o`MAX(NULL)`):r}case"variance":case"varianceSamp":{const s=e.type==="varianceSamp"||e.statisticalConfig?.useSample,r=this.databaseAdapter.buildVariance(i,s);return r===null?(console.warn(`[drizzle-cube] ${e.type} not supported on ${this.databaseAdapter.getEngineType()}, returning NULL`),o`MAX(NULL)`):r}case"percentile":case"median":case"p95":case"p99":{let s;switch(e.type){case"median":s=50;break;case"p95":s=95;break;case"p99":s=99;break;default:s=e.statisticalConfig?.percentile??50}const r=this.databaseAdapter.buildPercentile(i,s);return r===null?(console.warn(`[drizzle-cube] ${e.type} not supported on ${this.databaseAdapter.getEngineType()}, returning NULL`),o`MAX(NULL)`):r}case"lag":case"lead":case"rank":case"denseRank":case"rowNumber":case"ntile":case"firstValue":case"lastValue":case"movingAvg":case"movingSum":{const s=e.windowConfig||{};let r;if(s.partitionBy&&s.partitionBy.length>0&&n){const c=s.partitionBy.map(l=>{const m=l.includes(".")?l.split(".")[1]:l,p=n.dimensions?.[m];return p?R(p.sql,t):(console.warn(`[drizzle-cube] Window function partition dimension '${l}' not found in cube '${n.name}'`),null)}).filter(l=>l!==null);c.length>0&&(r=c)}let a;if(s.orderBy&&s.orderBy.length>0&&n){const c=s.orderBy.map(l=>{const m=l.field.includes(".")?l.field.split(".")[1]:l.field,p=n.dimensions?.[m];if(p)return{field:R(p.sql,t),direction:l.direction};const f=n.measures?.[m];return f&&f.sql?{field:R(f.sql,t),direction:l.direction}:(console.warn(`[drizzle-cube] Window function order field '${l.field}' not found in cube '${n.name}'`),null)}).filter(l=>l!==null);c.length>0&&(a=c)}const u=this.databaseAdapter.buildWindowFunction(e.type,["rank","denseRank","rowNumber"].includes(e.type)?null:i,r,a,{offset:s.offset,defaultValue:s.defaultValue,nTile:s.nTile,frame:s.frame});return u===null?(console.warn(`[drizzle-cube] ${e.type} not supported on ${this.databaseAdapter.getEngineType()}, returning NULL`),o`NULL`):u}default:return Re(i)}}static WINDOW_FUNCTION_TYPES=["lag","lead","rank","denseRank","rowNumber","ntile","firstValue","lastValue","movingAvg","movingSum"];static isWindowFunction(e){return j.WINDOW_FUNCTION_TYPES.includes(e)}static categorizeMeasures(e,t){const n=[],i=[];for(const s of e){const[r,a]=s.split("."),u=t.get(r);if(u?.measures?.[a]){const c=u.measures[a];j.isWindowFunction(c.type)?n.push(s):i.push(s)}}return{windowMeasures:n,aggregateMeasures:i}}static hasWindowFunctions(e,t){const{windowMeasures:n}=j.categorizeMeasures(e,t);return n.length>0}static isPostAggregationWindow(e){return j.isWindowFunction(e.type)&&e.windowConfig?.measure!==void 0}static getWindowBaseMeasure(e,t){if(!e.windowConfig?.measure)return null;const n=e.windowConfig.measure;return n.includes(".")?n:`${t}.${n}`}static getDefaultWindowOperation(e){switch(e){case"lag":case"lead":return"difference";default:return"raw"}}static categorizeForPostAggregation(e,t){const n=[],i=[],s=new Set;for(const r of e){const[a,u]=r.split("."),c=t.get(a);if(c?.measures?.[u]){const l=c.measures[u];if(j.isPostAggregationWindow(l)){i.push(r);const m=j.getWindowBaseMeasure(l,a);m&&s.add(m)}else j.isWindowFunction(l.type)||n.push(r)}}return{aggregateMeasures:n,postAggWindowMeasures:i,requiredBaseMeasures:s}}static hasPostAggregationWindows(e,t){const{postAggWindowMeasures:n}=j.categorizeForPostAggregation(e,t);return n.length>0}}class un{constructor(e){this.dateTimeBuilder=e}isWindowFunctionType(e){return["lag","lead","rank","denseRank","rowNumber","ntile","firstValue","lastValue","movingAvg","movingSum"].includes(e)}isAggregateFunctionType(e){return["count","countDistinct","sum","avg","min","max","stddev","stddevSamp","variance","varianceSamp","median","p95","p99","percentile","number"].includes(e)}buildGroupByFields(e,t,n,i){const s=[],r=e instanceof Map?e:new Map([[e.name,e]]),a=t.dimensions&&t.dimensions.length>0||t.timeDimensions&&t.timeDimensions.length>0,u=t.measures&&t.measures.length>0,c=a&&!u;let l=!1;for(const m of t.measures||[]){const[p,f]=m.split("."),h=r.get(p);if(h&&h.measures&&h.measures[f]){const g=h.measures[f];if(this.isAggregateFunctionType(g.type)||g.type==="calculated"){l=!0;break}if(j.isPostAggregationWindow(g)){const y=j.getWindowBaseMeasure(g,p);if(y){const[b,w]=y.split("."),S=r.get(b)?.measures?.[w];if(S&&this.isAggregateFunctionType(S.type)){l=!0;break}}}}}if(!l&&!c)return[];if(t.dimensions)for(const m of t.dimensions){const[p,f]=m.split("."),h=r.get(p);if(h&&h.dimensions&&h.dimensions[f]){const g=i?.preAggregationCTEs?.find(y=>y.cube.name===p);if(g){const y=g.joinKeys.find(b=>b.targetColumn===f);if(y&&y.sourceColumnObj)s.push(y.sourceColumnObj);else{const b=o`${o.identifier(g.cteAlias)}.${o.identifier(f)}`;s.push(b)}}else{const y=h.dimensions[f],b=R(y.sql,n);s.push(b)}}}if(t.timeDimensions)for(const m of t.timeDimensions){const[p,f]=m.dimension.split("."),h=r.get(p);if(h&&h.dimensions&&h.dimensions[f]){const g=i?.preAggregationCTEs?.find(y=>y.cube.name===p);if(g){const y=g.joinKeys.find(b=>b.targetColumn===f);if(y&&y.sourceColumnObj){const b=this.dateTimeBuilder.buildTimeDimensionExpression(y.sourceColumnObj,m.granularity,n);s.push(b)}else{const b=o`${o.identifier(g.cteAlias)}.${o.identifier(f)}`;s.push(b)}}else{const y=h.dimensions[f],b=this.dateTimeBuilder.buildTimeDimensionExpression(y.sql,m.granularity,n);s.push(b)}}}return s}}class ln{dateTimeBuilder;filterBuilder;groupByBuilder;measureBuilder;constructor(e){this.dateTimeBuilder=new re(e),this.filterBuilder=new be(e,this.dateTimeBuilder),this.groupByBuilder=new un(this.dateTimeBuilder),this.measureBuilder=new j(e)}buildResolvedMeasures(e,t,n,i){return this.measureBuilder.buildResolvedMeasures(e,t,n,i)}buildSelections(e,t,n){const i={},s=e instanceof Map?e:new Map([[e.name,e]]);if(t.dimensions)for(const r of t.dimensions){const[a,u]=r.split("."),c=s.get(a);if(c&&c.dimensions&&c.dimensions[u]){const l=c.dimensions[u],m=R(l.sql,n);i[r]=o`${m}`.as(r)}}if(t.measures){const r=this.buildResolvedMeasures(t.measures,s,n);for(const a of t.measures){const u=r.get(a);if(u){const c=u();i[a]=o`${c}`.as(a)}}}if(t.timeDimensions)for(const r of t.timeDimensions){const[a,u]=r.dimension.split("."),c=s.get(a);if(c&&c.dimensions&&c.dimensions[u]){const l=c.dimensions[u],m=this.buildTimeDimensionExpression(l.sql,r.granularity,n);i[r.dimension]=o`${m}`.as(r.dimension)}}return Object.keys(i).length===0&&(i.count=Re()),i}buildCalculatedMeasure(e,t,n,i,s){return this.measureBuilder.buildCalculatedMeasure(e,t,n,i,s)}buildCTECalculatedMeasure(e,t,n,i,s){return this.measureBuilder.buildCTECalculatedMeasure(e,t,n,i,s)}buildHavingMeasureExpression(e,t,n,i,s){return this.measureBuilder.buildHavingMeasureExpression(e,t,n,i,s)}buildMeasureExpression(e,t,n){return this.measureBuilder.buildMeasureExpression(e,t,n)}buildTimeDimensionExpression(e,t,n){return this.dateTimeBuilder.buildTimeDimensionExpression(e,t,n)}buildWhereConditions(e,t,n,i,s){const r=[],a=e instanceof Map?e:new Map([[e.name,e]]),u=new Set;if(t.filters&&t.filters.length>0)for(const c of t.filters){if(s&&"member"in c){const[m]=c.member.split(".");if(a.has(m)&&s.has(m)&&!u.has(m)){const f=s.get(m);r.push(...f),u.add(m);continue}else if(u.has(m))continue}const l=this.processFilter(c,a,n,"where",i);l&&r.push(l)}if(t.timeDimensions)for(const c of t.timeDimensions){const[l,m]=c.dimension.split("."),p=a.get(l);if(p&&p.dimensions[m]&&c.dateRange){if(i?.preAggregationCTEs&&i.preAggregationCTEs.some(b=>b.cube.name===l))continue;if(n.filterCache){const y=ct(c.dimension,c.dateRange),b=n.filterCache.get(y);if(b){r.push(b);continue}}const f=p.dimensions[m],h=R(f.sql,n),g=this.buildDateRangeCondition(h,c.dateRange);g&&r.push(g)}}return r}buildHavingConditions(e,t,n,i){const s=[],r=e instanceof Map?e:new Map([[e.name,e]]);if(t.filters&&t.filters.length>0)for(const a of t.filters){const u=this.processFilter(a,r,n,"having",i);u&&s.push(u)}return s}processFilter(e,t,n,i,s){if("and"in e||"or"in e){const f=e;if(f.and){const h=f.and.map(g=>this.processFilter(g,t,n,i,s)).filter(g=>g!==null);return h.length>0?A(...h):null}if(f.or){const h=f.or.map(g=>this.processFilter(g,t,n,i,s)).filter(g=>g!==null);return h.length>0?oe(...h):null}}const r=e,[a,u]=r.member.split("."),c=t.get(a);if(!c)return null;const l=c.dimensions[u],m=c.measures[u],p=l||m;if(!p)return null;if(i==="where"&&l){if(s?.preAggregationCTEs&&s.preAggregationCTEs.some(y=>y.cube.name===a))return null;const f=l.type==="time";if(n.filterCache){const g=fe(e),y=n.filterCache.get(g);if(y)return y}const h=f?R(l.sql,n):typeof l.sql=="function"?l.sql(n):l.sql;return this.buildFilterCondition(h,r.operator,r.values,p,r.dateRange)}else{if(i==="where"&&m)return null;if(i==="having"&&m){const f=this.buildHavingMeasureExpression(a,u,m,n,s);return this.buildFilterCondition(f,r.operator,r.values,p,r.dateRange)}}return null}buildFilterCondition(e,t,n,i,s){return this.filterBuilder.buildFilterCondition(e,t,n,i,s)}buildDateRangeCondition(e,t){return this.dateTimeBuilder.buildDateRangeCondition(e,t)}buildGroupByFields(e,t,n,i){return this.groupByBuilder.buildGroupByFields(e,t,n,i)}buildOrderBy(e,t){const n=[],i=t||[...e.measures||[],...e.dimensions||[],...e.timeDimensions?.map(s=>s.dimension)||[]];if(e.order&&Object.keys(e.order).length>0)for(const[s,r]of Object.entries(e.order)){if(!i.includes(s))throw new Error(`Cannot order by '${s}': field is not selected in the query`);const a=r==="desc"?vt(o.identifier(s)):ze(o.identifier(s));n.push(a)}if(e.timeDimensions&&e.timeDimensions.length>0){const s=new Set(Object.keys(e.order||{})),r=[...e.timeDimensions].sort((a,u)=>a.dimension.localeCompare(u.dimension));for(const a of r)s.has(a.dimension)||n.push(ze(o.identifier(a.dimension)))}return n}collectNumericFields(e,t){const n=[],i=e instanceof Map?e:new Map([[e.name,e]]);if(t.measures&&n.push(...t.measures),t.dimensions)for(const s of t.dimensions){const[r,a]=s.split("."),u=i.get(r);if(u){const c=u.dimensions[a];c&&c.type==="number"&&n.push(s)}}return n}applyLimitAndOffset(e,t){let n=t.limit;t.offset!==void 0&&t.offset>0&&n===void 0&&(n=50);let i=e;if(n!==void 0){if(n<0)throw new Error("Limit must be non-negative");i=i.limit(n)}if(t.offset!==void 0){if(t.offset<0)throw new Error("Offset must be non-negative");i=i.offset(t.offset)}return i}buildFilterConditionPublic(e,t,n,i,s){return this.buildFilterCondition(e,t,n,i,s)}buildLogicalFilter(e,t,n){return this.filterBuilder.buildLogicalFilter(e,t,n)}}class ue{cubes;connectivityCache=new Map;reverseIndex;constructor(e){this.cubes=e,this.reverseIndex=this.buildReverseIndex()}buildReverseIndex(){const e=new Map;for(const[t,n]of this.cubes)if(n.joins)for(const[,i]of Object.entries(n.joins)){if(i.relationship==="belongsToMany")continue;const r=K(i.targetCube).name;let a=e.get(r);a||(a=[],e.set(r,a)),a.push({definingCube:t,joinDef:i})}return e}findPath(e,t,n=new Set){if(e===t)return[];const i=this.getCacheKey(e,t,n),s=this.getFromCache(i);if(s!==void 0)return s;const r=[{cube:e,path:[]}],a=new Set([e,...n]);for(;r.length>0;){const{cube:u,path:c}=r.shift(),l=this.cubes.get(u);if(l?.joins)for(const[,p]of Object.entries(l.joins)){const h=K(p.targetCube).name;if(a.has(h))continue;const g=[...c,{fromCube:u,toCube:h,joinDef:p}];if(h===t)return this.setInCache(i,g),g;a.add(h),r.push({cube:h,path:g})}const m=this.reverseIndex.get(u)||[];for(const{definingCube:p,joinDef:f}of m){if(a.has(p))continue;const h=[...c,{fromCube:u,toCube:p,joinDef:f,reversed:!0}];if(p===t)return this.setInCache(i,h),h;a.add(p),r.push({cube:p,path:h})}}return this.setInCache(i,null),null}findPathPreferring(e,t,n,i=new Set){return this.findPathPreferringDetailed(e,t,n,i).selectedPath}findPathPreferringDetailed(e,t,n,i=new Set){const s=this.findAllPaths(e,t,new Set);if(s.length===0){const a=this.findPath(e,t,i),u=a?[{path:a,score:0,usesPreferredJoin:!1,preferredCubesInPath:0,usesProcessed:a.some(c=>i.has(c.toCube)),scoreBreakdown:{preferredJoinBonus:0,preferredCubeBonus:0,lengthPenalty:0}}]:[];return{strategy:"fallbackShortest",preferredCubes:Array.from(n).sort(),selectedIndex:a?0:-1,candidates:u,selectedPath:a}}const r=s.map(a=>{let u=0;const c=a.some((h,g)=>g!==0?!1:h.reversed?h.joinDef.preferredFor?.includes(e)??!1:h.joinDef.preferredFor?.includes(t)??!1);c&&(u=10);const l=a.filter(h=>n.has(h.toCube)).length,m=l,p=a.length-1,f=u+m-p;return{path:a,score:f,usesPreferredJoin:c,preferredCubesInPath:l,usesProcessed:a.some(h=>i.has(h.toCube)),scoreBreakdown:{preferredJoinBonus:u,preferredCubeBonus:m,lengthPenalty:p}}});return r.sort((a,u)=>u.score!==a.score?u.score-a.score:a.usesProcessed!==u.usesProcessed?a.usesProcessed?-1:1:a.path.length-u.path.length),{strategy:"preferred",preferredCubes:Array.from(n).sort(),selectedIndex:r.length>0?0:-1,candidates:r,selectedPath:r[0]?.path??null}}findAllPaths(e,t,n,i=4){if(e===t)return[[]];const s=[],r=[{cube:e,path:[],visited:new Set([e,...n])}];for(;r.length>0;){const{cube:a,path:u,visited:c}=r.shift();if(u.length>=i)continue;const l=this.cubes.get(a);if(l?.joins)for(const[,p]of Object.entries(l.joins)){const h=K(p.targetCube).name;if(c.has(h))continue;const g=[...u,{fromCube:a,toCube:h,joinDef:p}];if(h===t)s.push(g);else{const y=new Set(c);y.add(h),r.push({cube:h,path:g,visited:y})}}const m=this.reverseIndex.get(a)||[];for(const{definingCube:p,joinDef:f}of m){if(c.has(p))continue;const h=[...u,{fromCube:a,toCube:p,joinDef:f,reversed:!0}];if(p===t)s.push(h);else{const g=new Set(c);g.add(p),r.push({cube:p,path:h,visited:g})}}}return s}canReachAll(e,t){const n=t.filter(i=>i!==e);for(const i of n){const s=this.findForwardOnlyPath(e,i,new Set);if(!s||s.length===0)return!1}return!0}findForwardOnlyPath(e,t,n){if(e===t)return[];const i=[{cube:e,path:[]}],s=new Set([e,...n]);for(;i.length>0;){const{cube:r,path:a}=i.shift(),u=this.cubes.get(r);if(u?.joins)for(const[,c]of Object.entries(u.joins)){const m=K(c.targetCube).name;if(s.has(m))continue;const p=[...a,{fromCube:r,toCube:m,joinDef:c}];if(m===t)return p;s.add(m),i.push({cube:m,path:p})}}return null}buildJoinCondition(e,t,n){const i=[];for(const s of e.on){const r=t?o`${o.identifier(t)}.${o.identifier(s.source.name)}`:Me(s.source),a=n?o`${o.identifier(n)}.${o.identifier(s.target.name)}`:Me(s.target),u=s.as||k;i.push(u(r,a))}return A(...i)}getReachableCubes(e){const t=new Set([e]),n=[e];for(;n.length>0;){const i=n.shift(),s=this.cubes.get(i);if(s?.joins)for(const[,a]of Object.entries(s.joins)){const c=K(a.targetCube).name;t.has(c)||(t.add(c),n.push(c))}const r=this.reverseIndex.get(i)||[];for(const{definingCube:a}of r)t.has(a)||(t.add(a),n.push(a))}return t}getCacheKey(e,t,n){const i=Array.from(n).sort().join(",");return`${e}:${t}:${i}`}getFromCache(e){const t=this.connectivityCache.get(e);if(t)return t.path}setInCache(e,t){this.connectivityCache.set(e,{path:t})}}class cn{resolverCache=new WeakMap;getResolver(e){let t=this.resolverCache.get(e);return t||(t=new ue(e),this.resolverCache.set(e,t)),t}analyzeCubeUsage(e){const t=new Set;if(e.measures)for(const n of e.measures){const[i]=n.split(".");t.add(i)}if(e.dimensions)for(const n of e.dimensions){const[i]=n.split(".");t.add(i)}if(e.timeDimensions)for(const n of e.timeDimensions){const[i]=n.dimension.split(".");t.add(i)}if(e.filters)for(const n of e.filters)this.extractCubeNamesFromFilter(n,t);if(e.order)for(const n of Object.keys(e.order)){const[i]=n.split(".");i&&t.add(i)}return t}collectPathHintCubes(e){return this.analyzeCubeUsage(e)}extractCubeNamesFromFilter(e,t){if("and"in e||"or"in e){const n=e.and||e.or||[];for(const i of n)this.extractCubeNamesFromFilter(i,t);return}if("member"in e){const[n]=e.member.split(".");n&&t.add(n)}}extractMeasuresFromFilters(e,t){const n=[];if(!e.filters)return n;for(const i of e.filters)this.extractMeasuresFromFilter(i,t,n);return n}extractMeasuresFromFilter(e,t,n){if("and"in e||"or"in e){const i=e.and||e.or||[];for(const s of i)this.extractMeasuresFromFilter(s,t,n);return}if("member"in e){const i=e.member,[s,r]=i.split(".");s===t.name&&t.measures&&t.measures[r]&&n.push(i)}}choosePrimaryCube(e,t,n){return e.length===1?e[0]:n?this.analyzePrimaryCubeSelection(e,t,n).selectedCube:[...e].sort()[0]}analyzePrimaryCube(e,t,n){return this.analyzePrimaryCubeSelection(e,t,n)}analyzeJoinPathForTarget(e,t,n,i){return this.analyzeJoinPath(e,t,n,i)}buildJoinPlanForPrimary(e,t,n,i,s){return this.buildJoinPlan(e,t,n,i,s)}buildPreAggregationCTEs(e,t,n,i,s){return this.planPreAggregationCTEs(e,t,n,i,s)}buildWarnings(e,t){return this.generateWarnings(e,t)}buildJoinPlan(e,t,n,i,s){const r=this.getResolver(e),a=[],u=new Set([t.name]),c=new Set;if(s.measures)for(const f of s.measures){const[h]=f.split(".");c.add(h)}const l=this.collectPathHintCubes(s),m=new Set;for(const f of c){if(f===t.name)continue;this.findHasManyJoinDef(t,f)&&m.add(f)}const p=n.filter(f=>f!==t.name);for(const f of p){if(u.has(f))continue;const h=new Set([...u].filter(y=>!m.has(y))),g=r.findPathPreferring(t.name,f,l,h);if(!g||g.length===0)throw new Error(`No join path found from '${t.name}' to '${f}'`);for(const{fromCube:y,toCube:b,joinDef:w,reversed:T}of g){if(u.has(b))continue;const S=e.get(b);if(!S)throw new Error(`Cube '${b}' not found`);const C=T?Ne(w.relationship):w.relationship;if(C==="belongsToMany"&&w.through){const $=Xt(w,i.securityContext);a.push({cube:S,alias:`${b.toLowerCase()}_cube`,joinType:$.junctionJoins[1].joinType,joinCondition:$.junctionJoins[1].condition,relationship:"belongsToMany",junctionTable:{table:w.through.table,alias:`junction_${b.toLowerCase()}`,joinType:$.junctionJoins[0].joinType,joinCondition:$.junctionJoins[0].condition,securitySql:w.through.securitySql,sourceCubeName:y}})}else{const $=r.buildJoinCondition(w,null,null),D=Fe(C,w.sqlJoinType);a.push({cube:S,alias:`${b.toLowerCase()}_cube`,joinType:D,joinCondition:$,relationship:C})}u.add(b)}}return a}planPreAggregationCTEs(e,t,n,i,s){const r=[];if(!i.measures||i.measures.length===0)return r;const a=this.computeCTEReasons(t,n,i);if(a.size===0)return r;for(const u of n){const c=a.get(u.cube.name);if(!c)continue;const l=u.cube,m=u.alias,p=i.measures.filter(D=>D.startsWith(l.name+".")),f=this.extractMeasuresFromFilters(i,l),h=[...new Set([...p,...f])];if(h.length===0)continue;const g=this.analyzeJoinPathToPrimary(e,t,l.name,s,i);let y,b;if(g?.hasIntermediateHasMany&&g.intermediateJoins.length>0)y=g.correctJoinKeys,b=g.intermediateJoins;else{const N=(g?.path&&g.path.length>0?(()=>{const F=g.path[g.path.length-1],v=e.get(F.fromCube);return v?{sourceCube:v,joinDef:F.joinDef,reversed:F.reversed}:null})():null)??this.findJoinInfoForCube(e,t,l.name);if(!N)continue;N.joinDef.relationship==="belongsToMany"&&N.joinDef.through?N.sourceCube?.name===t.name&&!("reversed"in N&&N.reversed)?y=N.joinDef.through.targetKey.map(v=>({sourceColumn:v.source.name,targetColumn:v.target.name,sourceColumnObj:v.source,targetColumnObj:v.target})):y=N.joinDef.through.sourceKey.map(v=>({sourceColumn:v.target.name,targetColumn:v.source.name,sourceColumnObj:v.target,targetColumnObj:v.source})):y="reversed"in N&&N.reversed?N.joinDef.on.map(v=>({sourceColumn:v.target.name,targetColumn:v.source.name,sourceColumnObj:v.target,targetColumnObj:v.source})):N.joinDef.on.map(v=>({sourceColumn:v.source.name,targetColumn:v.target.name,sourceColumnObj:v.source,targetColumnObj:v.target})),b=void 0}const w=this.findPropagatingFilters(i,l,e),T=new Map([[l.name,l]]),{aggregateMeasures:S,requiredBaseMeasures:C}=j.categorizeForPostAggregation(h,T),$=[...new Set([...S,...Array.from(C).filter(D=>D.startsWith(l.name+"."))])];if($.length>0){const D=this.expandCalculatedMeasureDependencies(l,$),N=this.findDownstreamJoinKeys(l,i,e);r.push({cube:l,alias:m,cteAlias:`${l.name.toLowerCase()}_agg`,joinKeys:y,measures:D,propagatingFilters:w.length>0?w:void 0,downstreamJoinKeys:N.length>0?N:void 0,intermediateJoins:b&&b.length>0?b:void 0,cteType:"aggregate",cteReason:c})}}return r}findJoinInfoToCube(e,t){for(const[,n]of e)if(n.name!==t&&n.joins){for(const[,i]of Object.entries(n.joins))if(K(i.targetCube).name===t)return{sourceCube:n,joinDef:i}}return null}analyzeJoinPathToPrimary(e,t,n,i,s){const r=this.getResolver(e),a=this.collectPathHintCubes(s),u=a.size>0?r.findPathPreferring(t.name,n,a,new Set):r.findPath(t.name,n);if(!u||u.length===0)return null;const c=u.map(g=>({fromCube:g.fromCube,toCube:g.toCube,joinDef:g.joinDef,reversed:g.reversed}));if(!c.slice(0,-1).some(g=>(g.reversed?Ne(g.joinDef.relationship):g.joinDef.relationship)==="hasMany"))return{path:c,hasIntermediateHasMany:!1,intermediateJoins:[],correctJoinKeys:[]};const p=[];for(let g=0;g<c.length-1;g++){const y=c[g],b=c[g+1],w=e.get(y.toCube);if(!w)continue;const S=w.sql(i).where,C=b.joinDef.on[0]?.source,$=y.joinDef.on[0]?.target;p.push({cube:w,joinDef:b.joinDef,securityFilter:S,primaryJoinColumn:$,cteJoinColumn:C})}const h=c[0].joinDef.on.map(g=>({sourceColumn:g.source.name,targetColumn:g.target.name,sourceColumnObj:g.source,targetColumnObj:g.target}));return{path:c,hasIntermediateHasMany:!0,intermediateJoins:p,correctJoinKeys:h}}computeCTEReasons(e,t,n){const i=new Map,s=new Set,r=new Set,a=new Set;if(n.measures)for(const u of n.measures){const[c]=u.split(".");a.add(c)}for(const u of t)u.relationship==="hasMany"||u.relationship==="belongsToMany"?s.add(u.cube.name):u.relationship==="belongsTo"&&a.has(u.cube.name)&&r.add(u.cube.name);if(s.size===0&&r.size===0)return i;for(const u of t)a.has(u.cube.name)&&(s.has(u.cube.name)?i.set(u.cube.name,"hasMany"):(r.has(u.cube.name)||s.size>0)&&i.set(u.cube.name,"fanOutPrevention"));return i}findJoinInfoForCube(e,t,n){if(t.joins){for(const[,s]of Object.entries(t.joins))if(K(s.targetCube).name===n)return{sourceCube:t,joinDef:s}}const i=e.get(n);if(i?.joins){for(const[,s]of Object.entries(i.joins))if(K(s.targetCube).name===t.name)return{sourceCube:i,joinDef:s,reversed:!0}}for(const[,s]of e)if(!(s.name===t.name||s.name===n)&&s.joins){for(const[,r]of Object.entries(s.joins))if(K(r.targetCube).name===n)return{sourceCube:s,joinDef:r}}return null}findDownstreamJoinKeys(e,t,n){const i=[],s=new Set;if(t.dimensions)for(const r of t.dimensions){const[a]=r.split(".");a!==e.name&&s.add(a)}if(t.timeDimensions)for(const r of t.timeDimensions){const[a]=r.dimension.split(".");a!==e.name&&s.add(a)}if(t.filters){for(const r of t.filters)this.extractCubeNamesFromFilter(r,s);s.delete(e.name)}if(e.joins)for(const[,r]of Object.entries(e.joins)){const u=K(r.targetCube).name;if(s.has(u)){let c;r.relationship==="belongsToMany"&&r.through?c=r.through.sourceKey.map(l=>({sourceColumn:l.source.name,targetColumn:l.target.name,sourceColumnObj:l.source,targetColumnObj:l.target})):c=r.on.map(l=>({sourceColumn:l.source.name,targetColumn:l.target.name,sourceColumnObj:l.source,targetColumnObj:l.target})),i.push({targetCubeName:u,joinKeys:c})}}return i}expandCalculatedMeasureDependencies(e,t){const n=new Set,i=[...t];for(;i.length>0;){const s=i.pop();if(n.has(s))continue;n.add(s);const[,r]=s.split(".");if(!e.measures||!e.measures[r])continue;const a=e.measures[r];if(a.type==="calculated"&&a.calculatedSql){const u=this.extractDependenciesFromTemplate(a.calculatedSql,e.name);for(const c of u)n.has(c)||i.push(c)}}return Array.from(n)}extractDependenciesFromTemplate(e,t){const n=/\{([^}]+)\}/g,i=e.matchAll(n),s=[];for(const r of i){const a=r[1].trim();a.includes(".")?s.push(a):s.push(`${t}.${a}`)}return s}findHasManyJoinDef(e,t){if(!e.joins)return null;for(const[,n]of Object.entries(e.joins))if(K(n.targetCube).name===t&&n.relationship==="hasMany")return n;return null}findPropagatingFilters(e,t,n){const i=[];if(!e.filters)return i;const s=new Set;if(this.extractFilterCubeNamesToSet(e.filters,s),e.timeDimensions){for(const r of e.timeDimensions)if(r.dateRange){const[a]=r.dimension.split(".");a&&s.add(a)}}for(const r of s){if(r===t.name)continue;const a=n.get(r);if(a?.joins){for(const[,u]of Object.entries(a.joins))if(K(u.targetCube).name===t.name&&u.relationship==="hasMany"){const l=this.extractFiltersForCube(e.filters,r),m=this.extractTimeDimensionFiltersForCube(e,r),p=[...l,...m];p.length>0&&u.on.length>0&&i.push({sourceCube:a,filters:p,joinConditions:u.on.map(f=>({source:f.source,target:f.target}))})}}}return i}extractFilterCubeNamesToSet(e,t){for(const n of e){if("and"in n||"or"in n){const i=n.and||n.or||[];this.extractFilterCubeNamesToSet(i,t);continue}if("member"in n){const[i]=n.member.split(".");i&&t.add(i)}}}extractFiltersForCube(e,t){const n=[];for(const i of e){if("and"in i){const s=this.extractFiltersForCube(i.and||[],t);s.length>0&&n.push({and:s});continue}if("or"in i){const s=i.or||[];if(this.allFiltersFromCube(s,t)){const a=this.extractFiltersForCube(s,t);a.length>0&&n.push({or:a})}continue}if("member"in i){const[s]=i.member.split(".");s===t&&n.push(i)}}return n}allFiltersFromCube(e,t){for(const n of e){if("and"in n){if(!this.allFiltersFromCube(n.and||[],t))return!1;continue}if("or"in n){if(!this.allFiltersFromCube(n.or||[],t))return!1;continue}if("member"in n){const[i]=n.member.split(".");if(i!==t)return!1}}return!0}extractTimeDimensionFiltersForCube(e,t){const n=[];if(!e.timeDimensions)return n;for(const i of e.timeDimensions){const[s]=i.dimension.split(".");s===t&&i.dateRange&&n.push({member:i.dimension,operator:"inDateRange",values:Array.isArray(i.dateRange)?i.dateRange:[i.dateRange]})}return n}analyzePrimaryCubeSelection(e,t,n){if(e.length===1)return{selectedCube:e[0],reason:"single_cube",explanation:"Only one cube is used in this query"};const i=[],s=(t.dimensions||[]).map(l=>l.split(".")[0]),r=new Map;for(const l of s)r.set(l,(r.get(l)||0)+1);const a=this.getResolver(n);for(const l of e){const m=n.get(l),p=r.get(l)||0,f=m?.joins?Object.keys(m.joins).length:0,h=a.canReachAll(l,e);i.push({cubeName:l,dimensionCount:p,joinCount:f,canReachAll:h})}if(t.dimensions&&t.dimensions.length>0){const l=Math.max(...i.map(m=>m.dimensionCount));if(l>0){const m=i.filter(p=>p.dimensionCount===l).sort((p,f)=>p.cubeName.localeCompare(f.cubeName));for(const p of m)if(p.canReachAll)return{selectedCube:p.cubeName,reason:"most_dimensions",explanation:`Selected because it has ${p.dimensionCount} dimension${p.dimensionCount!==1?"s":""} in the query (defines the analytical grain)`,candidates:i}}}const u=i.filter(l=>l.canReachAll);if(u.length>0){const l=Math.max(...u.map(p=>p.joinCount)),m=u.filter(p=>p.joinCount===l).sort((p,f)=>p.cubeName.localeCompare(f.cubeName))[0];return{selectedCube:m.cubeName,reason:"most_connected",explanation:`Selected because it has ${m.joinCount} join relationship${m.joinCount!==1?"s":""} and can reach all other cubes`,candidates:i}}return{selectedCube:[...e].sort()[0],reason:"alphabetical_fallback",explanation:"Selected alphabetically as fallback (no cube could reach all others)",candidates:i}}analyzeJoinPath(e,t,n,i){const s=this.getResolver(e),r=i?this.collectPathHintCubes(i):new Set,a=r.size>0?s.findPathPreferringDetailed(t,n,r):null,u=a?.selectedPath??s.findPath(t,n),c=[t];if(u)for(const m of u)c.push(m.toCube);if(!u||u.length===0)return{targetCube:n,pathFound:!1,error:`No join path found from '${t}' to '${n}'. Ensure the target cube has a relationship defined (belongsTo, hasOne, hasMany, or belongsToMany).`,visitedCubes:c,selection:this.buildJoinPathSelectionAnalysis(a)};const l=this.convertInternalPathToJoinPathSteps(u);return{targetCube:n,pathFound:!0,path:l,pathLength:l.length,visitedCubes:c,selection:this.buildJoinPathSelectionAnalysis(a)}}convertInternalPathToJoinPathSteps(e){return e.map(t=>{const n=t.reversed?Ne(t.joinDef.relationship):t.joinDef.relationship,i=Fe(n,t.joinDef.sqlJoinType),s=t.joinDef.on.map(a=>({sourceColumn:a.source.name,targetColumn:a.target.name})),r={fromCube:t.fromCube,toCube:t.toCube,relationship:n,joinType:i,joinColumns:s};if(t.reversed&&(r.reversed=!0),n==="belongsToMany"&&t.joinDef.through){const a=t.joinDef.through;r.junctionTable={tableName:a.table[Symbol.for("drizzle:Name")]||"junction_table",sourceColumns:a.sourceKey.map(u=>u.target.name),targetColumns:a.targetKey.map(u=>u.source.name)}}return r})}buildJoinPathSelectionAnalysis(e){if(!e)return{strategy:"shortest"};const t=e.candidates.map((n,i)=>this.mapPreferredCandidate(n,i+1));return{strategy:e.strategy,preferredCubes:e.preferredCubes,selectedRank:e.selectedIndex>=0?e.selectedIndex+1:void 0,selectedScore:e.selectedIndex>=0?e.candidates[e.selectedIndex]?.score:void 0,candidates:t}}mapPreferredCandidate(e,t){return{rank:t,score:e.score,usesPreferredJoin:e.usesPreferredJoin,preferredCubesInPath:e.preferredCubesInPath,usesProcessed:e.usesProcessed,scoreBreakdown:e.scoreBreakdown,path:this.convertInternalPathToJoinPathSteps(e.path)}}generateWarnings(e,t){const n=[],i=this.checkFanOutNoDimensions(e,t);return i&&n.push(i),n}checkFanOutNoDimensions(e,t){if(!t||t.length===0||!e.measures||e.measures.length===0)return null;const n=new Set;for(const r of e.measures){const[a]=r.split(".");n.add(a)}if(n.size<2)return null;const i=e.dimensions&&e.dimensions.length>0,s=e.timeDimensions?.some(r=>r.granularity);return i||s?null:{code:"FAN_OUT_NO_DIMENSIONS",message:"Query combines measures from multiple cubes with hasMany relationships but has no dimensions. Results are aggregated at the join key level, which may produce unexpected totals.",severity:"warning",cubes:[...n].sort(),measures:e.measures,suggestion:"Add a dimension to see per-group breakdowns, or add a time dimension with granularity."}}}class dn{constructor(e){this.queryBuilder=e}buildPreAggregationCTE(e,t,n,i,s){const r=e.cube,a=r.sql(n),u=e.intermediateJoins&&e.intermediateJoins.length>0,c={};if(u&&e.intermediateJoins){const $=e.intermediateJoins[0].primaryJoinColumn;if($){const D=$.name;c[D]=$}}else for(const C of e.joinKeys)if(C.targetColumnObj){c[C.targetColumn]=C.targetColumnObj;for(const[$,D]of Object.entries(r.dimensions||{}))D.sql===C.targetColumnObj&&$!==C.targetColumn&&(c[$]=o`${C.targetColumnObj}`.as($))}if(e.downstreamJoinKeys)for(const C of e.downstreamJoinKeys)for(const $ of C.joinKeys)$.sourceColumnObj&&(c[$.sourceColumn]=$.sourceColumnObj);const l=r.name,m=new Map([[l,r]]),p=this.queryBuilder.buildResolvedMeasures(e.measures,m,n);for(const C of e.measures){const[,$]=C.split("."),D=p.get(C);if(D){const N=D();c[$]=o`${N}`.as($)}}if(t.dimensions)for(const C of t.dimensions){const[$,D]=C.split(".");if($===l&&r.dimensions&&r.dimensions[D]){const N=r.dimensions[D],F=this.queryBuilder.buildMeasureExpression({sql:N.sql,type:"number"},n);c[D]=o`${F}`.as(D)}}if(t.timeDimensions)for(const C of t.timeDimensions){const[$,D]=C.dimension.split(".");if($===l&&r.dimensions&&r.dimensions[D]){const N=r.dimensions[D],F=this.queryBuilder.buildTimeDimensionExpression(N.sql,C.granularity,n);c[D]=o`${F}`.as(D)}}if(Object.keys(c).length===0)return null;let f=n.db.select(c).from(a.from);if(u&&e.intermediateJoins){const C=[...e.intermediateJoins].reverse();for(const $ of C){const D=$.cube.sql(n),F=[k($.cteJoinColumn,$.joinDef.on[0]?.target)];$.securityFilter&&F.push($.securityFilter),f=f.leftJoin(D.from,A(...F))}}const h=i?{...i,preAggregationCTEs:i.preAggregationCTEs?.filter(C=>C.cube.name!==r.name)}:void 0,g=this.queryBuilder.buildWhereConditions(r,t,n,h,s),y=[];if(t.timeDimensions)for(const C of t.timeDimensions){const[$,D]=C.dimension.split(".");if($===l&&r.dimensions&&r.dimensions[D]&&C.dateRange){const N=r.dimensions[D],F=this.queryBuilder.buildMeasureExpression({sql:N.sql,type:"number"},n),v=this.queryBuilder.buildDateRangeCondition(F,C.dateRange);v&&y.push(v)}}if(t.filters){for(const C of t.filters)if(!("and"in C)&&!("or"in C)&&"member"in C&&"operator"in C){const $=C,[D,N]=$.member.split(".");if(D===l&&r.dimensions&&r.dimensions[N]){const F=r.dimensions[N];if($.operator==="inDateRange"){const v=this.queryBuilder.buildMeasureExpression({sql:F.sql,type:"number"},n),U=this.queryBuilder.buildDateRangeCondition(v,$.values);U&&y.push(U)}}}}if(e.propagatingFilters&&e.propagatingFilters.length>0)for(const C of e.propagatingFilters){const $=this.buildPropagatingFilterSubquery(C,n);$&&y.push($)}const b=[];if(a.where&&b.push(a.where),b.push(...g,...y),b.length>0){const C=b.length===1?b[0]:A(...b);f=f.where(C)}const w=[],T=new Set,S=C=>{const $=C?.name||(typeof C=="string"?C:null);$&&!T.has($)?(T.add($),w.push(C)):$||w.push(C)};if(u&&e.intermediateJoins){const C=e.intermediateJoins[0];C.primaryJoinColumn&&S(C.primaryJoinColumn)}else for(const C of e.joinKeys)C.targetColumnObj&&S(C.targetColumnObj);if(e.downstreamJoinKeys)for(const C of e.downstreamJoinKeys)for(const $ of C.joinKeys)$.sourceColumnObj&&S($.sourceColumnObj);if(t.dimensions)for(const C of t.dimensions){const[$,D]=C.split(".");if($===l&&r.dimensions&&r.dimensions[D]){const N=r.dimensions[D],F=R(N.sql,n);w.push(F)}}if(t.timeDimensions)for(const C of t.timeDimensions){const[$,D]=C.dimension.split(".");if($===l&&r.dimensions&&r.dimensions[D]){const N=r.dimensions[D],F=this.queryBuilder.buildTimeDimensionExpression(N.sql,C.granularity,n);w.push(F)}}return w.length>0&&(f=f.groupBy(...w)),n.db.$with(e.cteAlias).as(f)}buildCTEJoinCondition(e,t,n){const i=n.preAggregationCTEs?.find(r=>r.cube.name===e.cube.name);if(!i)throw new Error(`CTE info not found for cube ${e.cube.name}`);const s=[];if(i.intermediateJoins&&i.intermediateJoins.length>0){const r=i.intermediateJoins[0],a=this.resolveCTEJoinSourceColumn(i.joinKeys[0],i,n),u=o`${o.identifier(t)}.${o.identifier(r.primaryJoinColumn.name)}`;s.push(k(a,u))}else for(const r of i.joinKeys){const a=this.resolveCTEJoinSourceColumn(r,i,n),u=o`${o.identifier(t)}.${o.identifier(r.targetColumn)}`;s.push(k(a,u))}return s.length===1?s[0]:A(...s)}resolveCTEJoinSourceColumn(e,t,n){if(!e)throw new Error(`Missing join key while building CTE join condition for '${t.cube.name}'`);const i=e.sourceColumnObj||o.identifier(e.sourceColumn);if(!e.sourceColumnObj||!n.preAggregationCTEs)return i;for(const s of n.preAggregationCTEs)if(s.cube.name!==t.cube.name){for(const[r,a]of Object.entries(s.cube.dimensions||{}))if(typeof a.sql!="function"&&a.sql===e.sourceColumnObj)return o`${o.identifier(s.cteAlias)}.${o.identifier(r)}`}return i}buildPropagatingFilterSubquery(e,t){const n=e.sourceCube,i=n.sql(t),s=[];if(i.where&&s.push(i.where),e.preBuiltFilterSQL)s.push(e.preBuiltFilterSQL);else{const u={filters:e.filters},c=new Map([[n.name,n]]),l=this.queryBuilder.buildWhereConditions(c,u,t);s.push(...l)}if(s.length===0)return null;const r=s.length===1?s[0]:A(...s),a=e.joinConditions;if(a.length===1){const{source:u,target:c}=a[0],l=t.db.select({pk:u}).from(i.from).where(r);return o`${c} IN ${l}`}else{const u=a.map(m=>k(m.source,m.target)),c=A(...u,r),l=t.db.select({one:o`1`}).from(i.from).where(c);return o`EXISTS ${l}`}}}function mn(d,e,t){const n=[];let i=Ye(new Date(d),t);const s=Ye(new Date(e),t),r=1e4;for(;i<=s&&n.length<r;)n.push(new Date(i)),i=fn(i,t);return n}function Ye(d,e){const t=new Date(d);switch(e){case"second":t.setUTCMilliseconds(0);break;case"minute":t.setUTCSeconds(0,0);break;case"hour":t.setUTCMinutes(0,0,0);break;case"day":t.setUTCHours(0,0,0,0);break;case"week":{const n=t.getUTCDay(),i=n===0?6:n-1;t.setUTCDate(t.getUTCDate()-i),t.setUTCHours(0,0,0,0);break}case"month":t.setUTCDate(1),t.setUTCHours(0,0,0,0);break;case"quarter":{const n=Math.floor(t.getUTCMonth()/3)*3;t.setUTCMonth(n,1),t.setUTCHours(0,0,0,0);break}case"year":t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0);break}return t}function fn(d,e){const t=new Date(d);switch(e){case"second":t.setUTCSeconds(t.getUTCSeconds()+1);break;case"minute":t.setUTCMinutes(t.getUTCMinutes()+1);break;case"hour":t.setUTCHours(t.getUTCHours()+1);break;case"day":t.setUTCDate(t.getUTCDate()+1);break;case"week":t.setUTCDate(t.getUTCDate()+7);break;case"month":t.setUTCMonth(t.getUTCMonth()+1);break;case"quarter":t.setUTCMonth(t.getUTCMonth()+3);break;case"year":t.setUTCFullYear(t.getUTCFullYear()+1);break}return t}function pn(d){if(d instanceof Date)return d.toISOString();if(typeof d=="string"){const e=new Date(d);if(!isNaN(e.getTime()))return e.toISOString()}return String(d)}function hn(d,e){return e.length===0?"__all__":e.map(t=>String(d[t]??"")).join("|||")}function gn(d,e){const{timeDimensionKey:t,granularity:n,dateRange:i,fillValue:s,measures:r,dimensions:a}=e,u=mn(i[0],i[1],n);if(u.length===0)return d;const c=new Map;for(const m of d){const p=hn(m,a),f=pn(m[t]);c.has(p)||c.set(p,new Map),c.get(p).set(f,m)}c.size===0&&a.length===0&&c.set("__all__",new Map);const l=[];for(const[m,p]of c){const f=p.size>0?p.values().next().value:null;for(const h of u){const g=h.toISOString(),y=p.get(g);if(y)l.push(y);else{const b={[t]:g};if(f)for(const w of a)b[w]=f[w];for(const w of r)b[w]=s;l.push(b)}}}return l}function bn(d){if(!d)return null;if(Array.isArray(d)){if(d.length<2)return null;const t=new Date(d[0]),n=new Date(d[1]);return isNaN(t.getTime())||isNaN(n.getTime())?null:[t,n]}const e=new Date(d);return isNaN(e.getTime())?null:[e,e]}function Xe(d,e,t){if(!e.timeDimensions||e.timeDimensions.length===0)return d;const n=e.timeDimensions.filter(u=>{const c=u.fillMissingDates!==!1,l=u.granularity&&u.dateRange;return c&&l});if(n.length===0)return d;const i=e.fillMissingDatesValue===void 0?0:e.fillMissingDatesValue,s=new Set(e.timeDimensions.map(u=>u.dimension)),r=(e.dimensions||[]).filter(u=>!s.has(u));let a=d;for(const u of n){const c=bn(u.dateRange);if(!c)continue;const l={timeDimensionKey:u.dimension,granularity:u.granularity,dateRange:c,fillValue:i,measures:t,dimensions:r};a=gn(a,l)}return a}class yn{dateTimeBuilder;constructor(e){this.dateTimeBuilder=new re(e)}hasComparison(e){return e.timeDimensions?.some(t=>t.compareDateRange&&t.compareDateRange.length>=2)??!1}getComparisonTimeDimension(e){return e.timeDimensions?.find(t=>t.compareDateRange&&t.compareDateRange.length>=2)}normalizePeriods(e){const t=[];for(let n=0;n<e.length;n++){const i=e[n];let s,r,a;if(typeof i=="string"){const u=this.dateTimeBuilder.parseRelativeDateRange(i);if(u)s=u.start,r=u.end,a=i;else{const c=new Date(i);if(!isNaN(c.getTime()))s=new Date(c),s.setUTCHours(0,0,0,0),r=new Date(c),r.setUTCHours(23,59,59,999),a=i;else continue}}else{if(s=new Date(i[0]),r=new Date(i[1]),isNaN(s.getTime())||isNaN(r.getTime()))continue;/^\d{4}-\d{2}-\d{2}$/.test(i[1])&&r.setUTCHours(23,59,59,999),a=`${i[0]} - ${i[1]}`}t.push({start:s,end:r,label:a,index:n})}return t}createPeriodQuery(e,t){return{...e,timeDimensions:e.timeDimensions?.map(n=>n.compareDateRange?{...n,dateRange:[t.start.toISOString(),t.end.toISOString()],compareDateRange:void 0}:n)}}calculatePeriodDayIndex(e,t,n){const i=typeof e=="string"?new Date(e):e,s=t.getTime(),r=i.getTime();switch(n){case"second":return Math.floor((r-s)/1e3);case"minute":return Math.floor((r-s)/(1e3*60));case"hour":return Math.floor((r-s)/(1e3*60*60));case"day":return Math.floor((r-s)/(1e3*60*60*24));case"week":return Math.floor((r-s)/(1e3*60*60*24*7));case"month":{const a=t.getUTCFullYear(),u=t.getUTCMonth(),c=i.getUTCFullYear(),l=i.getUTCMonth();return(c-a)*12+(l-u)}case"quarter":{const a=t.getUTCFullYear(),u=Math.floor(t.getUTCMonth()/3),c=i.getUTCFullYear(),l=Math.floor(i.getUTCMonth()/3);return(c-a)*4+(l-u)}case"year":return i.getUTCFullYear()-t.getUTCFullYear();default:return Math.floor((r-s)/(1e3*60*60*24))}}addPeriodMetadata(e,t,n,i){return e.map(s=>{const r=s[n];let a=0;if(r){const u=typeof r=="string"?new Date(r):r instanceof Date?r:null;u&&!isNaN(u.getTime())&&(a=this.calculatePeriodDayIndex(u,t.start,i))}return{...s,__period:t.label,__periodIndex:t.index,__periodDayIndex:a}})}mergeComparisonResults(e,t,n){const i=[];let s={measures:{},dimensions:{},segments:{},timeDimensions:{}};const r=e.map(u=>u.period);for(const{result:u,period:c}of e){const l=this.addPeriodMetadata(u.data,c,t.dimension,n);i.push(...l),s={measures:{...s.measures,...u.annotation.measures},dimensions:{...s.dimensions,...u.annotation.dimensions},segments:{...s.segments,...u.annotation.segments},timeDimensions:{...s.timeDimensions,...u.annotation.timeDimensions}}}const a={ranges:r.map(u=>[u.start.toISOString().split("T")[0],u.end.toISOString().split("T")[0]]),labels:r.map(u=>u.label),timeDimension:t.dimension,granularity:n};return{data:i,annotation:{...s,periods:a}}}sortComparisonResults(e,t){return[...e].sort((n,i)=>{const s=n.__periodIndex-i.__periodIndex;if(s!==0)return s;const r=n[t],a=i[t];return typeof r=="string"&&typeof a=="string"?new Date(r).getTime()-new Date(a).getTime():0})}}class Cn{constructor(e){this.databaseAdapter=e,this.dateTimeBuilder=new re(e),this.filterBuilder=new be(e,this.dateTimeBuilder)}filterBuilder;dateTimeBuilder;hasFunnel(e){return e.funnel!==void 0&&e.funnel.steps.length>=2}validateConfig(e,t){const n=[];if(e.steps.length<2&&n.push("Funnel must have at least 2 steps"),typeof e.bindingKey=="string"){const[i,s]=e.bindingKey.split(".");if(!i||!s)n.push(`Invalid binding key format: ${e.bindingKey}. Expected 'CubeName.dimensionName'`);else{const r=t.get(i);r?r.dimensions?.[s]||n.push(`Binding key dimension not found: ${s} in cube ${i}`):n.push(`Binding key cube not found: ${i}`)}}else if(Array.isArray(e.bindingKey))for(const i of e.bindingKey){const s=t.get(i.cube);if(!s)n.push(`Binding key mapping cube not found: ${i.cube}`);else{const[,r]=i.dimension.split(".");s.dimensions?.[r]||n.push(`Binding key dimension not found: ${r} in cube ${i.cube}`)}}if(typeof e.timeDimension=="string"){const[i,s]=e.timeDimension.split(".");if(!i||!s)n.push(`Invalid time dimension format: ${e.timeDimension}. Expected 'CubeName.dimensionName'`);else{const r=t.get(i);r?r.dimensions?.[s]||n.push(`Time dimension not found: ${s} in cube ${i}`):n.push(`Time dimension cube not found: ${i}`)}}for(let i=0;i<e.steps.length;i++){const s=e.steps[i];if(s.name||n.push(`Step ${i} must have a name`),"cube"in s&&s.cube&&(t.get(s.cube)||n.push(`Step ${i} cube not found: ${s.cube}`)),s.filter){let r;"cube"in s&&s.cube?r=s.cube:typeof e.bindingKey=="string"&&([r]=e.bindingKey.split("."));const a=r?new ue(t):null,u=Array.isArray(s.filter)?s.filter:[s.filter];for(const c of u)if("member"in c){const[l,m]=c.member.split("."),p=t.get(l);if(!p)n.push(`Step ${i} filter cube not found: ${l}`);else if(p.dimensions?.[m]||(p.measures?.[m]?n.push(`Step ${i} filter '${l}.${m}' is a measure. Funnel step filters only support dimensions, not measures.`):n.push(`Step ${i} filter member not found: ${m} in cube ${l}`)),r&&l!==r&&a){const f=a.findPath(r,l);(!f||f.length===0)&&n.push(`Step ${i} filter '${l}.${m}' requires a join from '${r}' but no join path was found. Define a join relationship between these cubes.`)}}}s.timeToConvert&&i>0&&(/^P(?:\d+Y)?(?:\d+M)?(?:\d+D)?(?:T(?:\d+H)?(?:\d+M)?(?:\d+(?:\.\d+)?S)?)?$/.test(s.timeToConvert)||n.push(`Step ${i} timeToConvert must be ISO 8601 duration format: ${s.timeToConvert}`))}return{isValid:n.length===0,errors:n}}buildFunnelQuery(e,t,n){const i=this.resolveSteps(e,t,n),s=[];for(let c=0;c<i.length;c++){const l=c>0?s[c-1]:void 0;s.push(this.buildStepCTE(i[c],n,l))}const r=this.buildFunnelResultsCTE(s,i,e,n),a=this.buildAggregationCTE(r,s,i,e,n),u=[...s,r,a];return n.db.with(...u).select().from(a)}transformResult(e,t){if(!e||e.length===0)return[];const n=e[0],i=[],s=Number(n.step_0_count)||0;for(let r=0;r<t.steps.length;r++){const a=t.steps[r],u=Number(n[`step_${r}_count`])||0,c=r>0&&Number(n[`step_${r-1}_count`])||0,l={step:a.name,stepIndex:r,count:u,conversionRate:r===0?null:c>0?u/c:0,cumulativeConversionRate:s>0?u/s:0};t.includeTimeMetrics&&r>0&&(l.avgSecondsToConvert=n[`step_${r}_avg_seconds`]!==null?Number(n[`step_${r}_avg_seconds`]):null,l.minSecondsToConvert=n[`step_${r}_min_seconds`]!==null?Number(n[`step_${r}_min_seconds`]):null,l.maxSecondsToConvert=n[`step_${r}_max_seconds`]!==null?Number(n[`step_${r}_max_seconds`]):null,n[`step_${r}_median_seconds`]!==void 0&&(l.medianSecondsToConvert=n[`step_${r}_median_seconds`]!==null?Number(n[`step_${r}_median_seconds`]):null),n[`step_${r}_p90_seconds`]!==void 0&&(l.p90SecondsToConvert=n[`step_${r}_p90_seconds`]!==null?Number(n[`step_${r}_p90_seconds`]):null)),i.push(l)}return i}extractFilterCubeNames(e){const t=new Set;if(!e.filter)return t;const n=Array.isArray(e.filter)?e.filter:[e.filter],i=s=>{if("and"in s&&s.and)for(const r of s.and)i(r);else if("or"in s&&s.or)for(const r of s.or)i(r);else if("type"in s&&"filters"in s){const r=s;for(const a of r.filters||[])i(a)}else if("member"in s){const[r]=s.member.split(".");t.add(r)}};for(const s of n)i(s);return t}resolveSteps(e,t,n){const i=new ue(t);return e.steps.map((s,r)=>{const a=this.resolveCubeForStep(s,e,t),u=this.resolveBindingKey(e,a,n),c=this.resolveTimeDimension(e,a,n),l=this.buildStepFilters(s,a,t,n),m=this.extractFilterCubeNames(s),p=[];for(const f of m)if(f!==a.name){const h=t.get(f);if(h){const g=i.findPath(a.name,f);g&&g.length>0&&p.push({cube:h,joinPath:g})}}return{name:s.name,index:r,cube:a,bindingKeyExpr:u,timeExpr:c,filterConditions:l,timeToConvert:s.timeToConvert,joinedCubes:p}})}resolveCubeForStep(e,t,n){if("cube"in e&&e.cube){const i=n.get(e.cube);if(!i)throw new Error(`Cube not found for step: ${e.cube}`);return i}if(typeof t.bindingKey=="string"){const[i]=t.bindingKey.split("."),s=n.get(i);if(!s)throw new Error(`Cube not found for binding key: ${t.bindingKey}`);return s}throw new Error("Cannot resolve cube for step - multi-cube funnel requires cube specification in each step")}resolveBindingKey(e,t,n){if(typeof e.bindingKey=="string"){const[,a]=e.bindingKey.split("."),u=t.dimensions?.[a];if(!u)throw new Error(`Binding key dimension not found: ${e.bindingKey}`);return R(u.sql,n)}const i=e.bindingKey.find(a=>a.cube===t.name);if(!i)throw new Error(`No binding key mapping found for cube: ${t.name}`);const[,s]=i.dimension.split("."),r=t.dimensions?.[s];if(!r)throw new Error(`Binding key dimension not found: ${i.dimension}`);return R(r.sql,n)}resolveTimeDimension(e,t,n){if(typeof e.timeDimension=="string"){const[,a]=e.timeDimension.split("."),u=t.dimensions?.[a];if(!u)throw new Error(`Time dimension not found: ${e.timeDimension}`);return R(u.sql,n)}const i=e.timeDimension.find(a=>a.cube===t.name);if(!i)throw new Error(`No time dimension mapping found for cube: ${t.name}`);const[,s]=i.dimension.split("."),r=t.dimensions?.[s];if(!r)throw new Error(`Time dimension not found: ${i.dimension}`);return R(r.sql,n)}buildStepFilters(e,t,n,i){if(!e.filter)return[];const s=Array.isArray(e.filter)?e.filter:[e.filter],r=[];for(const a of s){const u=this.buildFilterCondition(a,t,n,i);u&&r.push(u)}return r}buildFilterCondition(e,t,n,i){const s="and"in e||"or"in e,r="type"in e&&"filters"in e&&(e.type==="and"||e.type==="or");if(s||r){const g=[];let y;if(r){const b=e;y=b.type==="and";for(const w of b.filters||[]){const T=this.buildFilterCondition(w,t,n,i);T&&g.push(T)}}else{const b=e;y="and"in b&&!!b.and;const w=b.and||b.or||[];for(const T of w){const S=this.buildFilterCondition(T,t,n,i);S&&g.push(S)}}return g.length===0?null:g.length===1?g[0]:y?A(...g):o`(${o.join(g,o` OR `)})`}const a=e,[u,c]=a.member.split("."),l=a.dateRange!==void 0;if(a.operator!=="set"&&a.operator!=="notSet"&&!l&&(!a.values||a.values.length===0||a.values[0]===void 0||a.values[0]===""))return null;const p=n.get(u);if(!p)return null;if(u!==t.name){const y=new ue(n).findPath(t.name,u);if(!y||y.length===0)return console.warn(`Funnel filter: Cannot filter by '${u}.${c}' in step using '${t.name}'. No join path found. Filter will be skipped.`),null}const f=p.dimensions?.[c];if(!f)return null;const h=f.type==="time"?R(f.sql,i):typeof f.sql=="function"?f.sql(i):f.sql;return this.filterBuilder.buildFilterCondition(h,a.operator,a.values||[],f,a.dateRange)}buildStepCTE(e,t,n){return e.index===0?this.buildFirstStepCTE(e,t):this.buildSubsequentStepCTE(e,t,n)}buildFirstStepCTE(e,t){const n=`step_${e.index}`,i=e.cube.sql(t),s=[];i.where&&s.push(i.where),s.push(...e.filterConditions);let r=t.db.select({binding_key:o`${e.bindingKeyExpr}`.as("binding_key"),step_time:o`MIN(${e.timeExpr})`.as("step_time")}).from(i.from);if(r=this.addCrossJoinsToQuery(r,e,t,s),s.length>0){const a=s.length===1?s[0]:A(...s);r=r.where(a)}return r=r.groupBy(e.bindingKeyExpr),t.db.$with(n).as(r)}buildSubsequentStepCTE(e,t,n){const i=`step_${e.index}`,s=`step_${e.index-1}`,r=e.cube.sql(t),a=[];r.where&&a.push(r.where),a.push(...e.filterConditions);const u=o`${o.identifier(s)}.step_time`;let c=o`${e.timeExpr} > ${u}`;if(e.timeToConvert){const m=this.databaseAdapter.buildDateAddInterval(u,e.timeToConvert);c=o`${c} AND ${e.timeExpr} <= ${m}`}a.push(c);let l=t.db.select({binding_key:o`${e.bindingKeyExpr}`.as("binding_key"),step_time:o`MIN(${e.timeExpr})`.as("step_time")}).from(r.from).innerJoin(n,o`${e.bindingKeyExpr} = ${o.identifier(s)}.binding_key`);if(l=this.addCrossJoinsToQuery(l,e,t,a),a.length>0){const m=a.length===1?a[0]:A(...a);l=l.where(m)}return l=l.groupBy(e.bindingKeyExpr),t.db.$with(i).as(l)}addCrossJoinsToQuery(e,t,n,i){if(t.joinedCubes.length===0)return e;for(const s of t.joinedCubes)for(const r of s.joinPath){const a=r.joinDef,u=[];for(const p of a.on)p.as?u.push(p.as(p.source,p.target)):u.push(k(p.source,p.target));const c=u.length===1?u[0]:A(...u),m=s.cube.sql(n);e=e.leftJoin(m.from,c),m.where&&i.push(m.where)}return e}buildFunnelResultsCTE(e,t,n,i){const s={binding_key:o`s0.binding_key`,step_0_time:o`s0.step_time`};for(let l=1;l<t.length;l++)s[`step_${l}_time`]=o`s${o.raw(String(l))}.step_time`;let r=o`${o.identifier("step_0")} s0`;for(let l=1;l<t.length;l++)r=o`${r}
|
|
61
|
+
LEFT JOIN ${o.identifier(`step_${l}`)} s${o.raw(String(l))} ON s0.binding_key = s${o.raw(String(l))}.binding_key`;const a=Object.entries(s).map(([l,m])=>o`${m} AS ${o.identifier(l)}`),u=o`SELECT ${o.join(a,o`, `)} FROM ${r}`,c={binding_key:o`binding_key`.as("binding_key"),step_0_time:o`step_0_time`.as("step_0_time")};for(let l=1;l<t.length;l++)c[`step_${l}_time`]=o`${o.identifier(`step_${l}_time`)}`.as(`step_${l}_time`);return i.db.$with("funnel_joined").as(i.db.select(c).from(o`(${u}) as _inner`))}buildAggregationCTE(e,t,n,i,s){const r={};r.step_0_count=o`COUNT(*)`.as("step_0_count");for(let u=1;u<n.length;u++)r[`step_${u}_count`]=o`COUNT(${o.identifier(`step_${u}_time`)})`.as(`step_${u}_count`);if(i.includeTimeMetrics)for(let u=1;u<n.length;u++){const c=o.identifier(`step_${u}_time`),l=o.identifier(`step_${u-1}_time`),m=this.databaseAdapter.buildTimeDifferenceSeconds(o`${c}`,o`${l}`),p=o`${c} IS NOT NULL`;r[`step_${u}_avg_seconds`]=this.databaseAdapter.buildConditionalAggregation("avg",m,p).as(`step_${u}_avg_seconds`),r[`step_${u}_min_seconds`]=this.databaseAdapter.buildConditionalAggregation("min",m,p).as(`step_${u}_min_seconds`),r[`step_${u}_max_seconds`]=this.databaseAdapter.buildConditionalAggregation("max",m,p).as(`step_${u}_max_seconds`);const f=this.databaseAdapter.getCapabilities(),h=this.databaseAdapter.buildPercentile(m,50);h&&f.supportsPercentileSubqueries&&(r[`step_${u}_median_seconds`]=o`(SELECT ${h} FROM ${o.identifier("funnel_joined")} WHERE ${c} IS NOT NULL)`.as(`step_${u}_median_seconds`));const g=this.databaseAdapter.buildPercentile(m,90);g&&f.supportsPercentileSubqueries&&(r[`step_${u}_p90_seconds`]=o`(SELECT ${g} FROM ${o.identifier("funnel_joined")} WHERE ${c} IS NOT NULL)`.as(`step_${u}_p90_seconds`))}const a=s.db.select(r).from(e);return s.db.$with("funnel_metrics").as(a)}}class wn{filterBuilder;dateTimeBuilder;databaseAdapter;constructor(e){this.databaseAdapter=e,this.dateTimeBuilder=new re(e),this.filterBuilder=new be(e,this.dateTimeBuilder)}hasFlow(e){return e.flow!==void 0&&e.flow.startingStep!==void 0&&e.flow.eventDimension!==void 0}validateConfig(e,t){const n=[],i=[],s=this.databaseAdapter.getEngineType(),r=this.databaseAdapter.supportsLateralJoins();if(s==="sqlite")return n.push("Flow queries are not supported on SQLite. Use PostgreSQL or MySQL for flow analysis."),{isValid:!1,errors:n,warnings:i};if(typeof e.bindingKey=="string"){const[a,u]=e.bindingKey.split(".");if(!a||!u)n.push(`Invalid binding key format: ${e.bindingKey}. Expected 'CubeName.dimensionName'`);else{const c=t.get(a);c?c.dimensions?.[u]||n.push(`Binding key dimension not found: ${u} in cube ${a}`):n.push(`Binding key cube not found: ${a}`)}}else if(Array.isArray(e.bindingKey))for(const a of e.bindingKey){const u=t.get(a.cube);if(!u)n.push(`Binding key mapping cube not found: ${a.cube}`);else{const[,c]=a.dimension.split(".");u.dimensions?.[c]||n.push(`Binding key dimension not found: ${c} in cube ${a.cube}`)}}if(typeof e.timeDimension=="string"){const[a,u]=e.timeDimension.split(".");if(!a||!u)n.push(`Invalid time dimension format: ${e.timeDimension}. Expected 'CubeName.dimensionName'`);else{const c=t.get(a);c?c.dimensions?.[u]||n.push(`Time dimension not found: ${u} in cube ${a}`):n.push(`Time dimension cube not found: ${a}`)}}if(e.eventDimension){const[a,u]=e.eventDimension.split(".");if(!a||!u)n.push(`Invalid event dimension format: ${e.eventDimension}. Expected 'CubeName.dimensionName'`);else{const c=t.get(a);c?c.dimensions?.[u]||n.push(`Event dimension not found: ${u} in cube ${a}`):n.push(`Event dimension cube not found: ${a}`)}}else n.push("Event dimension is required for flow analysis");return e.startingStep?(e.startingStep.filter||n.push("Starting step must have at least one filter"),e.startingStep.name||i.push("Starting step has no name - using default")):n.push("Starting step is required for flow analysis"),(e.stepsBefore<0||e.stepsBefore>5)&&n.push(`stepsBefore must be between 0 and 5, got: ${e.stepsBefore}`),(e.stepsAfter<0||e.stepsAfter>5)&&n.push(`stepsAfter must be between 0 and 5, got: ${e.stepsAfter}`),(e.stepsBefore>=4||e.stepsAfter>=4)&&i.push("High step depth (4-5) may impact query performance on large datasets"),e.joinStrategy&&!["auto","lateral","window"].includes(e.joinStrategy)?n.push(`Invalid joinStrategy: ${e.joinStrategy}`):e.joinStrategy==="lateral"&&!r&&n.push("Lateral joins are not supported on this database"),{isValid:n.length===0,errors:n,warnings:i}}buildFlowQuery(e,t,n){if(this.databaseAdapter.getEngineType()==="sqlite")throw new Error("Flow queries are not supported on SQLite. Use PostgreSQL or MySQL for flow analysis.");const s=this.databaseAdapter.supportsLateralJoins(),r=e.joinStrategy??"auto",a=r==="lateral"||r==="auto"&&s;if(r==="lateral"&&!s)throw new Error("Lateral joins are not supported on this database");const u={...e,stepsBefore:e.outputMode==="sunburst"?0:e.stepsBefore},c=this.resolveFlowConfig(u,t,n),l=[],m=this.buildStartingEntitiesCTE(u,c,n);l.push(m);const p=a?this.buildBeforeCTEsLateral(u,c,n):this.buildBeforeCTEsWindow(u,c,n);l.push(...p);const f=a?this.buildAfterCTEsLateral(u,c,n):this.buildAfterCTEsWindow(u,c,n);l.push(...f);const h=this.buildNodesAggregationCTE(u,n);l.push(h);const g=this.buildLinksAggregationCTE(u,n);l.push(g);const y=this.buildFinalResultCTE(n);return l.push(y),n.db.with(...l).select().from(y)}transformResult(e){if(!e||e.length===0)return{nodes:[],links:[]};const t=[],n=[];for(const i of e){const s=i.record_type;s==="node"?t.push({id:String(i.id),name:String(i.name),layer:Number(i.layer),value:Number(i.value)}):s==="link"&&n.push({source:String(i.source_id),target:String(i.target_id),value:Number(i.value)})}return t.sort((i,s)=>i.layer-s.layer),{nodes:t,links:n}}resolveFlowConfig(e,t,n){const i=this.resolveCube(e,t),s=i.sql(n);return{cube:i,cubeBase:s,bindingKeyExpr:this.resolveBindingKey(e,i,n),timeExpr:this.resolveTimeDimension(e,i,n),eventExpr:this.resolveEventDimension(e,i,n),startingStepFilters:this.buildStartingStepFilters(e,i,n)}}resolveCube(e,t){let n;if(typeof e.bindingKey=="string")[n]=e.bindingKey.split(".");else if(Array.isArray(e.bindingKey)&&e.bindingKey.length>0)n=e.bindingKey[0].cube;else throw new Error("Cannot resolve cube for flow query");const i=t.get(n);if(!i)throw new Error(`Cube not found: ${n}`);return i}resolveBindingKey(e,t,n){if(typeof e.bindingKey=="string"){const[,a]=e.bindingKey.split("."),u=t.dimensions?.[a];if(!u)throw new Error(`Binding key dimension not found: ${e.bindingKey}`);return R(u.sql,n)}const i=e.bindingKey.find(a=>a.cube===t.name);if(!i)throw new Error(`No binding key mapping found for cube: ${t.name}`);const[,s]=i.dimension.split("."),r=t.dimensions?.[s];if(!r)throw new Error(`Binding key dimension not found: ${i.dimension}`);return R(r.sql,n)}resolveTimeDimension(e,t,n){if(typeof e.timeDimension=="string"){const[,a]=e.timeDimension.split("."),u=t.dimensions?.[a];if(!u)throw new Error(`Time dimension not found: ${e.timeDimension}`);return R(u.sql,n)}const i=e.timeDimension.find(a=>a.cube===t.name);if(!i)throw new Error(`No time dimension mapping found for cube: ${t.name}`);const[,s]=i.dimension.split("."),r=t.dimensions?.[s];if(!r)throw new Error(`Time dimension not found: ${i.dimension}`);return R(r.sql,n)}resolveEventDimension(e,t,n){const[,i]=e.eventDimension.split("."),s=t.dimensions?.[i];if(!s)throw new Error(`Event dimension not found: ${e.eventDimension}`);return R(s.sql,n)}buildStartingStepFilters(e,t,n){if(!e.startingStep.filter)return[];const i=Array.isArray(e.startingStep.filter)?e.startingStep.filter:[e.startingStep.filter],s=[];for(const r of i){const a=this.buildFilterCondition(r,t,n);a&&s.push(a)}return s}buildFilterCondition(e,t,n){if("and"in e||"or"in e){const u=e,c=[],l=u.and||u.or||[];for(const m of l){const p=this.buildFilterCondition(m,t,n);p&&c.push(p)}return c.length===0?null:c.length===1?c[0]:"and"in e?A(...c):o`(${o.join(c,o` OR `)})`}if("type"in e&&"filters"in e){const u=e,c=[];for(const l of u.filters||[]){const m=this.buildFilterCondition(l,t,n);m&&c.push(m)}return c.length===0?null:c.length===1?c[0]:u.type==="and"?A(...c):o`(${o.join(c,o` OR `)})`}const i=e,[,s]=i.member.split("."),r=t.dimensions?.[s];if(!r)return null;const a=r.type==="time"?R(r.sql,n):typeof r.sql=="function"?r.sql(n):r.sql;return this.filterBuilder.buildFilterCondition(a,i.operator,i.values||[],r,i.dateRange)}buildStartingEntitiesCTE(e,t,n){const{cubeBase:i,bindingKeyExpr:s,timeExpr:r,eventExpr:a,startingStepFilters:u}=t,c=[];i.where&&c.push(i.where),c.push(...u);let l=n.db.select({binding_key:o`${s}`.as("binding_key"),start_time:o`MIN(${r})`.as("start_time"),event_type:o`${a}`.as("event_type"),event_path:o`${a}`.as("event_path")}).from(i.from);if(c.length>0){const m=c.length===1?c[0]:A(...c);l=l.where(m)}return l=l.groupBy(s,a),e.entityLimit&&(l=l.limit(e.entityLimit)),n.db.$with("starting_entities").as(l)}buildBeforeCTEsLateral(e,t,n){const{cubeBase:i,bindingKeyExpr:s,timeExpr:r,eventExpr:a}=t,u=[],c=e.outputMode==="sunburst";for(let l=1;l<=e.stepsBefore;l++){const m=l===1?"starting_entities":`before_step_${l-1}`,p=l===1?"start_time":"step_time",f=`before_step_${l}`,h=[];i.where&&h.push(i.where),h.push(o`${s} = ${o.identifier(m)}.binding_key`,o`${r} < ${o.identifier(m)}.${o.identifier(p)}`);const g=h.length===1?h[0]:A(...h),y=c?o`${a} || ${"→"} || ${o.identifier(m)}.event_path`:o`${a}`,b=n.db.select({binding_key:o`${s}`.as("binding_key"),step_time:o`${r}`.as("step_time"),event_type:o`${a}`.as("event_type"),event_path:y.as("event_path")}).from(i.from).where(g).orderBy(o`${r} DESC`).limit(1),w=n.db.$with(f).as(n.db.select({binding_key:o`e.binding_key`.as("binding_key"),step_time:o`e.step_time`.as("step_time"),event_type:o`e.event_type`.as("event_type"),event_path:o`e.event_path`.as("event_path")}).from(o`${o.identifier(m)}`).crossJoinLateral(b.as("e")));u.push(w)}return u}buildAfterCTEsLateral(e,t,n){const{cubeBase:i,bindingKeyExpr:s,timeExpr:r,eventExpr:a}=t,u=[],c=e.outputMode==="sunburst";for(let l=1;l<=e.stepsAfter;l++){const m=l===1?"starting_entities":`after_step_${l-1}`,p=l===1?"start_time":"step_time",f=`after_step_${l}`,h=[];i.where&&h.push(i.where),h.push(o`${s} = ${o.identifier(m)}.binding_key`,o`${r} > ${o.identifier(m)}.${o.identifier(p)}`);const g=h.length===1?h[0]:A(...h),y=c?o`${o.identifier(m)}.event_path || ${"→"} || ${a}`:o`${a}`,b=n.db.select({binding_key:o`${s}`.as("binding_key"),step_time:o`${r}`.as("step_time"),event_type:o`${a}`.as("event_type"),event_path:y.as("event_path")}).from(i.from).where(g).orderBy(o`${r} ASC`).limit(1),w=n.db.$with(f).as(n.db.select({binding_key:o`e.binding_key`.as("binding_key"),step_time:o`e.step_time`.as("step_time"),event_type:o`e.event_type`.as("event_type"),event_path:o`e.event_path`.as("event_path")}).from(o`${o.identifier(m)}`).crossJoinLateral(b.as("e")));u.push(w)}return u}buildBeforeCTEsWindow(e,t,n){const{cubeBase:i,bindingKeyExpr:s,timeExpr:r,eventExpr:a}=t,u=[],c=e.outputMode==="sunburst";for(let l=1;l<=e.stepsBefore;l++){const m=l===1?"starting_entities":`before_step_${l-1}`,p=l===1?"start_time":"step_time",f=`before_step_${l}`,h=[];i.where&&h.push(i.where),h.push(o`${r} < ${o.identifier(m)}.${o.identifier(p)}`);const g=h.length===1?h[0]:A(...h),y=c?o`${a} || ${"→"} || ${o.identifier(m)}.event_path`:o`${a}`,b=n.db.select({binding_key:o`${s}`.as("binding_key"),step_time:o`${r}`.as("step_time"),event_type:o`${a}`.as("event_type"),event_path:y.as("event_path"),rn:o`ROW_NUMBER() OVER (PARTITION BY ${s} ORDER BY ${r} DESC)`.as("rn")}).from(i.from).innerJoin(o`${o.identifier(m)}`,o`${s} = ${o.identifier(m)}.binding_key`).where(g),w=n.db.select({binding_key:o`binding_key`.as("binding_key"),step_time:o`step_time`.as("step_time"),event_type:o`event_type`.as("event_type"),event_path:o`event_path`.as("event_path")}).from(b.as("ranked")).where(o`rn = 1`);u.push(n.db.$with(f).as(w))}return u}buildAfterCTEsWindow(e,t,n){const{cubeBase:i,bindingKeyExpr:s,timeExpr:r,eventExpr:a}=t,u=[],c=e.outputMode==="sunburst";for(let l=1;l<=e.stepsAfter;l++){const m=l===1?"starting_entities":`after_step_${l-1}`,p=l===1?"start_time":"step_time",f=`after_step_${l}`,h=[];i.where&&h.push(i.where),h.push(o`${r} > ${o.identifier(m)}.${o.identifier(p)}`);const g=h.length===1?h[0]:A(...h),y=c?o`${o.identifier(m)}.event_path || ${"→"} || ${a}`:o`${a}`,b=n.db.select({binding_key:o`${s}`.as("binding_key"),step_time:o`${r}`.as("step_time"),event_type:o`${a}`.as("event_type"),event_path:y.as("event_path"),rn:o`ROW_NUMBER() OVER (PARTITION BY ${s} ORDER BY ${r} ASC)`.as("rn")}).from(i.from).innerJoin(o`${o.identifier(m)}`,o`${s} = ${o.identifier(m)}.binding_key`).where(g),w=n.db.select({binding_key:o`binding_key`.as("binding_key"),step_time:o`step_time`.as("step_time"),event_type:o`event_type`.as("event_type"),event_path:o`event_path`.as("event_path")}).from(b.as("ranked")).where(o`rn = 1`);u.push(n.db.$with(f).as(w))}return u}buildNodesAggregationCTE(e,t){const n=[],i=e.outputMode==="sunburst";for(let a=e.stepsBefore;a>=1;a--){const u=-a,c=`before_step_${a}`;i?n.push(o`
|
|
62
|
+
SELECT
|
|
63
|
+
${o.raw(`'before_${a}_'`)} || event_path AS node_id,
|
|
64
|
+
event_type AS name,
|
|
65
|
+
${o.raw(String(u))} AS layer,
|
|
66
|
+
COUNT(*) AS value
|
|
67
|
+
FROM ${o.identifier(c)}
|
|
68
|
+
GROUP BY event_path, event_type
|
|
69
|
+
`):n.push(o`
|
|
70
|
+
SELECT
|
|
71
|
+
${o.raw(`'before_${a}_'`)} || event_type AS node_id,
|
|
72
|
+
event_type AS name,
|
|
73
|
+
${o.raw(String(u))} AS layer,
|
|
74
|
+
COUNT(*) AS value
|
|
75
|
+
FROM ${o.identifier(c)}
|
|
76
|
+
GROUP BY event_type
|
|
77
|
+
`)}n.push(o`
|
|
78
|
+
SELECT
|
|
79
|
+
${o.raw("'start_'")} || event_type AS node_id,
|
|
80
|
+
event_type AS name,
|
|
81
|
+
0 AS layer,
|
|
82
|
+
COUNT(*) AS value
|
|
83
|
+
FROM starting_entities
|
|
84
|
+
GROUP BY event_type
|
|
85
|
+
`);for(let a=1;a<=e.stepsAfter;a++){const u=a,c=`after_step_${a}`;i?n.push(o`
|
|
86
|
+
SELECT
|
|
87
|
+
${o.raw(`'after_${a}_'`)} || event_path AS node_id,
|
|
88
|
+
event_type AS name,
|
|
89
|
+
${o.raw(String(u))} AS layer,
|
|
90
|
+
COUNT(*) AS value
|
|
91
|
+
FROM ${o.identifier(c)}
|
|
92
|
+
GROUP BY event_path, event_type
|
|
93
|
+
`):n.push(o`
|
|
94
|
+
SELECT
|
|
95
|
+
${o.raw(`'after_${a}_'`)} || event_type AS node_id,
|
|
96
|
+
event_type AS name,
|
|
97
|
+
${o.raw(String(u))} AS layer,
|
|
98
|
+
COUNT(*) AS value
|
|
99
|
+
FROM ${o.identifier(c)}
|
|
100
|
+
GROUP BY event_type
|
|
101
|
+
`)}const s=o.join(n,o` UNION ALL `),r=t.db.select({node_id:o`node_id`.as("node_id"),name:o`name`.as("name"),layer:o`layer`.as("layer"),value:o`value`.as("value")}).from(o`(${s}) AS nodes_union`);return t.db.$with("nodes_agg").as(r)}buildLinksAggregationCTE(e,t){const n=[],i=e.outputMode==="sunburst";for(let a=e.stepsBefore;a>=2;a--){const u=`before_step_${a}`,c=`before_step_${a-1}`;i?n.push(o`
|
|
102
|
+
SELECT
|
|
103
|
+
${o.raw(`'before_${a}_'`)} || f.event_path AS source_id,
|
|
104
|
+
${o.raw(`'before_${a-1}_'`)} || t.event_path AS target_id,
|
|
105
|
+
COUNT(*) AS value
|
|
106
|
+
FROM ${o.identifier(u)} f
|
|
107
|
+
INNER JOIN ${o.identifier(c)} t ON f.binding_key = t.binding_key
|
|
108
|
+
GROUP BY f.event_path, t.event_path
|
|
109
|
+
`):n.push(o`
|
|
110
|
+
SELECT
|
|
111
|
+
${o.raw(`'before_${a}_'`)} || f.event_type AS source_id,
|
|
112
|
+
${o.raw(`'before_${a-1}_'`)} || t.event_type AS target_id,
|
|
113
|
+
COUNT(*) AS value
|
|
114
|
+
FROM ${o.identifier(u)} f
|
|
115
|
+
INNER JOIN ${o.identifier(c)} t ON f.binding_key = t.binding_key
|
|
116
|
+
GROUP BY f.event_type, t.event_type
|
|
117
|
+
`)}e.stepsBefore>=1&&(i?n.push(o`
|
|
118
|
+
SELECT
|
|
119
|
+
${o.raw("'before_1_'")} || b.event_path AS source_id,
|
|
120
|
+
${o.raw("'start_'")} || s.event_type AS target_id,
|
|
121
|
+
COUNT(*) AS value
|
|
122
|
+
FROM before_step_1 b
|
|
123
|
+
INNER JOIN starting_entities s ON b.binding_key = s.binding_key
|
|
124
|
+
GROUP BY b.event_path, s.event_type
|
|
125
|
+
`):n.push(o`
|
|
126
|
+
SELECT
|
|
127
|
+
${o.raw("'before_1_'")} || b.event_type AS source_id,
|
|
128
|
+
${o.raw("'start_'")} || s.event_type AS target_id,
|
|
129
|
+
COUNT(*) AS value
|
|
130
|
+
FROM before_step_1 b
|
|
131
|
+
INNER JOIN starting_entities s ON b.binding_key = s.binding_key
|
|
132
|
+
GROUP BY b.event_type, s.event_type
|
|
133
|
+
`)),e.stepsAfter>=1&&(i?n.push(o`
|
|
134
|
+
SELECT
|
|
135
|
+
${o.raw("'start_'")} || s.event_type AS source_id,
|
|
136
|
+
${o.raw("'after_1_'")} || a.event_path AS target_id,
|
|
137
|
+
COUNT(*) AS value
|
|
138
|
+
FROM starting_entities s
|
|
139
|
+
INNER JOIN after_step_1 a ON s.binding_key = a.binding_key
|
|
140
|
+
GROUP BY s.event_type, a.event_path
|
|
141
|
+
`):n.push(o`
|
|
142
|
+
SELECT
|
|
143
|
+
${o.raw("'start_'")} || s.event_type AS source_id,
|
|
144
|
+
${o.raw("'after_1_'")} || a.event_type AS target_id,
|
|
145
|
+
COUNT(*) AS value
|
|
146
|
+
FROM starting_entities s
|
|
147
|
+
INNER JOIN after_step_1 a ON s.binding_key = a.binding_key
|
|
148
|
+
GROUP BY s.event_type, a.event_type
|
|
149
|
+
`));for(let a=1;a<e.stepsAfter;a++){const u=`after_step_${a}`,c=`after_step_${a+1}`;i?n.push(o`
|
|
150
|
+
SELECT
|
|
151
|
+
${o.raw(`'after_${a}_'`)} || f.event_path AS source_id,
|
|
152
|
+
${o.raw(`'after_${a+1}_'`)} || t.event_path AS target_id,
|
|
153
|
+
COUNT(*) AS value
|
|
154
|
+
FROM ${o.identifier(u)} f
|
|
155
|
+
INNER JOIN ${o.identifier(c)} t ON f.binding_key = t.binding_key
|
|
156
|
+
GROUP BY f.event_path, t.event_path
|
|
157
|
+
`):n.push(o`
|
|
158
|
+
SELECT
|
|
159
|
+
${o.raw(`'after_${a}_'`)} || f.event_type AS source_id,
|
|
160
|
+
${o.raw(`'after_${a+1}_'`)} || t.event_type AS target_id,
|
|
161
|
+
COUNT(*) AS value
|
|
162
|
+
FROM ${o.identifier(u)} f
|
|
163
|
+
INNER JOIN ${o.identifier(c)} t ON f.binding_key = t.binding_key
|
|
164
|
+
GROUP BY f.event_type, t.event_type
|
|
165
|
+
`)}if(n.length===0){const a=t.db.select({source_id:o`NULL`.as("source_id"),target_id:o`NULL`.as("target_id"),value:o`0`.as("value")}).from(o`(SELECT 1) AS empty`).where(o`1 = 0`);return t.db.$with("links_agg").as(a)}const s=o.join(n,o` UNION ALL `),r=t.db.select({source_id:o`source_id`.as("source_id"),target_id:o`target_id`.as("target_id"),value:o`value`.as("value")}).from(o`(${s}) AS links_union`);return t.db.$with("links_agg").as(r)}buildFinalResultCTE(e){const t=o`
|
|
166
|
+
SELECT
|
|
167
|
+
'node' AS record_type,
|
|
168
|
+
node_id AS id,
|
|
169
|
+
name AS name,
|
|
170
|
+
layer AS layer,
|
|
171
|
+
value AS value,
|
|
172
|
+
NULL AS source_id,
|
|
173
|
+
NULL AS target_id
|
|
174
|
+
FROM nodes_agg
|
|
175
|
+
UNION ALL
|
|
176
|
+
SELECT
|
|
177
|
+
'link' AS record_type,
|
|
178
|
+
NULL AS id,
|
|
179
|
+
NULL AS name,
|
|
180
|
+
NULL AS layer,
|
|
181
|
+
value AS value,
|
|
182
|
+
source_id AS source_id,
|
|
183
|
+
target_id AS target_id
|
|
184
|
+
FROM links_agg
|
|
185
|
+
WHERE source_id IS NOT NULL
|
|
186
|
+
`,n=e.db.select({record_type:o`record_type`.as("record_type"),id:o`id`.as("id"),name:o`name`.as("name"),layer:o`layer`.as("layer"),value:o`value`.as("value"),source_id:o`source_id`.as("source_id"),target_id:o`target_id`.as("target_id")}).from(o`(${t}) AS final_union`);return e.db.$with("final_result").as(n)}}function Ze(d){return Array.isArray(d)}function dt(d){return typeof d=="object"&&d!==null&&"cube"in d}function et(d){if(dt(d))return d.cube;const e=d.indexOf(".");if(e===-1)throw new Error(`Invalid time dimension format: ${d}. Expected 'CubeName.dimensionName'`);return d.substring(0,e)}function tt(d){if(dt(d))return d.dimension;const e=d.indexOf(".");if(e===-1)throw new Error(`Invalid time dimension format: ${d}. Expected 'CubeName.dimensionName'`);return d.substring(e+1)}class $n{constructor(e){this.databaseAdapter=e,this.dateTimeBuilder=new re(e),this.filterBuilder=new be(e,this.dateTimeBuilder)}filterBuilder;dateTimeBuilder;hasRetention(e){return e.retention!==void 0&&e.retention.timeDimension!=null&&e.retention.bindingKey!=null}validateConfig(e,t){const n=[];try{const r=et(e.timeDimension),a=tt(e.timeDimension),u=t.get(r);u?u.dimensions?.[a]||n.push(`Time dimension not found: ${a} in cube ${r}`):n.push(`Cube not found: ${r}`)}catch{n.push(`Invalid time dimension format: ${e.timeDimension}`)}if(Ze(e.bindingKey))for(const r of e.bindingKey){const a=t.get(r.cube);if(!a)n.push(`Binding key mapping cube not found: ${r.cube}`);else{const u=this.extractDimensionName(r.dimension);a.dimensions?.[u]||n.push(`Binding key dimension not found: ${u} in cube ${r.cube}`)}}else{const[r,a]=e.bindingKey.split(".");if(!r||!a)n.push(`Invalid binding key format: ${e.bindingKey}. Expected 'CubeName.dimensionName'`);else{const u=t.get(r);u?u.dimensions?.[a]||n.push(`Binding key dimension not found: ${a} in cube ${r}`):n.push(`Binding key cube not found: ${r}`)}}if(e.breakdownDimensions&&e.breakdownDimensions.length>0)for(const r of e.breakdownDimensions){const[a,u]=r.split(".");if(!a||!u)n.push(`Invalid breakdown dimension format: ${r}. Expected 'CubeName.dimensionName'`);else{const c=t.get(a);c?c.dimensions?.[u]||n.push(`Breakdown dimension not found: ${u} in cube ${a}`):n.push(`Breakdown dimension cube not found: ${a}`)}}if(e.periods<1&&n.push("Periods must be at least 1"),e.periods>52&&n.push("Periods cannot exceed 52 (performance limit)"),["day","week","month"].includes(e.granularity)||n.push(`Invalid granularity: ${e.granularity}`),["classic","rolling"].includes(e.retentionType)||n.push(`Invalid retention type: ${e.retentionType}`),!e.dateRange)n.push("Date range is required");else{if(!e.dateRange.start)n.push("Date range start is required");else{const r=new Date(e.dateRange.start);isNaN(r.getTime())&&n.push("Invalid date range start format")}if(!e.dateRange.end)n.push("Date range end is required");else{const r=new Date(e.dateRange.end);isNaN(r.getTime())&&n.push("Invalid date range end format")}if(e.dateRange.start&&e.dateRange.end){const r=new Date(e.dateRange.start),a=new Date(e.dateRange.end);!isNaN(r.getTime())&&!isNaN(a.getTime())&&r>a&&n.push("Date range start must be before or equal to end")}}return{isValid:n.length===0,errors:n}}buildRetentionQuery(e,t,n){const i=this.resolveConfig(e,t,n),s=i.breakdowns.length,r=this.buildCohortBaseCTE(e,i,n),a=this.buildActivityPeriodsCTE(e,i,n),u=this.buildCohortSizesCTE(e,n,s),c=this.buildRetentionCountsCTE(e,n,s),l=i.breakdowns.length>0,m={period:o`rc.period_number`.as("period"),cohort_size:o`cs.cohort_size`.as("cohort_size"),retained_users:o`rc.retained_users`.as("retained_users"),retention_rate:o`CAST(rc.retained_users AS NUMERIC) / NULLIF(cs.cohort_size, 0)`.as("retention_rate")};for(let h=0;h<i.breakdowns.length;h++)m[`breakdown_${h}`]=o.raw(`rc.breakdown_${h}`).as(`breakdown_${h}`);let p=n.db.with(r,a,u,c).select(m).from(o`retention_counts rc`);if(l){const h=i.breakdowns.map((y,b)=>o`COALESCE(CAST(rc.breakdown_${o.raw(String(b))} AS TEXT), '') = COALESCE(CAST(cs.breakdown_${o.raw(String(b))} AS TEXT), '')`),g=h.length===1?h[0]:o.join(h,o` AND `);p=p.innerJoin(o`cohort_sizes cs`,g)}else p=p.innerJoin(o`cohort_sizes cs`,o`1 = 1`);const f=[];for(let h=0;h<i.breakdowns.length;h++)f.push(o.raw(`rc.breakdown_${h}`));return f.push(o`rc.period_number`),p=p.orderBy(...f),p}transformResult(e,t){const n=t.breakdownDimensions||[],i=n.length>0;return e.map(s=>{const r={period:Number(s.period),cohortSize:Number(s.cohort_size),retainedUsers:Number(s.retained_users),retentionRate:s.retention_rate!==null?Number(s.retention_rate):0};if(i){const a={};for(let u=0;u<n.length;u++){const c=n[u],l=s[`breakdown_${u}`];a[c]=l!==void 0?String(l):null}r.breakdownValues=a}return r})}resolveConfig(e,t,n){const i=et(e.timeDimension),s=tt(e.timeDimension),r=t.get(i);if(!r)throw new Error(`Cube not found: ${i}`);const a=r.dimensions?.[s];if(!a)throw new Error(`Time dimension not found: ${s}`);const u=R(a.sql,n),c=this.resolveBindingKey(e.bindingKey,r,t,n),l=this.buildFilterConditions(e.cohortFilters,r,t,n),m=this.buildFilterConditions(e.activityFilters,r,t,n),p=[];if(e.breakdownDimensions&&e.breakdownDimensions.length>0)for(const f of e.breakdownDimensions){const[h,g]=f.split("."),y=t.get(h);if(y&&y.dimensions?.[g]){const b=R(y.dimensions[g].sql,n);p.push({dimension:f,expr:b})}}return{cube:r,bindingKeyExpr:c,timeExpr:u,cohortFilterConditions:l,activityFilterConditions:m,breakdowns:p}}resolveBindingKey(e,t,n,i){if(Ze(e)){const c=e.find(f=>f.cube===t.name);if(!c)throw new Error(`No binding key mapping found for cube: ${t.name}`);const l=this.extractDimensionName(c.dimension),m=n.get(c.cube);if(!m)throw new Error(`Binding key cube not found: ${c.cube}`);const p=m.dimensions?.[l];if(!p)throw new Error(`Binding key dimension not found: ${c.dimension}`);return R(p.sql,i)}const[s,r]=e.split("."),a=n.get(s);if(!a)throw new Error(`Binding key cube not found: ${s}`);const u=a.dimensions?.[r];if(!u)throw new Error(`Binding key dimension not found: ${e}`);return R(u.sql,i)}buildFilterConditions(e,t,n,i){if(!e)return[];const s=Array.isArray(e)?e:[e],r=[];for(const a of s){const u=this.buildSingleFilterCondition(a,t,n,i);u&&r.push(u)}return r}buildSingleFilterCondition(e,t,n,i){if("and"in e||"or"in e){const m=e,p=[],f="and"in m&&!!m.and,h=m.and||m.or||[];for(const g of h){const y=this.buildSingleFilterCondition(g,t,n,i);y&&p.push(y)}return p.length===0?null:p.length===1?p[0]:f?A(...p):o`(${o.join(p,o` OR `)})`}const s=e,[r,a]=s.member.split("."),u=n.get(r);if(!u)return null;const c=u.dimensions?.[a];if(!c)return null;const l=c.type==="time"?R(c.sql,i):typeof c.sql=="function"?c.sql(i):c.sql;return this.filterBuilder.buildFilterCondition(l,s.operator,s.values||[],c,s.dateRange)}buildCohortBaseCTE(e,t,n){const i=t.cube.sql(n),s=[];if(i.where&&s.push(i.where),s.push(...t.cohortFilterConditions),e.dateRange){const l=this.buildDateRangeCondition(t.timeExpr,e.dateRange);s.push(l)}const r=this.databaseAdapter.buildTimeDimension(e.granularity,t.timeExpr),a={binding_key:o`${t.bindingKeyExpr}`.as("binding_key"),cohort_entry:o`MIN(${r})`.as("cohort_entry")};for(let l=0;l<t.breakdowns.length;l++){const{expr:m}=t.breakdowns[l];a[`breakdown_${l}`]=o`MIN(${m})`.as(`breakdown_${l}`)}let u=n.db.select(a).from(i.from);if(s.length>0){const l=s.length===1?s[0]:A(...s);u=u.where(l)}const c=[t.bindingKeyExpr];for(let l=0;l<t.breakdowns.length;l++)c.push(t.breakdowns[l].expr);if(u=u.groupBy(...c),e.dateRange){const l=this.buildDateRangeHavingCondition(r,e.dateRange);u=u.having(l)}return n.db.$with("cohort_base").as(u)}buildDateRangeCondition(e,t){return o`${e} >= ${t.start}::date AND ${e} < (${t.end}::date + interval '1 day')`}buildDateRangeHavingCondition(e,t){return o`MIN(${e}) >= ${t.start}::date AND MIN(${e}) < (${t.end}::date + interval '1 day')`}buildActivityPeriodsCTE(e,t,n){const i=t.cube.sql(n),s=[];i.where&&s.push(i.where),s.push(...t.activityFilterConditions),s.push(o`${t.timeExpr} >= cohort_base.cohort_entry`);const r=this.databaseAdapter.buildTimeDimension(e.granularity,t.timeExpr),a=this.buildPeriodNumberExpression(o`cohort_base.cohort_entry`,r,e.granularity),u={binding_key:o`cohort_base.binding_key`.as("binding_key"),period_number:a.as("period_number")};for(let m=0;m<t.breakdowns.length;m++)u[`breakdown_${m}`]=o.raw(`cohort_base.breakdown_${m}`).as(`breakdown_${m}`);let c=n.db.select(u).from(i.from).innerJoin(o`cohort_base`,o`${t.bindingKeyExpr} = cohort_base.binding_key`);if(s.length>0){const m=s.length===1?s[0]:A(...s);c=c.where(m)}const l=[o`cohort_base.binding_key`,a];for(let m=0;m<t.breakdowns.length;m++)l.push(o.raw(`cohort_base.breakdown_${m}`));return c=c.groupBy(...l),n.db.$with("activity_periods").as(c)}buildCohortSizesCTE(e,t,n){if(n>0){const r={cohort_size:o`COUNT(*)`.as("cohort_size")},a=[];for(let c=0;c<n;c++)r[`breakdown_${c}`]=o.raw(`breakdown_${c}`).as(`breakdown_${c}`),a.push(o.raw(`breakdown_${c}`));const u=t.db.select(r).from(o`cohort_base`).groupBy(...a);return t.db.$with("cohort_sizes").as(u)}const s=t.db.select({cohort_size:o`COUNT(*)`.as("cohort_size")}).from(o`cohort_base`);return t.db.$with("cohort_sizes").as(s)}buildRetentionCountsCTE(e,t,n){let i;if(e.retentionType==="rolling")i=this.buildRollingRetentionCountsQuery(e,t,n);else{const s={period_number:o`period_number`.as("period_number"),retained_users:o`COUNT(DISTINCT binding_key)`.as("retained_users")},r=[o`period_number`];for(let a=0;a<n;a++)s[`breakdown_${a}`]=o.raw(`breakdown_${a}`).as(`breakdown_${a}`),r.push(o.raw(`breakdown_${a}`));i=t.db.select(s).from(o`activity_periods`).where(o`period_number >= 0 AND period_number <= ${e.periods}`).groupBy(...r)}return t.db.$with("retention_counts").as(i)}buildRollingRetentionCountsQuery(e,t,n){const i=[];for(let l=0;l<n;l++)i.push(`breakdown_${l}`);const s=i.length>0?`, ${i.join(", ")}`:"",r=o`(
|
|
187
|
+
SELECT
|
|
188
|
+
binding_key,
|
|
189
|
+
${o.raw(i.map(l=>`${l}`).join(", ")+(i.length>0?",":""))}
|
|
190
|
+
MAX(period_number) as max_period
|
|
191
|
+
FROM activity_periods
|
|
192
|
+
WHERE period_number >= 0 AND period_number <= ${e.periods}
|
|
193
|
+
GROUP BY binding_key${o.raw(s)}
|
|
194
|
+
)`,a=this.databaseAdapter.buildPeriodSeriesSubquery(e.periods),u={period_number:o`p.period_number`.as("period_number"),retained_users:o`COUNT(DISTINCT CASE WHEN ump.max_period >= p.period_number THEN ump.binding_key END)`.as("retained_users")},c=[o`p.period_number`];for(let l=0;l<n;l++)u[`breakdown_${l}`]=o.raw(`ump.breakdown_${l}`).as(`breakdown_${l}`),c.push(o.raw(`ump.breakdown_${l}`));return t.db.select(u).from(o`${r} ump`).crossJoin(a).groupBy(...c)}buildPeriodNumberExpression(e,t,n){return this.databaseAdapter.buildDateDiffPeriods(e,t,n)}extractDimensionName(e){const t=e.split(".");return t.length>1?t[1]:t[0]}}class Tn{constructor(e){this.queryPlanner=e}plan(e,t,n){return this.planWithAnalysis(e,t,n).plan}planWithAnalysis(e,t,n){const i=Array.from(this.queryPlanner.analyzeCubeUsage(t));if(i.length===0)throw new Error("No cubes found in query");const s=this.queryPlanner.analyzePrimaryCube(i,t,e),r=s.selectedCube,a=e.get(r);if(!a)throw new Error(`Primary cube '${r}' not found`);const c=i.filter(C=>C!==r).map(C=>this.queryPlanner.analyzeJoinPathForTarget(e,r,C,t)),l=i.length>1?this.queryPlanner.buildJoinPlanForPrimary(e,a,i,n,t):[],m=i.length>1?this.queryPlanner.buildPreAggregationCTEs(e,a,l,t,n)??[]:[],p=this.queryPlanner.buildWarnings(t,m),f=this.buildSourceFromPhases(a,l,m,e,t,n),h=f.source,g=this.buildQueryNode(h,t,e,p),y=this.buildPreAggregationAnalysis(m),b=new Map;for(const C of i){const $=e.get(C);$&&b.set(C,$)}const w=j.hasPostAggregationWindows(t.measures??[],b),T=[...c.filter(C=>!C.pathFound&&C.error).map(C=>C.error),...p.map(C=>C.message)],S={timestamp:new Date().toISOString(),cubeCount:i.length,cubesInvolved:[...i].sort(),primaryCube:s,joinPaths:c,preAggregations:y,querySummary:{queryType:m.length>0?"multi_cube_cte":i.length>1?"multi_cube_join":"single_cube",measureStrategy:f.strategy,joinCount:l.length,cteCount:m.length,hasPreAggregation:m.length>0,hasWindowFunctions:w},warnings:T.length>0?T:void 0,planningTrace:{steps:[{phase:"cube_usage",decision:`Identified ${i.length} cube${i.length===1?"":"s"} from query members`,details:{cubesInvolved:[...i].sort()}},{phase:"primary_cube_selection",decision:`Selected '${s.selectedCube}' as primary cube (${s.reason})`,details:{selectedCube:s.selectedCube,reason:s.reason,candidates:s.candidates?.map(C=>C.cubeName)}},{phase:"join_planning",decision:`Planned ${l.length} join${l.length===1?"":"s"}`,details:{joinCount:l.length,joinTargets:l.map(C=>C.cube.name),pathSelection:c.map(C=>({targetCube:C.targetCube,strategy:C.selection?.strategy,selectedRank:C.selection?.selectedRank,selectedScore:C.selection?.selectedScore}))}},{phase:"cte_planning",decision:`Planned ${m.length} pre-aggregation CTE${m.length===1?"":"s"}`,details:{cteCount:m.length,cubes:m.map(C=>C.cube.name)}},{phase:"measure_strategy",decision:`Selected '${f.strategy}' measure strategy`,details:{strategy:f.strategy,regularMeasures:f.classification.regular.map(C=>C.name),multipliedMeasures:f.classification.multiplied.map(C=>C.name),deduplicationSafeMeasures:f.classification.deduplicationSafe.map(C=>C.name),sourceType:h.type}},{phase:"warnings",decision:p.length>0?`Generated ${p.length} planning warning${p.length===1?"":"s"}`:"No planning warnings generated",details:{warningCodes:p.map(C=>C.code)}}]}};return{plan:g,analysis:S}}buildSourceFromPhases(e,t,n,i,s,r){const a=this.tryBuildMultiFactMergeSource(s,i,r);if(a){const p={regular:this.buildMeasureRefs(s,i),multiplied:[],deduplicationSafe:[]};return{source:a,strategy:"multiFactMerge",classification:p}}const u=this.buildSimpleSourceFromPhases(e,t,n,i,s),c=this.classifyMeasuresForStrategy(u.schema.measures,n),l=this.selectMeasureStrategy(c,s,i);return l==="keysDeduplication"?{source:this.buildKeysDeduplicationSource(u,c),strategy:l,classification:c}:{source:u,strategy:l,classification:c}}buildSimpleSourceFromPhases(e,t,n,i,s){const r=this.buildMeasureRefs(s,i),a=this.buildDimensionRefs(s,i),u=this.buildTimeDimensionRefs(s,i),c=this.toCubeRef(e),l=t.map(f=>({target:this.toCubeRef(f.cube),alias:f.alias,joinType:f.joinType,joinCondition:f.joinCondition,relationship:f.relationship,junctionTable:f.junctionTable})),m=n.map(f=>{const h=this.toCubeRef(f.cube);return{type:"ctePreAggregate",schema:this.buildCTESchema(f,i),cube:h,alias:f.alias,cteAlias:f.cteAlias,joinKeys:f.joinKeys,measures:f.measures,propagatingFilters:f.propagatingFilters,downstreamJoinKeys:f.downstreamJoinKeys,intermediateJoins:f.intermediateJoins,cteType:f.cteType??"aggregate",cteReason:f.cteReason??"hasMany"}});return{type:"simpleSource",schema:{measures:r,dimensions:a,timeDimensions:u},primaryCube:c,joins:l,ctes:m}}tryBuildMultiFactMergeSource(e,t,n){if(!e.measures||e.measures.length<2)return null;const i=new Set;for(const h of e.measures){const[g]=h.split(".");g&&i.add(g)}if(i.size<2)return null;const s=new Set;for(const h of e.dimensions??[]){const[g]=h.split(".");g&&s.add(g)}for(const h of e.timeDimensions??[]){const[g]=h.dimension.split(".");g&&s.add(g)}if(s.size!==1)return null;const r=Array.from(s)[0];if(i.has(r)||!t.get(r))return null;const u=Array.from(i);if(!u.every(h=>this.hasDirectJoinToSharedDimension(t.get(h),r)))return null;const l=this.buildDimensionRefs(e,t),m=this.buildTimeDimensionRefs(e,t),p={measures:this.buildMeasureRefs(e,t),dimensions:l,timeDimensions:m},f=[];for(const h of u){const g=(e.measures??[]).filter(T=>T.startsWith(`${h}.`)),y=new Set([h,r]),b={measures:g,dimensions:e.dimensions,timeDimensions:e.timeDimensions,filters:this.projectFiltersToAllowedCubes(e.filters,y)},w=this.buildGroupQueryNode(b,t,n);if(!w)return null;f.push(w)}return f.length<2?null:{type:"multiFactMerge",schema:p,groups:f,sharedDimensions:l,mergeStrategy:"fullJoin"}}hasDirectJoinToSharedDimension(e,t){if(!e?.joins)return!1;for(const[,n]of Object.entries(e.joins)){const i=n.targetCube,s=typeof i=="function"?i():i;if(!(!s||s.name!==t)&&(n.relationship==="belongsTo"||n.relationship==="hasOne"))return!0}return!1}buildGroupQueryNode(e,t,n){const i=Array.from(this.queryPlanner.analyzeCubeUsage(e));if(i.length===0)return null;const s=this.queryPlanner.analyzePrimaryCube(i,e,t),r=t.get(s.selectedCube);if(!r)return null;const a=i.length>1?this.queryPlanner.buildJoinPlanForPrimary(t,r,i,n,e):[],u=i.length>1?this.queryPlanner.buildPreAggregationCTEs(t,r,a,e,n)??[]:[],c=this.queryPlanner.buildWarnings(e,u),l=this.buildSourceFromPhases(r,a,u,t,e,n);return this.buildQueryNode(l.source,e,t,c)}projectFiltersToAllowedCubes(e,t){if(!e||e.length===0)return;const n=e.map(i=>this.projectFilterNodeToAllowedCubes(i,t)).filter(i=>!!i);return n.length>0?n:void 0}projectFilterNodeToAllowedCubes(e,t){if("member"in e){const[n]=e.member.split(".");return n&&t.has(n)?e:null}if("and"in e){const n=(e.and??[]).map(i=>this.projectFilterNodeToAllowedCubes(i,t)).filter(i=>!!i);return n.length===0?null:n.length===1?n[0]:{and:n}}if("or"in e){const n=(e.or??[]).map(i=>this.projectFilterNodeToAllowedCubes(i,t)).filter(i=>!!i);return n.length===0?null:n.length===1?n[0]:{or:n}}return null}classifyMeasuresForStrategy(e,t){const n={regular:[],multiplied:[],deduplicationSafe:[]},i=new Set(t.filter(s=>s.cteReason==="fanOutPrevention").map(s=>s.cube.name));for(const s of e){const r=s.cube.cube,a=r.measures?.[s.localName];if(!a||!i.has(r.name)){n.regular.push(s);continue}this.isDeduplicationSafeMeasure(a)?n.deduplicationSafe.push(s):n.multiplied.push(s)}return n}selectMeasureStrategy(e,t,n){return e.multiplied.length===0?"simple":e.multiplied.every(s=>this.getPrimaryKeyColumns(s.cube.cube).length>0)&&this.isKeysDeduplicationExecutionSupported(e,t,n)?"keysDeduplication":"ctePreAggregateFallback"}isKeysDeduplicationExecutionSupported(e,t,n){const i=new Set(e.multiplied.map(u=>u.cube.name));if(i.size!==1)return!1;const s=Array.from(i)[0],r=t.measures??[];if(r.length===0)return!1;const a=n.get(s);if(!a)return!1;for(const u of r){const[c,l]=u.split(".");if(c!==s){const f=n.get(c)?.measures?.[l];if(!f||!["sum","count","number","min","max"].includes(f.type))return!1;continue}const m=a.measures?.[l];if(!m||!["sum","count","number","min","max","avg"].includes(m.type))return!1}return!this.queryHasMeasureFilter(t,s,a)}queryHasMeasureFilter(e,t,n){const i=r=>{const[a,u]=r.split(".");return a===t&&!!n.measures?.[u]},s=r=>{if(!r)return!1;for(const a of r){if("and"in a){if(s(a.and))return!0;continue}if("or"in a){if(s(a.or))return!0;continue}if("member"in a&&i(a.member))return!0}return!1};return s(e.filters)}buildKeysDeduplicationSource(e,t){const n=this.deduplicateColumnRefs(t.multiplied.flatMap(s=>this.getPrimaryKeyColumns(s.cube.cube))),i=t.regular.length>0?t.regular.map(s=>s.name):void 0;return{type:"keysDeduplication",schema:e.schema,keysSource:e,measureSource:e,joinOn:n,regularMeasures:i}}isDeduplicationSafeMeasure(e){return e.type==="countDistinct"||e.type==="countDistinctApprox"}getPrimaryKeyColumns(e){const t=[];for(const[n,i]of Object.entries(e.dimensions??{}))!i.primaryKey||typeof i.sql=="function"||t.push({column:i.sql,alias:`${e.name}.${n}`});return t}deduplicateColumnRefs(e){const t=new Map;for(const n of e){const i=n.alias??String(n.column?.name??"");t.has(i)||t.set(i,n)}return Array.from(t.values())}buildQueryNode(e,t,n,i){const s=this.buildMeasureRefs(t,n),r=this.buildDimensionRefs(t,n),a=this.buildTimeDimensionRefs(t,n),u=this.buildOrderByRefs(t),c=t.filters??[];return{type:"query",schema:{measures:s,dimensions:r,timeDimensions:a},source:e,dimensions:r,measures:s,filters:c,timeDimensions:a,orderBy:u,limit:t.limit,offset:t.offset,warnings:i}}buildPreAggregationAnalysis(e){return e.map(t=>({cubeName:t.cube.name,cteAlias:t.cteAlias,reason:t.cteReason==="fanOutPrevention"?`Potential fan-out from hasMany joins - pre-aggregate ${t.cube.name} to preserve correctness`:`hasMany relationship requires pre-aggregation for ${t.cube.name}`,reasonType:t.cteReason,measures:t.measures,joinKeys:t.joinKeys.map(n=>({sourceColumn:n.sourceColumn,targetColumn:n.targetColumn})),cteType:t.cteType}))}buildMeasureRefs(e,t){return e.measures?e.measures.map(n=>{const[i,s]=n.split("."),r=t.get(i);if(!r)throw new Error(`Cube '${i}' not found for measure '${n}'`);return{name:n,cube:this.toCubeRef(r),localName:s}}):[]}buildDimensionRefs(e,t){return e.dimensions?e.dimensions.map(n=>{const[i,s]=n.split("."),r=t.get(i);if(!r)throw new Error(`Cube '${i}' not found for dimension '${n}'`);return{name:n,cube:this.toCubeRef(r),localName:s}}):[]}buildTimeDimensionRefs(e,t){return e.timeDimensions?e.timeDimensions.map(n=>{const[i,s]=n.dimension.split("."),r=t.get(i);if(!r)throw new Error(`Cube '${i}' not found for time dimension '${n.dimension}'`);return{name:n.dimension,cube:this.toCubeRef(r),localName:s,granularity:n.granularity,dateRange:n.dateRange,fillMissingDates:n.fillMissingDates,compareDateRange:n.compareDateRange}}):[]}buildOrderByRefs(e){return e.order?Object.entries(e.order).map(([t,n])=>({name:t,direction:n})):[]}toCubeRef(e){return{name:e.name,cube:e}}buildCTESchema(e,t){return{measures:e.measures.map(i=>{const[s,r]=i.split("."),a=t.get(s);return{name:i,cube:{name:s,cube:a},localName:r}}),dimensions:[],timeDimensions:[]}}}class En{name="identity";optimise(e){return e}}function Sn(d,e,t,n){const i=new Map;if(d.preAggregationCTEs&&d.preAggregationCTEs.length>0){for(const u of d.preAggregationCTEs)if(u.propagatingFilters&&u.propagatingFilters.length>0)for(const c of u.propagatingFilters){const l=c.sourceCube.name;if(!i.has(l)){const p={filters:c.filters},f=new Map([[l,c.sourceCube]]),h=n.queryBuilder.buildWhereConditions(f,p,t);i.set(l,h)}const m=i.get(l);m&&m.length>0&&(c.preBuiltFilterSQL=m.length===1?m[0]:A(...m))}}const s=[],r=new Map,a=new Map;if(d.preAggregationCTEs&&d.preAggregationCTEs.length>0)for(const u of d.preAggregationCTEs){const c=n.cteBuilder.buildPreAggregationCTE(u,e,t,d,i);if(c&&(s.push(c),r.set(u.cube.name,u.cteAlias),u.downstreamJoinKeys))for(const l of u.downstreamJoinKeys)a.set(l.targetCubeName,{cteAlias:u.cteAlias,joinKeys:l.joinKeys})}return{preBuiltFilterMap:i,ctes:s,cteAliasMap:r,downstreamCubeMap:a}}function Dn(d,e,t,n,i,s){if(t.measures)for(const r of t.measures){const[a,u]=r.split("."),c=i.get(a);if(!c?.measures?.[u])continue;const l=c.measures[u];if(!j.isPostAggregationWindow(l))continue;const m=j.getWindowBaseMeasure(l,a);if(!m)continue;const[p,f]=m.split("."),h=i.get(p);if(!h?.measures?.[f])continue;const g=h.measures[f],y=e.preAggregationCTEs?.find(T=>T.cube?.name===p&&T.measures?.includes(m));let b;if(y){const T=o`${o.identifier(y.cteAlias)}.${o.identifier(f)}`;b=o`sum(${T})`}else b=s.queryBuilder.buildMeasureExpression(g,n,h);d[m]||(d[m]=o`${b}`.as(m));const w=Nn(l,b,t,n,c,e,s);w&&(d[r]=o`${w}`.as(r))}}function Nn(d,e,t,n,i,s,r){const a=d.windowConfig||{},u=(f,h)=>{if(!s.preAggregationCTEs)return null;const g=s.preAggregationCTEs.find(y=>y.cube?.name===f);return g&&g.cteAlias?o`${o.identifier(g.cteAlias)}.${o.identifier(h)}`:null};let c;if(a.orderBy&&a.orderBy.length>0)c=a.orderBy.map(f=>{const h=f.field.includes(".")?f.field.split(".")[1]:f.field;if(t.timeDimensions)for(const b of t.timeDimensions){const[w,T]=b.dimension.split(".");if(T===h){const S=u(w,h);if(S)return{field:S,direction:f.direction};const C=i.dimensions?.[T];if(C)return{field:r.queryBuilder.buildTimeDimensionExpression(C.sql,b.granularity,n),direction:f.direction}}}const g=i.dimensions?.[h];if(g)return{field:R(g.sql,n),direction:f.direction};const y=a.measure?.includes(".")?a.measure.split(".")[1]:a.measure;return h===y||f.field===a.measure?{field:e,direction:f.direction}:null}).filter(f=>f!==null);else if(t.timeDimensions&&t.timeDimensions.length>0){const f=t.timeDimensions[0],[h,g]=f.dimension.split("."),y=u(h,g);if(y)c=[{field:y,direction:"asc"}];else{const b=i.name===h?i:void 0;if(b?.dimensions?.[g]){const w=b.dimensions[g];c=[{field:r.queryBuilder.buildTimeDimensionExpression(w.sql,f.granularity,n),direction:"asc"}]}}}let l;a.partitionBy&&a.partitionBy.length>0&&(l=a.partitionBy.map(f=>{const h=f.includes(".")?f.split(".")[1]:f,g=i.dimensions?.[h];return g?R(g.sql,n):null}).filter(f=>f!==null));const m=r.databaseAdapter.buildWindowFunction(d.type,e,l,c,{offset:a.offset,defaultValue:a.defaultValue,nTile:a.nTile,frame:a.frame});if(!m)return null;switch(a.operation||j.getDefaultWindowOperation(d.type)){case"difference":return o`${e} - ${m}`;case"ratio":return o`${e} / NULLIF(${m}, 0)`;case"percentChange":return o`((${e} - ${m}) / NULLIF(${m}, 0)) * 100`;default:return m}}function An(d,e,t,n,i){const r={...i.queryBuilder.buildSelections(d.joinCubes.length>0?n:d.primaryCube,e,t)};if(d.preAggregationCTEs)for(const a of d.preAggregationCTEs){const u=a.cube.name;for(const c of a.measures){if(!r[c])continue;const[,l]=c.split("."),m=n.get(u);if(!m?.measures?.[l])continue;const p=m.measures[l],f=o`${o.identifier(a.cteAlias)}.${o.identifier(l)}`;let h;if(p.type==="calculated"&&p.calculatedSql)h=i.queryBuilder.buildCTECalculatedMeasure(p,m,a,n,t);else{const g=a.cteReason==="fanOutPrevention",y=_n(a,e,n),b=g||y;switch(p.type){case"count":case"countDistinct":case"sum":h=b?H(f):V(f);break;case"avg":h=b?H(f):i.databaseAdapter.buildAvg(f);break;case"min":h=ae(f);break;case"max":h=H(f);break;case"number":h=H(f);break;default:h=b?H(f):V(f)}}r[c]=o`${h}`.as(c)}for(const c in r){const[l,m]=c.split(".");if(l!==u)continue;const p=n.get(u),f=p&&p.dimensions?.[m],h=c.startsWith(u+".");if(!f&&!h)continue;let g=a.joinKeys.find(y=>y.targetColumn===m);if(!g&&p?.dimensions?.[m]){const y=p.dimensions[m].sql;g=a.joinKeys.find(b=>b.targetColumnObj===y)}g?r[c]=o`${o.identifier(a.cteAlias)}.${o.identifier(m)}`.as(c):h&&p?.dimensions?.[m]&&(r[c]=o`${o.identifier(a.cteAlias)}.${o.identifier(m)}`.as(c))}}return Dn(r,d,e,t,n,i),r}function _n(d,e,t){return d.cteReason!=="hasMany"||d.downstreamJoinKeys&&d.downstreamJoinKeys.length>0||d.intermediateJoins&&d.intermediateJoins.length>0||!!!(e.dimensions&&e.dimensions.length>0||e.timeDimensions&&e.timeDimensions.length>0)||!!(e.dimensions?.some(s=>s.startsWith(`${d.cube.name}.`))||e.timeDimensions?.some(s=>s.dimension.startsWith(`${d.cube.name}.`)))?!1:d.joinKeys.length>0&&d.joinKeys.every(s=>!!s.sourceColumnObj&&vn(s.sourceColumnObj,e,t))}function vn(d,e,t){if(e.dimensions)for(const n of e.dimensions){const[i,s]=n.split(".");if(t.get(i)?.dimensions?.[s]?.sql===d)return!0}if(e.timeDimensions)for(const n of e.timeDimensions){if(n.granularity)continue;const[i,s]=n.dimension.split(".");if(t.get(i)?.dimensions?.[s]?.sql===d)return!0}return!1}function Rn(d,e,t,n,i,s){const r=[];let a=e.db.select(n).from(t.from);if(i.ctes.length>0&&(a=e.db.with(...i.ctes).select(n).from(t.from)),t.joins)for(const l of t.joins)switch(l.type||"left"){case"left":a=a.leftJoin(l.table,l.on);break;case"inner":a=a.innerJoin(l.table,l.on);break;case"right":a=a.rightJoin(l.table,l.on);break;case"full":a=a.fullJoin(l.table,l.on);break}const u=new Set,c=new Set;if(d.preAggregationCTEs){for(const l of d.preAggregationCTEs)if(l.intermediateJoins&&l.intermediateJoins.length>0)for(const m of l.intermediateJoins)c.add(m.cube.name)}if(d.joinCubes&&d.joinCubes.length>0)for(const l of d.joinCubes){const m=l.cube.name;if(c.has(m)&&!i.cteAliasMap.has(m))continue;const p=i.cteAliasMap.get(l.cube.name);if(l.junctionTable){const w=l.junctionTable;let T=w.joinCondition;const S=w.sourceCubeName?i.cteAliasMap.get(w.sourceCubeName):void 0;if(S){const D=d.preAggregationCTEs?.find(N=>N.cube.name===w.sourceCubeName)?.downstreamJoinKeys?.find(N=>N.targetCubeName===l.cube.name);if(D&&D.joinKeys.length>0){const N=[];for(const F of D.joinKeys){const v=o`${o.identifier(S)}.${o.identifier(F.sourceColumn)}`,U=F.targetColumnObj;U&&N.push(k(U,v))}N.length>0&&(T=A(...N))}}const C=[];if(w.securitySql){const $=w.securitySql(e.securityContext);Array.isArray($)?C.push(...$):C.push($)}try{switch(w.joinType||"left"){case"left":a=a.leftJoin(w.table,T);break;case"inner":a=a.innerJoin(w.table,T);break;case"right":a=a.rightJoin(w.table,T);break;case"full":a=a.fullJoin(w.table,T);break}C.length>0&&r.push(...C)}catch{}}let f,h,g;if(p)f=o`${o.identifier(p)}`,h=s.cteBuilder.buildCTEJoinCondition(l,p,d),g=void 0;else{const w=i.downstreamCubeMap.get(l.cube.name),T=l.cube.sql(e);if(f=T.from,g=T.where,w&&!l.junctionTable){const S=[];for(const C of w.joinKeys){const $=o`${o.identifier(w.cteAlias)}.${o.identifier(C.sourceColumn)}`,D=C.targetColumnObj||o.identifier(C.targetColumn);S.push(k($,D))}h=S.length===1?S[0]:A(...S)}else h=l.joinCondition}const y=l.joinType||"left",b=y!=="inner"&&g?A(h,g):h;try{switch(y){case"left":a=a.leftJoin(f,b),g&&u.add(l.cube.name);break;case"inner":a=a.innerJoin(f,h);break;case"right":a=a.rightJoin(f,b),g&&u.add(l.cube.name);break;case"full":a=a.fullJoin(f,b),g&&u.add(l.cube.name);break}}catch{}}return{drizzleQuery:a,allWhereConditions:r,cubesWithSecurityInJoin:u,absorbedIntermediateCubes:c}}function Fn(d,e,t,n,i,s,r,a){const u=[...r.allWhereConditions];if(i.where&&u.push(i.where),d.joinCubes&&d.joinCubes.length>0)for(const h of d.joinCubes){const g=h.cube.name;if(s.cteAliasMap.get(g)||r.absorbedIntermediateCubes.has(g)||r.cubesWithSecurityInJoin.has(g))continue;const b=h.cube.sql(t);b.where&&u.push(b.where)}const c=a.queryBuilder.buildWhereConditions(d.joinCubes.length>0?n:d.primaryCube,e,t,d,s.preBuiltFilterMap);c.length>0&&u.push(...c);let l=r.drizzleQuery;if(u.length>0){const h=u.length===1?u[0]:A(...u);l=l.where(h)}const m=a.queryBuilder.buildGroupByFields(d.joinCubes.length>0?n:d.primaryCube,e,t,d);m.length>0&&(l=l.groupBy(...m));const p=a.queryBuilder.buildHavingConditions(d.joinCubes.length>0?n:d.primaryCube,e,t,d);if(p.length>0){const h=p.length===1?p[0]:A(...p);l=l.having(h)}const f=a.queryBuilder.buildOrderBy(e);return f.length>0&&(l=l.orderBy(...f)),l=a.queryBuilder.applyLimitAndOffset(l,e),l}function nt(d){const e=new Map;if(e.set(d.primaryCube.name,d.primaryCube),d.joinCubes)for(const t of d.joinCubes)e.set(t.cube.name,t.cube);return e}class Mn{constructor(e,t,n){this.queryBuilder=e,this.cteBuilder=t,this.databaseAdapter=n}derivePhysicalPlanContext(e){const t=e.source;if(t.type==="multiFactMerge")return this.derivePhysicalPlanContextFromMultiFact(e,t);if(t.type==="fullKeyAggregate")return this.derivePhysicalPlanContextFromFullKeyAggregate(e,t);const n=this.resolvePhysicalSimpleSource(t),i=this.resolveKeysDeduplicationMeta(t);return{primaryCube:n.primaryCube.cube,joinCubes:n.joins.map(s=>({cube:s.target.cube,alias:s.alias,joinType:s.joinType,joinCondition:s.joinCondition,junctionTable:s.junctionTable})),preAggregationCTEs:n.ctes.map(s=>({cube:s.cube.cube,alias:s.alias,cteAlias:s.cteAlias,joinKeys:s.joinKeys,measures:s.measures,propagatingFilters:s.propagatingFilters,downstreamJoinKeys:s.downstreamJoinKeys,intermediateJoins:s.intermediateJoins,cteType:s.cteType,cteReason:s.cteReason})),keysDeduplication:i,warnings:e.warnings.length>0?e.warnings:void 0}}derivePhysicalPlanContextFromMultiFact(e,t){const n=t.groups.map((s,r)=>{if(s.type!=="query")return null;const a=s,u=this.derivePhysicalPlanContext(a),c=this.toSemanticQuery(a);return{alias:`mf_group_${r+1}`,query:c,queryPlan:u,measures:c.measures??[]}}).filter(s=>!!s);if(n.length===0)throw new Error("multiFactMerge requires at least one query group");const i=n[0];return{primaryCube:i.queryPlan.primaryCube,joinCubes:i.queryPlan.joinCubes,preAggregationCTEs:i.queryPlan.preAggregationCTEs,warnings:e.warnings.length>0?e.warnings:void 0,multiFactMerge:{mergeStrategy:t.mergeStrategy,sharedDimensions:t.sharedDimensions.map(s=>s.name),groups:n}}}derivePhysicalPlanContextFromFullKeyAggregate(e,t){const n=t.subqueries.map((s,r)=>{if(s.type!=="query")throw new Error("fullKeyAggregate currently requires query subqueries");const a=s,u=this.derivePhysicalPlanContext(a),c=this.toSemanticQuery(a);return{alias:`fka_group_${r+1}`,query:c,queryPlan:u,measures:c.measures??[]}});if(n.length===0)throw new Error("fullKeyAggregate requires at least one subquery");const i=n[0];return{primaryCube:i.queryPlan.primaryCube,joinCubes:i.queryPlan.joinCubes,preAggregationCTEs:i.queryPlan.preAggregationCTEs,warnings:e.warnings.length>0?e.warnings:void 0,multiFactMerge:{mergeStrategy:"fullJoin",sharedDimensions:t.dimensions.map(s=>s.name),groups:n}}}toSemanticQuery(e){const t=e.orderBy.length>0?Object.fromEntries(e.orderBy.map(n=>[n.name,n.direction])):void 0;return{measures:e.measures.map(n=>n.name),dimensions:e.dimensions.map(n=>n.name),timeDimensions:e.timeDimensions.map(n=>({dimension:n.name,granularity:n.granularity,dateRange:n.dateRange,fillMissingDates:n.fillMissingDates,compareDateRange:n.compareDateRange})),filters:e.filters,order:t,limit:e.limit,offset:e.offset}}resolvePhysicalSimpleSource(e){switch(e.type){case"simpleSource":return e;case"keysDeduplication":return this.resolvePhysicalSimpleSourceFromKeysDedup(e);default:throw new Error(`Current SQL builder does not support logical node '${e.type}' in physical conversion`)}}resolvePhysicalSimpleSourceFromKeysDedup(e){const t=e.measureSource;if(t.type==="simpleSource")return t;const n=e.keysSource;if(n.type==="simpleSource")return n;throw new Error("keysDeduplication requires at least one simpleSource child for SQL physical conversion")}resolveKeysDeduplicationMeta(e){if(e.type!=="keysDeduplication")return;const t=e,n=new Set;for(const s of t.joinOn){if(!s.alias)continue;const[r,a]=s.alias.split(".");r&&a&&n.add(r)}const i=n.size===1?Array.from(n)[0]:"";return i?{multipliedCubeName:i,primaryKeyDimensions:t.joinOn.map(s=>s.alias?.split(".")[1]??"").filter(Boolean),regularMeasures:t.regularMeasures}:void 0}build(e,t,n){const i={queryBuilder:this.queryBuilder,cteBuilder:this.cteBuilder,databaseAdapter:this.databaseAdapter},s=this.tryBuildMultiFactMergeQuery(e,t,n,i);if(s)return s;const r=this.tryBuildKeysDeduplicationQuery(e,t,n,i);if(r)return r;const a=Sn(e,t,n,i),u=e.primaryCube.sql(n),c=e.joinCubes.length>0?nt(e):new Map([[e.primaryCube.name,e.primaryCube]]),l=An(e,t,n,c,i),m=Rn(e,n,u,l,a,i);return Fn(e,t,n,c,u,a,m,i)}tryBuildKeysDeduplicationQuery(e,t,n,i){const s=e.keysDeduplication;if(!s?.multipliedCubeName||!t.measures?.length)return null;const r=e.joinCubes.length>0?nt(e):new Map([[e.primaryCube.name,e.primaryCube]]),a=r.get(s.multipliedCubeName);if(!a||!this.canExecuteKeysDeduplication(t,a,s.multipliedCubeName))return null;const u=s.primaryKeyDimensions.length>0?s.primaryKeyDimensions:this.getPrimaryKeyDimensions(a);if(u.length===0)return null;const c=`${s.multipliedCubeName.toLowerCase()}_keys`,l=`${s.multipliedCubeName.toLowerCase()}_pk_agg`,m={},p=[];if(t.dimensions)for(const E of t.dimensions){const[_,M]=E.split("."),L=r.get(_),J=L?.dimensions?.[M];if(!L||!J)return null;const z=R(J.sql,n);m[E]=o`${z}`.as(E),p.push(z)}if(t.timeDimensions)for(const E of t.timeDimensions){const[_,M]=E.dimension.split("."),L=r.get(_),J=L?.dimensions?.[M];if(!L||!J)return null;const z=i.queryBuilder.buildTimeDimensionExpression(J.sql,E.granularity,n);m[E.dimension]=o`${z}`.as(E.dimension),p.push(z)}const f=[];for(const E of u){const _=a.dimensions?.[E];if(!_)return null;const M=R(_.sql,n),L=`__pk__${E}`;m[L]=o`${M}`.as(L),p.push(M),f.push(L)}const h=s.regularMeasures??[],g=new Set(h),y=t.measures.filter(E=>!g.has(E));if(h.length>0){const E=i.queryBuilder.buildResolvedMeasures(h,r,n);for(const _ of h){const M=E.get(_);if(!M)return null;const L=`__reg__${_.replace(".","__")}`;m[L]=o`${M()}`.as(L)}}const b=e.primaryCube.sql(n),w=[];b.where&&w.push(b.where);let T=n.db.select(m).from(b.from);if(b.joins)for(const E of b.joins)T=this.applyJoinByType(T,E.type??"left",E.table,E.on);for(const E of e.joinCubes){if(E.junctionTable&&(T=this.applyJoinByType(T,E.junctionTable.joinType??"left",E.junctionTable.table,E.junctionTable.joinCondition),E.junctionTable.securitySql)){const M=E.junctionTable.securitySql(n.securityContext);Array.isArray(M)?w.push(...M):w.push(M)}const _=E.cube.sql(n);T=this.applyJoinByType(T,E.joinType??"left",_.from,E.joinCondition),_.where&&w.push(_.where)}w.push(...i.queryBuilder.buildWhereConditions(r,t,n)),w.length>0&&(T=T.where(w.length===1?w[0]:A(...w))),p.length>0&&(T=T.groupBy(...p));const S=n.db.$with(c).as(T),C=a.sql(n),$={},D=[];for(const E of u){const _=a.dimensions?.[E];if(!_)return null;const M=R(_.sql,n);$[E]=o`${M}`.as(E),D.push(M)}const N=new Set;for(const E of y){const[,_]=E.split(".");a.measures?.[_]?.type==="avg"&&N.add(_)}const F=y.filter(E=>{const[,_]=E.split(".");return!N.has(_)});if(F.length>0){const E=i.queryBuilder.buildResolvedMeasures(F,new Map([[a.name,a]]),n);for(const _ of F){const[,M]=_.split("."),L=E.get(_);if(!L)return null;$[M]=o`${L()}`.as(M)}}for(const E of y){const[,_]=E.split(".");if(!N.has(_))continue;const M=a.measures?.[_];if(!M?.sql)return null;const L=R(M.sql,n),J=`__avg_sum__${_}`,z=`__avg_count__${_}`;$[J]=o`sum(${L})`.as(J),$[z]=o`count(${L})`.as(z)}let v=n.db.select($).from(C.from);const U=[];C.where&&U.push(C.where),U.push(...i.queryBuilder.buildWhereConditions(a,t,n)),U.length>0&&(v=v.where(U.length===1?U[0]:A(...U))),D.length>0&&(v=v.groupBy(...D));const yt=n.db.$with(l).as(v),Z={};for(const E of t.dimensions??[])Z[E]=o`${o.identifier(c)}.${o.identifier(E)}`.as(E);for(const E of t.timeDimensions??[])Z[E.dimension]=o`${o.identifier(c)}.${o.identifier(E.dimension)}`.as(E.dimension);for(const E of y){const[,_]=E.split("."),M=a.measures?.[_];Z[E]=this.buildKeysOuterAggregation(M?.type??"sum",l,_,E)}for(const E of h){const[_,M]=E.split("."),J=r.get(_)?.measures?.[M],z=`__reg__${E.replace(".","__")}`;Z[E]=this.buildKeysOuterAggregation(J?.type??"sum",c,z,E)}let q=n.db.with(S,yt).select(Z).from(o`${o.identifier(c)}`);const ye=f.map((E,_)=>k(o`${o.identifier(c)}.${o.identifier(E)}`,o`${o.identifier(l)}.${o.identifier(u[_])}`)),Ct=ye.length===1?ye[0]:A(...ye);q=q.leftJoin(o`${o.identifier(l)}`,Ct);const Le=[...(t.dimensions??[]).map(E=>o`${o.identifier(c)}.${o.identifier(E)}`),...(t.timeDimensions??[]).map(E=>o`${o.identifier(c)}.${o.identifier(E.dimension)}`)];Le.length>0&&(q=q.groupBy(...Le));const Pe=i.queryBuilder.buildOrderBy(t,Object.keys(Z));return Pe.length>0&&(q=q.orderBy(...Pe)),q=i.queryBuilder.applyLimitAndOffset(q,t),q}tryBuildMultiFactMergeQuery(e,t,n,i){const s=e.multiFactMerge;if(!s||s.groups.length<2)return null;const r=[...t.dimensions??[],...(t.timeDimensions??[]).map(b=>b.dimension)],a=Array.from(new Set(r)),u=a.length>0&&s.mergeStrategy==="fullJoin"&&!this.supportsFullOuterJoin(),c=this.selectRuntimeMergeStrategy(s.mergeStrategy,a.length>0),l=s.groups.map(b=>{const w=this.build(b.queryPlan,b.query,n);return n.db.$with(b.alias).as(w)});if(u)return this.buildMultiFactUnionKeysFallbackQuery(t,n,i,s,l,a);const m=s.groups[0].alias,p=s.groups.map(b=>b.alias),f={};if(a.length>0)for(const b of a){const w=this.coalesceQualifiedColumn(p,b);f[b]=o`${w}`.as(b)}for(const b of s.groups)for(const w of b.measures){const T=o`${o.identifier(b.alias)}.${o.identifier(w)}`;f[w]=o`coalesce(${T}, 0)`.as(w)}let h=n.db.with(...l).select(f).from(o`${o.identifier(m)}`),g=new Map;for(const b of a)g.set(b,o`${o.identifier(m)}.${o.identifier(b)}`);for(let b=1;b<s.groups.length;b++){const w=s.groups[b].alias;let T;if(a.length===0)T=o`1 = 1`;else{const S=a.map(C=>k(g.get(C),o`${o.identifier(w)}.${o.identifier(C)}`));T=S.length===1?S[0]:A(...S)}if(h=this.applyJoinByType(h,c,o`${o.identifier(w)}`,T),a.length>0&&c==="full")for(const S of a)g.set(S,o`coalesce(${g.get(S)}, ${o`${o.identifier(w)}.${o.identifier(S)}`})`)}const y=i.queryBuilder.buildOrderBy(t,Object.keys(f));return y.length>0&&(h=h.orderBy(...y)),i.queryBuilder.applyLimitAndOffset(h,t)}buildMultiFactUnionKeysFallbackQuery(e,t,n,i,s,r){const a="mf_all_keys",u=i.groups.map(h=>o`select ${this.buildSharedKeySelection(h.alias,r)} from ${o.identifier(h.alias)}`),c=o`${o.join(u,o` union `)}`,l=t.db.$with(a).as(c),m={};for(const h of r)m[h]=o`${o.identifier(a)}.${o.identifier(h)}`.as(h);for(const h of i.groups)for(const g of h.measures){const y=o`${o.identifier(h.alias)}.${o.identifier(g)}`;m[g]=o`coalesce(${y}, 0)`.as(g)}let p=t.db.with(...s,l).select(m).from(o`${o.identifier(a)}`);for(const h of i.groups){const g=r.map(b=>k(o`${o.identifier(a)}.${o.identifier(b)}`,o`${o.identifier(h.alias)}.${o.identifier(b)}`)),y=g.length===1?g[0]:A(...g);p=p.leftJoin(o`${o.identifier(h.alias)}`,y)}const f=n.queryBuilder.buildOrderBy(e,Object.keys(m));return f.length>0&&(p=p.orderBy(...f)),n.queryBuilder.applyLimitAndOffset(p,e)}buildSharedKeySelection(e,t){const n=t.map(i=>o`${o.identifier(e)}.${o.identifier(i)} as ${o.identifier(i)}`);return o.join(n,o`, `)}selectRuntimeMergeStrategy(e,t){return!t||e==="innerJoin"?"inner":e==="leftJoin"?"left":this.supportsFullOuterJoin()?"full":"left"}supportsFullOuterJoin(){const e=this.databaseAdapter.getEngineType();return e==="postgres"||e==="duckdb"}coalesceQualifiedColumn(e,t){if(e.length===1)return o`${o.identifier(e[0])}.${o.identifier(t)}`;const n=e.map(s=>o`${o.identifier(s)}.${o.identifier(t)}`);let i=n[0];for(let s=1;s<n.length;s++)i=o`coalesce(${i}, ${n[s]})`;return i}canExecuteKeysDeduplication(e,t,n){if(!e.measures?.length)return!1;for(const i of e.measures){const[s,r]=i.split(".");if(s!==n)continue;const a=t.measures?.[r];if(!a||!["sum","count","number","min","max","avg"].includes(a.type))return!1}return!this.queryContainsMeasureFilter(e,t,n)}queryContainsMeasureFilter(e,t,n){const i=s=>{if(!s)return!1;for(const r of s){if("and"in r){if(i(r.and))return!0;continue}if("or"in r){if(i(r.or))return!0;continue}if("member"in r){const[a,u]=r.member.split(".");if(a===n&&t.measures?.[u])return!0}}return!1};return i(e.filters)}getPrimaryKeyDimensions(e){return Object.entries(e.dimensions??{}).filter(([,t])=>!!t.primaryKey).map(([t])=>t)}buildKeysOuterAggregation(e,t,n,i){switch(e){case"min":{const s=o`${o.identifier(t)}.${o.identifier(n)}`;return o`min(${s})`.as(i)}case"max":{const s=o`${o.identifier(t)}.${o.identifier(n)}`;return o`max(${s})`.as(i)}case"avg":{const s=o`${o.identifier(t)}.${o.identifier(`__avg_sum__${n}`)}`,r=o`${o.identifier(t)}.${o.identifier(`__avg_count__${n}`)}`;return o`sum(${s}) / nullif(sum(${r}), 0)`.as(i)}default:{const s=o`${o.identifier(t)}.${o.identifier(n)}`;return o`coalesce(sum(${s}), 0)`.as(i)}}}applyJoinByType(e,t,n,i){switch(t){case"inner":return e.innerJoin(n,i);case"right":return e.rightJoin(n,i);case"full":return e.fullJoin(n,i);default:return e.leftJoin(n,i)}}}class On{constructor(e,t){if(this.dbExecutor=e,this.databaseAdapter=e.databaseAdapter,!this.databaseAdapter)throw new Error("DatabaseExecutor must have a databaseAdapter property");this.queryBuilder=new ln(this.databaseAdapter);const n=new cn,i=new dn(this.queryBuilder);this.drizzlePlanBuilder=new Mn(this.queryBuilder,i,this.databaseAdapter),this.comparisonQueryBuilder=new yn(this.databaseAdapter),this.funnelQueryBuilder=new Cn(this.databaseAdapter),this.flowQueryBuilder=new wn(this.databaseAdapter),this.retentionQueryBuilder=new $n(this.databaseAdapter),this.logicalPlanBuilder=new Tn(n),this.planOptimiser=new En,this.cacheConfig=t}queryBuilder;drizzlePlanBuilder;databaseAdapter;comparisonQueryBuilder;funnelQueryBuilder;flowQueryBuilder;retentionQueryBuilder;cacheConfig;logicalPlanBuilder;planOptimiser;async execute(e,t,n,i){try{const s=this.resolveQueryMode(t);this.validateQueryForMode(s,e,t);let r;if(this.cacheConfig?.enabled!==!1&&this.cacheConfig?.provider)if(r=Zt(t,n,this.cacheConfig),i?.skipCache)this.cacheConfig.onCacheEvent?.({type:"miss",key:r,durationMs:0});else try{const a=Date.now(),u=await this.cacheConfig.provider.get(r);if(u)return this.cacheConfig.onCacheEvent?.({type:"hit",key:r,durationMs:Date.now()-a}),{...u.value,cache:u.metadata?{hit:!0,cachedAt:new Date(u.metadata.cachedAt).toISOString(),ttlMs:u.metadata.ttlMs,ttlRemainingMs:u.metadata.ttlRemainingMs}:{hit:!0,cachedAt:new Date().toISOString(),ttlMs:0,ttlRemainingMs:0}};this.cacheConfig.onCacheEvent?.({type:"miss",key:r,durationMs:Date.now()-a})}catch(a){this.cacheConfig.onError?.(a,"get")}return await this.executeQueryByModeWithCache(s,e,t,n,r)}catch(s){if(s instanceof Error){let r=s;for(;r.cause instanceof Error;)r=r.cause;let a=r.message;const u=r;throw u.code&&(a+=` [${u.code}]`),u.detail&&(a+=` Detail: ${u.detail}`),u.hint&&(a+=` Hint: ${u.hint}`),s.message=`Query execution failed: ${a}`,s}throw new Error("Query execution failed: Unknown error")}}buildLogicalPlan(e,t,n){const i=new ne,s=this.createQueryContext(n,i);return this.preloadFilterCache(t,i,e,s),this.buildRegularQueryArtifacts(e,t,s).optimisedPlan}analyzeQuery(e,t,n){const i=new ne,s=this.createQueryContext(n,i);return this.preloadFilterCache(t,i,e,s),this.buildRegularQueryArtifacts(e,t,s).analysis}async executeQuery(e,t,n){const i=new Map;return i.set(e.name,e),this.execute(i,t,n)}async executeComparisonQueryWithCache(e,t,n,i){const s=await this.executeComparisonQuery(e,t,n);return await this.cacheResult(i,s),s}async executeComparisonQuery(e,t,n){const i=this.buildComparisonExecutionPlan(t),{timeDimension:s,periods:r,granularity:a,periodQueries:u}=i,c=u.map(async(p,f)=>({result:await this.executeStandardQuery(e,p,n),period:r[f]})),l=await Promise.all(c),m=this.comparisonQueryBuilder.mergeComparisonResults(l,s,a);return m.data=this.comparisonQueryBuilder.sortComparisonResults(m.data,s.dimension),m}buildComparisonExecutionPlan(e){const t=this.comparisonQueryBuilder.getComparisonTimeDimension(e);if(!t||!t.compareDateRange)throw new Error("No compareDateRange found in query");const n=this.comparisonQueryBuilder.normalizePeriods(t.compareDateRange);if(n.length<2)throw new Error("compareDateRange requires at least 2 periods");const i=n.map(s=>this.comparisonQueryBuilder.createPeriodQuery(e,s));return{timeDimension:t,granularity:t.granularity||"day",periods:n,periodQueries:i}}async executeFunnelQueryWithCache(e,t,n,i){const s=await this.executeFunnelQuery(e,t,n);return await this.cacheResult(i,s),{...s,cache:{hit:!1}}}async executeFunnelQuery(e,t,n){const i=t.funnel,s=this.funnelQueryBuilder.validateConfig(i,e);if(!s.isValid)throw new Error(`Funnel validation failed: ${s.errors.join(", ")}`);const r={db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:n},u=await this.funnelQueryBuilder.buildFunnelQuery(i,e,r),c=this.funnelQueryBuilder.transformResult(u,i),l={measures:{},dimensions:{},segments:{},timeDimensions:{}};return l.funnel={config:i,steps:i.steps.map((m,p)=>({name:m.name,index:p,timeToConvert:m.timeToConvert}))},{data:c,annotation:l}}async executeFlowQueryWithCache(e,t,n,i){const s=await this.executeFlowQuery(e,t,n);return await this.cacheResult(i,s),{...s,cache:{hit:!1}}}async executeFlowQuery(e,t,n){const i=t.flow,s=this.flowQueryBuilder.validateConfig(i,e);if(!s.isValid)throw new Error(`Flow validation failed: ${s.errors.join(", ")}`);const r={db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:n},u=await this.flowQueryBuilder.buildFlowQuery(i,e,r),c=this.flowQueryBuilder.transformResult(u),l={measures:{},dimensions:{},segments:{},timeDimensions:{}};return l.flow={config:i,startingStep:{name:i.startingStep.name},stepsBefore:i.stepsBefore,stepsAfter:i.stepsAfter},{data:[c],annotation:l}}async executeRetentionQueryWithCache(e,t,n,i){const s=await this.executeRetentionQuery(e,t,n);return await this.cacheResult(i,s),{...s,cache:{hit:!1}}}async executeRetentionQuery(e,t,n){const i=t.retention,s=this.retentionQueryBuilder.validateConfig(i,e);if(!s.isValid)throw new Error(`Retention validation failed: ${s.errors.join(", ")}`);const r={db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:n},u=await this.retentionQueryBuilder.buildRetentionQuery(i,e,r),c=this.retentionQueryBuilder.transformResult(u,i),l={measures:{},dimensions:{},segments:{},timeDimensions:{}};return l.retention={config:i,granularity:i.granularity,periods:i.periods,retentionType:i.retentionType,breakdownDimensions:i.breakdownDimensions},{data:c,annotation:l}}async executeStandardQuery(e,t,n){const i=new ne,s=this.createQueryContext(n,i);this.preloadFilterCache(t,i,e,s);const{optimisedPlan:r}=this.buildRegularQueryArtifacts(e,t,s),a=this.drizzlePlanBuilder.derivePhysicalPlanContext(r),u=this.drizzlePlanBuilder.build(a,t,s),c=this.queryBuilder.collectNumericFields(e,t),l=await this.dbExecutor.execute(u,c),m=Array.isArray(l)?l.map(g=>{const y={...g};if(t.timeDimensions){for(const b of t.timeDimensions)if(b.dimension in y){let w=y[b.dimension];if(typeof w=="string"&&w.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)){const T=w.replace(" ","T"),S=!T.endsWith("Z")&&!T.includes("+")?T+"Z":T;w=new Date(S)}w=this.databaseAdapter.convertTimeDimensionResult(w),y[b.dimension]=w}}return y}):[l],p=t.measures||[],f=Xe(m,t,p),h=this.generateAnnotations(a,t);return{data:f,annotation:h}}createQueryContext(e,t){return{db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:e,filterCache:t}}getOptimiserEngineType(){const e=this.dbExecutor.getEngineType?.();return e==="singlestore"?"mysql":e??"postgres"}buildRegularQueryArtifacts(e,t,n){const i=this.logicalPlanBuilder.planWithAnalysis(e,t,n),s=this.planOptimiser.optimise(i.plan,{engineType:this.getOptimiserEngineType()});return{logicalPlan:i.plan,analysis:i.analysis,optimisedPlan:s}}validateSecurityContext(e,t){const n=typeof process<"u"?process.env?.NODE_ENV:void 0,i=typeof process<"u"?process.env?.DRIZZLE_CUBE_WARN_SECURITY:void 0;if(n!=="development"&&!i)return;const s=[e.primaryCube];for(const a of e.joinCubes||[])s.push(a.cube);for(const a of e.preAggregationCTEs||[])s.push(a.cube);const r=new Set;for(const a of s)if(!r.has(a.name)){r.add(a.name);try{if(a.public)continue;a.sql(t).where||console.warn(`[drizzle-cube] WARNING: Cube '${a.name}' has no security filtering. If this cube contains public data, add 'public: true' to suppress this warning. Otherwise, ensure sql() returns: { from: table, where: eq(table.orgId, ctx.securityContext.orgId) }`)}catch{}}}async generateSQL(e,t,n){const i=new Map;return i.set(e.name,e),this.generateUnifiedSQL(i,t,n)}async generateMultiCubeSQL(e,t,n){return this.generateUnifiedSQL(e,t,n)}async dryRunFunnel(e,t,n){if(!this.funnelQueryBuilder.hasFunnel(t))throw new Error("Query does not contain a valid funnel configuration");const i=t.funnel,s=this.funnelQueryBuilder.validateConfig(i,e);if(!s.isValid)throw new Error(`Funnel validation failed: ${s.errors.join(", ")}`);const r={db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:n},u=this.funnelQueryBuilder.buildFunnelQuery(i,e,r).toSQL();return{sql:u.sql,params:u.params}}async dryRunFlow(e,t,n){if(!this.flowQueryBuilder.hasFlow(t))throw new Error("Query does not contain a valid flow configuration");const i=t.flow,s=this.flowQueryBuilder.validateConfig(i,e);if(!s.isValid)throw new Error(`Flow validation failed: ${s.errors.join(", ")}`);const r={db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:n},u=this.flowQueryBuilder.buildFlowQuery(i,e,r).toSQL();return{sql:u.sql,params:u.params}}async dryRunRetention(e,t,n){if(!this.retentionQueryBuilder.hasRetention(t))throw new Error("Query does not contain a valid retention configuration");const i=t.retention,s=this.retentionQueryBuilder.validateConfig(i,e);if(!s.isValid)throw new Error(`Retention validation failed: ${s.errors.join(", ")}`);const r={db:this.dbExecutor.db,schema:this.dbExecutor.schema,securityContext:n},u=this.retentionQueryBuilder.buildRetentionQuery(i,e,r).toSQL();return{sql:u.sql,params:u.params}}async explainQuery(e,t,n,i){const s=await this.dryRunSQL(e,t,n);return this.dbExecutor.explainQuery(s.sql,s.params||[],i)}async dryRunSQL(e,t,n){const i=this.resolveQueryMode(t);return this.validateQueryForMode(i,e,t),this.generateSqlForMode(i,e,t,n)}async generateUnifiedSQL(e,t,n){const i=new ne,s=this.createQueryContext(n,i);this.preloadFilterCache(t,i,e,s);const{optimisedPlan:r}=this.buildRegularQueryArtifacts(e,t,s),a=this.drizzlePlanBuilder.derivePhysicalPlanContext(r),c=this.drizzlePlanBuilder.build(a,t,s).toSQL();return{sql:c.sql,params:c.params}}resolveQueryMode(e){const t=[];if(this.comparisonQueryBuilder.hasComparison(e)&&t.push("comparison"),this.funnelQueryBuilder.hasFunnel(e)&&t.push("funnel"),this.flowQueryBuilder.hasFlow(e)&&t.push("flow"),this.retentionQueryBuilder.hasRetention(e)&&t.push("retention"),t.length===0)return"regular";if(t.length>1)throw new Error(`Query contains multiple query modes: ${t.join(", ")}`);return t[0]}validateQueryForMode(e,t,n){const i=()=>{const r=mt(t,n);if(!r.isValid)throw new Error(`Query validation failed: ${r.errors.join(", ")}`)};({regular:i,comparison:i,funnel:()=>{const r=this.funnelQueryBuilder.validateConfig(n.funnel,t);if(!r.isValid)throw new Error(`Funnel validation failed: ${r.errors.join(", ")}`)},flow:()=>{const r=this.flowQueryBuilder.validateConfig(n.flow,t);if(!r.isValid)throw new Error(`Flow validation failed: ${r.errors.join(", ")}`)},retention:()=>{const r=this.retentionQueryBuilder.validateConfig(n.retention,t);if(!r.isValid)throw new Error(`Retention validation failed: ${r.errors.join(", ")}`)}})[e]()}async executeQueryByModeWithCache(e,t,n,i,s){return{regular:()=>this.executeRegularQueryWithCache(t,n,i,s),comparison:()=>this.executeComparisonQueryWithCache(t,n,i,s),funnel:()=>this.executeFunnelQueryWithCache(t,n,i,s),flow:()=>this.executeFlowQueryWithCache(t,n,i,s),retention:()=>this.executeRetentionQueryWithCache(t,n,i,s)}[e]()}async executeRegularQueryWithCache(e,t,n,i){const s=new ne,r=this.createQueryContext(n,s);this.preloadFilterCache(t,s,e,r);const{optimisedPlan:a}=this.buildRegularQueryArtifacts(e,t,r),u=this.drizzlePlanBuilder.derivePhysicalPlanContext(a);this.validateSecurityContext(u,r);const c=this.drizzlePlanBuilder.build(u,t,r),l=this.queryBuilder.collectNumericFields(e,t),m=await this.dbExecutor.execute(c,l),p=Array.isArray(m)?m.map(b=>{const w={...b};if(t.timeDimensions){for(const T of t.timeDimensions)if(T.dimension in w){let S=w[T.dimension];if(typeof S=="string"&&S.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)){const C=S.replace(" ","T"),$=!C.endsWith("Z")&&!C.includes("+")?C+"Z":C;S=new Date($)}S=this.databaseAdapter.convertTimeDimensionResult(S),w[T.dimension]=S}}return w}):[m],f=t.measures||[],h=Xe(p,t,f),g=this.generateAnnotations(u,t),y={data:h,annotation:g,warnings:a.warnings?.length?a.warnings:void 0};return await this.cacheResult(i,y),y}async cacheResult(e,t){if(!(!e||!this.cacheConfig?.provider))try{const n=Date.now();await this.cacheConfig.provider.set(e,t,this.cacheConfig.defaultTtlMs??3e5),this.cacheConfig.onCacheEvent?.({type:"set",key:e,durationMs:Date.now()-n})}catch(n){this.cacheConfig.onError?.(n,"set")}}async generateSqlForMode(e,t,n,i){return{regular:()=>this.generateUnifiedSQL(t,n,i),comparison:()=>this.generateComparisonSQL(t,n,i),funnel:()=>this.dryRunFunnel(t,n,i),flow:()=>this.dryRunFlow(t,n,i),retention:()=>this.dryRunRetention(t,n,i)}[e]()}async generateComparisonSQL(e,t,n){const s=this.buildComparisonExecutionPlan(t).periodQueries[0];return this.generateUnifiedSQL(e,s,n)}generateAnnotations(e,t){const n={},i={},s={},r=[e.primaryCube].filter(Boolean);if(e.joinCubes&&e.joinCubes.length>0&&r.push(...e.joinCubes.map(a=>a.cube).filter(Boolean)),e.multiFactMerge?.groups?.length)for(const a of e.multiFactMerge.groups)a.queryPlan.primaryCube&&r.push(a.queryPlan.primaryCube),a.queryPlan.joinCubes?.length&&r.push(...a.queryPlan.joinCubes.map(u=>u.cube).filter(Boolean));if(t.measures)for(const a of t.measures){const[u,c]=a.split("."),l=r.find(m=>m?.name===u);if(l&&l.measures[c]){const m=l.measures[c];n[a]={title:m.title||c,shortTitle:m.title||c,type:m.type}}}if(t.dimensions)for(const a of t.dimensions){const[u,c]=a.split("."),l=r.find(m=>m?.name===u);if(l&&l.dimensions?.[c]){const m=l.dimensions[c];i[a]={title:m.title||c,shortTitle:m.title||c,type:m.type}}}if(t.timeDimensions)for(const a of t.timeDimensions){const[u,c]=a.dimension.split("."),l=r.find(m=>m?.name===u);if(l&&l.dimensions?.[c]){const m=l.dimensions[c];s[a.dimension]={title:m.title||c,shortTitle:m.title||c,type:m.type,granularity:a.granularity}}}return{measures:n,dimensions:i,segments:{},timeDimensions:s}}preloadFilterCache(e,t,n,i){if(e.filters&&e.filters.length>0){const s=Oe(e.filters);for(const r of s){const a=fe(r);if(t.has(a))continue;const[u,c]=r.member.split("."),l=n.get(u);if(!l)continue;const m=l.dimensions?.[c];if(!m||["arrayContains","arrayOverlaps","arrayContained"].includes(r.operator))continue;const f=m.type==="time"?R(m.sql,i):typeof m.sql=="function"?m.sql(i):m.sql,h=this.queryBuilder.buildFilterConditionPublic(f,r.operator,r.values,m,r.dateRange);h&&t.set(a,h)}}if(e.timeDimensions){for(const s of e.timeDimensions)if(s.dateRange){const r=ct(s.dimension,s.dateRange);if(t.has(r))continue;const[a,u]=s.dimension.split("."),c=n.get(a);if(!c)continue;const l=c.dimensions?.[u];if(!l)continue;const m=R(l.sql,i),p=this.queryBuilder.buildDateRangeCondition(m,s.dateRange);p&&t.set(r,p)}}}}const jn={name:"drizzle-cube-mcp-guide",description:"How to use drizzle-cube MCP tools to generate and run queries",messages:[{role:"user",content:{type:"text",text:["You are an analyst agent using drizzle-cube MCP.","","Workflow:","1) tools/call name=discover {topic|intent} - Find cubes and understand schema","2) Construct your query using the schema from discover (see cross-cube joins below)","3) tools/call name=validate {query} - Optional: fix schema issues","4) tools/call name=load {query} - Execute and get results","","CRITICAL - CROSS-CUBE JOINS:",'The "joins" property in discover results shows relationships between cubes.',"You can include dimensions from ANY related cube in your query!","Example: If Productivity joins to Employees, query:",'{ "measures": ["Productivity.totalPullRequests"], "dimensions": ["Employees.name"] }',"The system automatically joins the cubes for you.","","Query shapes:","- Regular: { measures, dimensions, filters[], timeDimensions[], order, limit, offset }","- Funnel: { funnel: { bindingKey, timeDimension, steps[], includeTimeMetrics? } }","- Flow: { flow: { bindingKey, eventDimension, steps?, window? } }","- Retention: { retention: { bindingKey, timeDimension, periods, granularity, retentionType, breakdownDimensions } }","","Time handling:",'- For AGGREGATED TOTALS (e.g., "last 3 months"): use filters with inDateRange, NOT timeDimensions','- For TIME SERIES (e.g., "by month"): use timeDimensions with granularity',"- You can combine both when needed","","Filters: flat arrays of { member, operator, values }. Do not nest arrays.","Do NOT hallucinate cube/field names—always use discover first."].join(`
|
|
195
|
+
`)}}]},In={name:"drizzle-cube-query-rules",description:"Key generation rules aligned with Gemini single-step prompt",messages:[{role:"user",content:{type:"text",text:["Rules (keep JSON only):","- Use only measures/dimensions/timeDimensions from schema.","- timeDimensions: include granularity when grouping; use inDateRange filter for relative windows; combine when both requested.","- Funnel detection keywords: funnel, conversion, journey, drop off, step by step; use funnel format only if eventStream metadata exists.","- Funnel rules: bindingKey/timeDimension from cube metadata; include time filter on step 0 (default last 6 months) using inDateRange; steps ordered; flat filters.","- Chart selection: line/area for time trends; bar for categories; scatter for 2-measure correlations; bubble for 3-measure correlations; funnel for funnels.","- Correlation keywords (correlation/relationship/vs/compare) -> scatter/bubble, never line.","- Prefer .name fields over .id; avoid Id dimensions unless requested.","- Filters: flat array of {member, operator, values}; operators equals, notEquals, contains, notContains, gt, gte, lt, lte, inDateRange, set, notSet."].join(`
|
|
196
|
+
`)}}]},Ln={name:"drizzle-cube-query-building",description:"CRITICAL: Complete guide for building valid queries of all types with examples",messages:[{role:"user",content:{type:"text",text:["# Drizzle Cube Query Building Guide","","## CRITICAL: Cross-Cube Joins","","You can combine measures from one cube with dimensions from RELATED cubes!",'Check the "joins" property in discover results to see relationships.',"",'Example: "Top 5 employees by pull requests last 3 months"',"- Productivity cube has: measures (totalPullRequests), dimensions (date)","- Productivity joins to Employees (via employeeId)","- Employees cube has: dimensions (name, department)","","Query combining BOTH cubes:","```json","{",' "measures": ["Productivity.totalPullRequests"],',' "dimensions": ["Employees.name"],',' "filters": [',' { "member": "Productivity.date", "operator": "inDateRange", "values": ["last 3 months"] }'," ],",' "order": { "Productivity.totalPullRequests": "desc" },',' "limit": 5',"}","```","The system AUTOMATICALLY joins Productivity to Employees for you!","","---","","## Date Filtering vs Time Grouping","","### For AGGREGATED TOTALS (no time breakdown)","Use `filters` with `inDateRange` operator. Do NOT use timeDimensions.","","```json","{",' "measures": ["Productivity.totalPullRequests"],',' "dimensions": ["Employees.name"],',' "filters": [{ "member": "Productivity.date", "operator": "inDateRange", "values": ["last 3 months"] }],',' "order": { "Productivity.totalPullRequests": "desc" },',' "limit": 5',"}","```","Result: 5 rows total, one per employee, with SUMMED pull requests.","","### For TIME SERIES (grouped by period)","Use `timeDimensions` WITH `granularity`.","","```json","{",' "measures": ["Productivity.totalPullRequests"],',' "timeDimensions": [{ "dimension": "Productivity.date", "dateRange": "last 3 months", "granularity": "month" }]',"}","```","Result: 3 rows (one per month) with pull request totals.","","### WRONG: timeDimensions without granularity","```json","// DON'T DO THIS - groups by DAY, returns ~90 rows!",'{ "timeDimensions": [{ "dimension": "X.date", "dateRange": "last 3 months" }] }',"```","","---","","## Regular Query Structure","","```json","{",' "measures": ["Cube.measure1", "Cube.measure2"],',' "dimensions": ["Cube.dimension1", "RelatedCube.dimension"],',' "filters": [',' { "member": "Cube.field", "operator": "equals", "values": ["value"] },',' { "member": "Cube.date", "operator": "inDateRange", "values": ["last 30 days"] }'," ],",' "timeDimensions": [],',' "order": { "Cube.measure1": "desc" },',' "limit": 100,',' "offset": 0',"}","```","","### Filter Operators","- String: equals, notEquals, contains, notContains, startsWith, endsWith","- Numeric: gt, gte, lt, lte","- Null: set, notSet","- Date: inDateRange, beforeDate, afterDate","","### Date Range Values",'- Relative: "last 7 days", "last 3 months", "last year", "this week", "this month"','- Absolute: ["2024-01-01", "2024-03-31"]',"","---","","## Funnel Query Structure","","Use when: conversion analysis, user journeys, step-by-step analysis","Requires: Cube with eventStream metadata","","```json","{",' "funnel": {',' "bindingKey": "Events.userId",',' "timeDimension": "Events.timestamp",',' "steps": ['," {",' "name": "Step 1",',' "filter": [',' { "member": "Events.eventType", "operator": "equals", "values": ["signup"] },',' { "member": "Events.timestamp", "operator": "inDateRange", "values": ["last 6 months"] }'," ]"," },"," {",' "name": "Step 2",',' "filter": [',' { "member": "Events.eventType", "operator": "equals", "values": ["purchase"] }'," ],",' "timeToConvert": { "value": 7, "unit": "day" }'," }"," ],",' "includeTimeMetrics": true'," }","}","```","","IMPORTANT: Put time filter (inDateRange) ONLY on step 0!","","---","","## Flow Query Structure","","Use when: analyzing event sequences, path analysis","","```json","{",' "flow": {',' "bindingKey": "Events.sessionId",',' "eventDimension": "Events.eventType",',' "timeDimension": "Events.timestamp",',' "stepsBefore": 2,',' "stepsAfter": 2,',' "startingStep": "checkout"'," }","}","```","","---","","## Retention Query Structure","","Use when: cohort analysis, user retention tracking","","```json","{",' "retention": {',' "bindingKey": "Users.id",',' "timeDimension": "Events.timestamp",',' "periods": 8,',' "granularity": "week",',' "retentionType": "rolling",',' "breakdownDimensions": ["Events.country"]'," }","}","```","","---","","## Common Mistakes to Avoid","","1. Using timeDimensions when you want aggregated totals → Use filters with inDateRange instead","2. Omitting granularity in timeDimensions → Results in day-level grouping","3. Guessing field names → Always use discover first to get actual schema","4. Nested filter arrays → Filters must be flat: [{ member, operator, values }]",'5. Missing date filter for "last N" queries → Always add inDateRange filter'].join(`
|
|
197
|
+
`)}}]},Pn={name:"drizzle-cube-date-filtering",description:"CRITICAL: How to correctly filter by date vs group by time period - the #1 source of query mistakes",messages:[{role:"user",content:{type:"text",text:["# Date Filtering vs Time Grouping - CRITICAL GUIDE","","This is the most common mistake when building queries. These are TWO DIFFERENT operations.","","## Quick Decision Tree","","```","User wants data over a time period?",'├── Wants AGGREGATED TOTALS (e.g., "total sales last month")',"│ └── Use: filters with inDateRange operator","│",'└── Wants TIME SERIES breakdown (e.g., "daily sales last month")'," └── Use: timeDimensions with granularity","```","","## For Aggregated Totals (MOST COMMON)","",'When user says: "last 3 months", "over the past year", "in Q1", "since January"',"","```json","{",' "measures": ["Sales.totalRevenue"],',' "dimensions": ["Products.category"],',' "filters": [',' { "member": "Sales.date", "operator": "inDateRange", "values": ["last 3 months"] }'," ]","}","```","","Result: One row per category with TOTAL revenue over the 3-month period.","","## For Time Series (Trend Analysis)","",'When user says: "by month", "per week", "daily trend", "over time"',"","```json","{",' "measures": ["Sales.totalRevenue"],',' "timeDimensions": [',' { "dimension": "Sales.date", "dateRange": "last 3 months", "granularity": "month" }'," ]","}","```","","Result: Multiple rows, one per month.","","## WRONG: timeDimensions Without Granularity","","```json","// This returns ~90 rows (daily) instead of aggregates!","{",' "timeDimensions": [{ "dimension": "Sales.date", "dateRange": "last 3 months" }]',"}","```","","## Both: Filter AND Group","",'When user wants: "monthly breakdown for last quarter"',"","```json","{",' "measures": ["Sales.totalRevenue"],',' "filters": [',' { "member": "Sales.date", "operator": "inDateRange", "values": ["last quarter"] }'," ],",' "timeDimensions": [',' { "dimension": "Sales.date", "granularity": "month" }'," ]","}","```","","## Summary Table","","| User Request | Use | Example |","|-------------|-----|---------|",'| "total for last 3 months" | filters + inDateRange | { filters: [{ operator: "inDateRange", values: ["last 3 months"] }] } |','| "top 5 last quarter" | filters + inDateRange | Same as above + order + limit |','| "monthly trend" | timeDimensions + granularity | { timeDimensions: [{ granularity: "month" }] } |','| "daily breakdown last week" | timeDimensions | { timeDimensions: [{ dateRange: "last week", granularity: "day" }] } |'].join(`
|
|
198
|
+
`)}}]},Bn=[jn,In,Ln,Pn];function kn(){return Bn}class Ie{cubes=new Map;dbExecutor;metadataCache;cacheConfig;constructor(e){e?.databaseExecutor?this.dbExecutor=e.databaseExecutor:e?.drizzle&&(this.dbExecutor=Ge(e.drizzle,e.schema,e.engineType)),this.cacheConfig=e?.cache}setDatabaseExecutor(e){this.dbExecutor=e}getEngineType(){return this.dbExecutor?.getEngineType()}setDrizzle(e,t,n){this.dbExecutor=Ge(e,t,n)}hasExecutor(){return!!this.dbExecutor}requireExecutor(){if(!this.dbExecutor)throw new Error("Database executor not configured");return this.dbExecutor}createQueryExecutor(e=!1){const t=this.requireExecutor();return new On(t,e?this.cacheConfig:void 0)}formatSqlResult(e){const t=this.requireExecutor().getEngineType();return{sql:Y.formatSqlString(e.sql,t),params:e.params}}registerCube(e){this.validateCalculatedMeasures(e),new X(this.cubes).populateDependencies(e),this.cubes.set(e.name,e),this.invalidateMetadataCache()}validateCalculatedMeasures(e){const t=[];for(const[n,i]of Object.entries(e.measures))if(i.type==="calculated"){if(!i.calculatedSql){t.push(`Calculated measure '${e.name}.${n}' must have calculatedSql property`);continue}const s=an(i.calculatedSql);if(!s.isValid){t.push(`Invalid calculatedSql syntax in '${e.name}.${n}': ${s.errors.join(", ")}`);continue}const r=new Map(this.cubes);r.set(e.name,e);const a=new X(r);try{a.validateDependencies(e)}catch(u){t.push(u instanceof Error?u.message:String(u))}}if(t.length===0){const n=new Map(this.cubes);n.set(e.name,e);const i=new X(n);i.buildGraph(e);const s=i.detectCycle();s&&t.push(`Circular dependency detected in calculated measures: ${s.join(" -> ")}`)}if(t.length>0)throw new Error(`Calculated measure validation failed for cube '${e.name}':
|
|
199
|
+
${t.join(`
|
|
200
|
+
`)}`)}getCube(e){return this.cubes.get(e)}getAllCubes(){return Array.from(this.cubes.values())}getAllCubesMap(){return this.cubes}async execute(e,t,n){return this.createQueryExecutor(!0).execute(this.cubes,e,t,n)}async executeMultiCubeQuery(e,t,n){return this.execute(e,t,n)}async executeQuery(e,t,n){if(!this.cubes.get(e))throw new Error(`Cube '${e}' not found`);return this.execute(t,n)}getMetadata(){return this.metadataCache?this.metadataCache:(this.metadataCache=Array.from(this.cubes.values()).map(e=>this.generateCubeMetadata(e)),this.metadataCache)}getColumnName(e){if(e&&e.name||e&&e.columnType&&e.name)return e.name;if(typeof e=="string")return e;if(e&&typeof e=="object"){if(e._.name)return e._.name;if(e.name)return e.name;if(e.columnName)return e.columnName}return"unknown_column"}static DEFAULT_TIME_GRANULARITIES=["year","quarter","month","week","day","hour"];generateCubeMetadata(e){const t=Object.keys(e.measures),n=Object.keys(e.dimensions),i=new Array(t.length),s=new Array(n.length);for(let c=0;c<t.length;c++){const l=t[c],m=e.measures[l];let p;m.drillMembers&&m.drillMembers.length>0&&(p=m.drillMembers.map(f=>f.includes(".")?f:`${e.name}.${f}`)),i[c]={name:`${e.name}.${l}`,title:m.title||l,shortTitle:m.title||l,type:m.type,format:void 0,description:m.description,synonyms:m.synonyms,drillMembers:p}}for(let c=0;c<n.length;c++){const l=n[c],m=e.dimensions[l];let p;m.type==="time"&&(p=m.granularities||Ie.DEFAULT_TIME_GRANULARITIES),s[c]={name:`${e.name}.${l}`,title:m.title||l,shortTitle:m.title||l,type:m.type,format:void 0,description:m.description,synonyms:m.synonyms,granularities:p}}const r=[];if(e.joins)for(const[,c]of Object.entries(e.joins)){const l=typeof c.targetCube=="function"?c.targetCube():c.targetCube;r.push({targetCube:l.name,relationship:c.relationship,joinFields:c.on.map(m=>({sourceField:this.getColumnName(m.source),targetField:this.getColumnName(m.target)}))})}const a=[];if(e.hierarchies)for(const[,c]of Object.entries(e.hierarchies))a.push({name:c.name,title:c.title||c.name,cubeName:e.name,levels:c.levels.map(l=>l.includes(".")?l:`${e.name}.${l}`)});return{name:e.name,title:e.title||e.name,description:e.description,exampleQuestions:e.exampleQuestions,measures:i,dimensions:s,segments:[],relationships:r.length>0?r:void 0,hierarchies:a.length>0?a:void 0,meta:e.meta}}async generateSQL(e,t,n){const i=this.getCube(e);if(!i)throw new Error(`Cube '${e}' not found`);const r=await this.createQueryExecutor().generateSQL(i,t,n);return this.formatSqlResult(r)}async generateMultiCubeSQL(e,t){const i=await this.createQueryExecutor().generateMultiCubeSQL(this.cubes,e,t);return this.formatSqlResult(i)}async dryRun(e,t){const i=await this.createQueryExecutor().dryRunSQL(this.cubes,e,t);return this.formatSqlResult(i)}async dryRunFunnel(e,t){return this.dryRun(e,t)}async dryRunFlow(e,t){return this.dryRun(e,t)}async dryRunRetention(e,t){return this.dryRun(e,t)}async explainQuery(e,t,n){return this.createQueryExecutor().explainQuery(this.cubes,e,t,n)}hasCube(e){return this.cubes.has(e)}removeCube(e){const t=this.cubes.delete(e);return t&&this.invalidateMetadataCache(),t}clearCubes(){this.cubes.clear(),this.invalidateMetadataCache()}invalidateMetadataCache(){this.metadataCache=void 0}getCubeNames(){return Array.from(this.cubes.keys())}validateQuery(e){return mt(this.cubes,e)}analyzeQuery(e,t){return this.createQueryExecutor(!0).analyzeQuery(this.cubes,e,t)}}function xn(d){const e=[];return d.timeDimensions?.some(t=>t.compareDateRange&&t.compareDateRange.length>=2)&&e.push("comparison"),d.funnel!==void 0&&d.funnel.steps?.length>=2&&e.push("funnel"),d.flow!==void 0&&d.flow.startingStep!==void 0&&d.flow.eventDimension!==void 0&&e.push("flow"),d.retention!==void 0&&d.retention.timeDimension!=null&&d.retention.bindingKey!=null&&e.push("retention"),e.length===0?[]:e}function mt(d,e){const t=[],n=xn(e);if(n.length>1)return t.push(`Query contains multiple query modes: ${n.join(", ")}`),{isValid:!1,errors:t};const i={funnel:()=>{const r=e.funnel.bindingKey;if(typeof r=="string"){const[a]=r.split(".");a&&!d.has(a)&&t.push(`Funnel binding key cube not found: ${a}`)}else if(Array.isArray(r))for(const a of r)d.has(a.cube)||t.push(`Funnel binding key cube not found: ${a.cube}`)},flow:()=>{const r=e.flow.bindingKey;if(typeof r=="string"){const[a]=r.split(".");a&&!d.has(a)&&t.push(`Flow binding key cube not found: ${a}`)}},retention:()=>{const r=e.retention,a=Un(r.timeDimension);a&&!d.has(a)&&t.push(`Retention cube not found: ${a}`);const u=r.bindingKey;if(typeof u=="string"){const[c]=u.split(".");c&&!d.has(c)&&t.push(`Retention binding key cube not found: ${c}`)}else if(Array.isArray(u))for(const c of u)d.has(c.cube)||t.push(`Retention binding key cube not found: ${c.cube}`);if(r.breakdownDimensions&&Array.isArray(r.breakdownDimensions))for(const c of r.breakdownDimensions){const[l]=c.split(".");l&&!d.has(l)&&t.push(`Retention breakdown cube not found: ${l}`)}}};if(n.length===1&&n[0]!=="comparison"){const r=n[0];return i[r](),{isValid:t.length===0,errors:t}}const s=new Set;if(e.measures)for(const r of e.measures){const[a,u]=r.split(".");if(!a||!u){t.push(`Invalid measure format: ${r}. Expected format: 'CubeName.fieldName'`);continue}s.add(a);const c=d.get(a);if(!c){t.push(`Cube '${a}' not found (referenced in measure '${r}')`);continue}c.measures[u]||t.push(`Measure '${u}' not found on cube '${a}'`)}if(e.dimensions)for(const r of e.dimensions){const[a,u]=r.split(".");if(!a||!u){t.push(`Invalid dimension format: ${r}. Expected format: 'CubeName.fieldName'`);continue}s.add(a);const c=d.get(a);if(!c){t.push(`Cube '${a}' not found (referenced in dimension '${r}')`);continue}c.dimensions[u]||t.push(`Dimension '${u}' not found on cube '${a}'`)}if(e.timeDimensions)for(const r of e.timeDimensions){const[a,u]=r.dimension.split(".");if(!a||!u){t.push(`Invalid timeDimension format: ${r.dimension}. Expected format: 'CubeName.fieldName'`);continue}s.add(a);const c=d.get(a);if(!c){t.push(`Cube '${a}' not found (referenced in timeDimension '${r.dimension}')`);continue}c.dimensions[u]||t.push(`TimeDimension '${u}' not found on cube '${a}' (must be a dimension with time type)`)}if(e.filters)for(const r of e.filters)ft(r,d,t,s);return s.size===0&&t.push("Query must reference at least one cube through measures, dimensions, or filters"),{isValid:t.length===0,errors:t}}function ft(d,e,t,n){if("and"in d||"or"in d){const a=d.and||d.or||[];for(const u of a)ft(u,e,t,n);return}if(!("member"in d)){t.push("Filter must have a member field");return}const[i,s]=d.member.split(".");if(!i||!s){t.push(`Invalid filter member format: ${d.member}. Expected format: 'CubeName.fieldName'`);return}n.add(i);const r=e.get(i);if(!r){t.push(`Cube '${i}' not found (referenced in filter '${d.member}')`);return}!r.dimensions[s]&&!r.measures[s]&&t.push(`Filter field '${s}' not found on cube '${i}' (must be a dimension or measure)`)}function Un(d){if(typeof d=="string"){const[e]=d.split(".");return e||null}return d.cube}const le=["2025-11-25","2025-06-18","2025-03-26"],pt="2025-11-25";function Qn(d){const t=Xn(d["mcp-protocol-version"])||pt;return{ok:le.includes(t),negotiated:le.includes(t)?t:null,supported:le}}function Kn(d){if(!d)return!1;const e=d.split(",").map(i=>i.trim().toLowerCase()),t=e.includes("text/event-stream"),n=e.includes("application/json");return t&&!n}const Wn="mcp-session-id";function Jn(d){if(!d)return!1;const e=d.split(",").map(i=>i.trim().toLowerCase().split(";")[0]),t=e.some(i=>i==="application/json"),n=e.some(i=>i==="text/event-stream");return t&&n}function zn(d,e={}){const{allowMissingOrigin:t=!0,allowedOrigins:n}=e;if(!d)return t?{valid:!0}:{valid:!1,reason:"Origin header is required"};if(!n||n.length===0)return{valid:!0};let i;try{i=new URL(d)}catch{return{valid:!1,reason:"Invalid Origin header format"}}return n.map(r=>{try{return new URL(r).origin}catch{return r}}).includes(i.origin)?{valid:!0}:{valid:!1,reason:"Origin not in allowed list"}}function qn(d,e,t){const n=[];return e&&n.push(`id: ${e}`),t&&t>0&&n.push(`retry: ${t}`),n.push("event: message"),n.push(`data: ${JSON.stringify(d)}`),n.push(""),n.join(`
|
|
201
|
+
`)}function Vn(d,e,t,n){return{jsonrpc:"2.0",id:d??null,error:{code:e,message:t,...n!==void 0?{data:n}:{}}}}function Gn(d,e){return{jsonrpc:"2.0",id:d??null,result:e}}function Hn(d){if(!d||typeof d!="object")return null;const e=d;return e.jsonrpc!=="2.0"||typeof e.method!="string"?null:{jsonrpc:"2.0",method:e.method,id:e.id,params:e.params}}async function Yn(d,e,t){const{semanticLayer:n,extractSecurityContext:i,rawRequest:s,rawResponse:r}=t,a=t.prompts??gt,u=t.resources??bt;switch(d){case"initialize":{const c=e?.protocolVersion;let l;return c&&le.includes(c)?l=c:l=pt,{protocolVersion:l,capabilities:{tools:{listChanged:!1},resources:{listChanged:!1},prompts:{listChanged:!1},sampling:{}},sessionId:ht(),serverInfo:{name:"drizzle-cube",version:typeof process<"u"?process.env?.npm_package_version||"dev":"worker"}}}case"list_tools":case"tools/list":return{tools:ei(),nextCursor:""};case"call_tool":case"tools/call":return ti(e,t);case"resources/list":return{resources:u.map(({uri:c,name:l,description:m,mimeType:p})=>({uri:c,name:l,description:m,mimeType:p})),nextCursor:""};case"resources/templates/list":return{resourceTemplates:[],nextCursor:""};case"resources/read":{const c=e?.uri,l=u.find(m=>m.uri===c)||u[0];if(!l)throw G(-32602,"resource not found");return{contents:[{uri:l.uri,mimeType:l.mimeType,text:l.text}]}}case"prompts/list":return{prompts:a.map(({name:c,description:l})=>({name:c,description:l})),nextCursor:""};case"ping":return{};case"notifications/initialized":return{};case"prompts/get":{const c=e?.name,l=a.find(m=>m.name===c)||a[0];if(!l)throw G(-32602,"prompt not found");return{name:l.name,description:l.description,messages:l.messages}}case"discover":return Y.handleDiscover(n,e||{});case"validate":{const c=e||{};if(!c.query)throw G(-32602,"query is required");return Y.handleValidate(n,c)}case"load":{const c=e||{};if(!c.query)throw G(-32602,"query is required");const l=await i(s,r);return Y.handleLoad(n,l,c)}default:throw G(-32601,`Unknown MCP method: ${d}`)}}function G(d,e,t){const n=new Error(e);return n.code=d,n}function Xn(d){return d?Array.isArray(d)?d[0]||null:d:null}function Zn(d){return d.id===void 0||d.id===null}function ht(){return`evt-${Y.generateRequestId()}`}function ei(){return[{name:"discover",description:`Find relevant cubes based on topic or intent. Call this FIRST to understand available data.
|
|
202
|
+
|
|
203
|
+
Returns cubes with:
|
|
204
|
+
- All measures and dimensions with their types
|
|
205
|
+
- Relationship information (joins) showing how cubes connect
|
|
206
|
+
- Metadata hints (eventStream for funnels, etc.)
|
|
207
|
+
|
|
208
|
+
IMPORTANT: The 'joins' property shows relationships between cubes. You can include dimensions from ANY related cube in your query - the system auto-joins them.
|
|
209
|
+
|
|
210
|
+
Example: If Productivity has a join to Employees, you can query:
|
|
211
|
+
{ "measures": ["Productivity.totalPullRequests"], "dimensions": ["Employees.name"] }`,inputSchema:{type:"object",properties:{topic:{type:"string",description:'Keyword to search (e.g., "sales", "employees")'},intent:{type:"string",description:'Natural language goal (e.g., "analyze productivity trends")'},limit:{type:"number",description:"Max results (default: 10)"},minScore:{type:"number",description:"Min relevance 0-1 (default: 0.1)"}}}},{name:"validate",description:`Validate a query and get auto-corrections for issues.
|
|
212
|
+
|
|
213
|
+
Checks:
|
|
214
|
+
- Field existence (measures, dimensions exist in schema)
|
|
215
|
+
- Filter syntax and operators
|
|
216
|
+
- Cross-cube join validity
|
|
217
|
+
|
|
218
|
+
Returns corrected query if issues found.`,inputSchema:{type:"object",required:["query"],properties:{query:{type:"object",description:"CubeQuery to validate"}}}},{name:"load",description:`Execute a semantic query and return aggregated results.
|
|
219
|
+
|
|
220
|
+
QUERY CONSTRUCTION RULES:
|
|
221
|
+
|
|
222
|
+
1. CROSS-CUBE JOINS (use dimensions from related cubes!)
|
|
223
|
+
Check 'joins' in discover results. Include dimensions from ANY related cube.
|
|
224
|
+
Example - get employee names with their productivity:
|
|
225
|
+
{
|
|
226
|
+
"measures": ["Productivity.totalPullRequests"],
|
|
227
|
+
"dimensions": ["Employees.name"],
|
|
228
|
+
"filters": [{ "member": "Productivity.date", "operator": "inDateRange", "values": ["last 3 months"] }]
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
2. DATE FILTERING vs TIME GROUPING
|
|
232
|
+
For AGGREGATED TOTALS: use 'filters' with 'inDateRange' (NOT timeDimensions)
|
|
233
|
+
{
|
|
234
|
+
"measures": ["Productivity.totalPullRequests"],
|
|
235
|
+
"dimensions": ["Employees.name"],
|
|
236
|
+
"filters": [{ "member": "Productivity.date", "operator": "inDateRange", "values": ["last 3 months"] }],
|
|
237
|
+
"order": { "Productivity.totalPullRequests": "desc" },
|
|
238
|
+
"limit": 5
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
For TIME SERIES: use 'timeDimensions' WITH 'granularity'
|
|
242
|
+
{
|
|
243
|
+
"measures": ["Productivity.totalPullRequests"],
|
|
244
|
+
"timeDimensions": [{ "dimension": "Productivity.date", "dateRange": "last 3 months", "granularity": "month" }]
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
WARNING: timeDimensions WITHOUT granularity groups by day, returning many rows!
|
|
248
|
+
|
|
249
|
+
3. TOP N PATTERN: filters + order + limit`,inputSchema:{type:"object",required:["query"],properties:{query:{type:"object",description:`CubeQuery object with:
|
|
250
|
+
- measures: string[] - Aggregations (from any cube)
|
|
251
|
+
- dimensions: string[] - Grouping fields (can be from RELATED cubes via joins)
|
|
252
|
+
- filters: [{ member, operator, values }] - Use 'inDateRange' for date filtering
|
|
253
|
+
- timeDimensions: [{ dimension, granularity, dateRange }] - ONLY for time series
|
|
254
|
+
- order: { "Cube.field": "asc"|"desc" }
|
|
255
|
+
- limit: number`}}}}]}async function ti(d,e){const{semanticLayer:t,extractSecurityContext:n,rawRequest:i,rawResponse:s}=e,r=d||{};if(!r.name)throw G(-32602,"name is required for tools/call");const a=r.arguments;switch(r.name){case"discover":return _e(await Y.handleDiscover(t,a||{}));case"validate":{const u=a||{};if(!u.query)throw G(-32602,"query is required");return _e(await Y.handleValidate(t,u))}case"load":{const u=a||{};if(!u.query)throw G(-32602,"query is required");const c=await n(i,s);return _e(await Y.handleLoad(t,c,u))}default:throw G(-32601,`Unknown tool: ${r.name}`)}}function _e(d){return{content:[{type:"text",text:typeof d=="string"?d:JSON.stringify(d)}],isError:!1}}const gt=kn(),bt=[{uri:"drizzle-cube://quickstart",name:"Drizzle Cube MCP Quickstart",description:"Minimal guide for using discover/suggest/validate/load",mimeType:"text/markdown",text:["# Drizzle Cube MCP Quickstart","","Tools:","- discover: { topic?, intent?, limit?, minScore? } → cubes list","- suggest: { naturalLanguage, cube? } → draft query","- validate: { query } → corrected query + issues","- load: { query } → data + annotation","","Recommended flow:","1) tools/list",'2) tools/call name=discover intent="<goal>"','3) tools/call name=suggest naturalLanguage="<goal>"',"4) tools/call name=validate query=<from suggest>","5) tools/call name=load query=<validated>","","Query shapes supported:","- regular Cube.js-style query { measures, dimensions, filters, timeDimensions, order, limit, offset }","- funnel { bindingKey, timeDimension, steps[], includeTimeMetrics? }","- flow { bindingKey, eventDimension, steps?, window? }","- retention { bindingKey, timeDimension, periods, granularity, retentionType, breakdownDimensions }","","Filter rules: flat arrays of { member, operator, values }; do not nest arrays."].join(`
|
|
256
|
+
`)},{uri:"drizzle-cube://query-shapes",name:"Query Shapes Reference",description:"Detailed schema examples for regular, funnel, flow, and retention queries",mimeType:"text/markdown",text:["# Query Shapes","","## Regular query","```json","{",' "measures": ["Sales.count"],',' "dimensions": ["Sales.channel"],',' "filters": [ { "member": "Sales.status", "operator": "equals", "values": ["paid"] } ],',' "timeDimensions": [ { "dimension": "Sales.createdAt", "dateRange": "last 30 days", "granularity": "day" } ],',' "order": { "Sales.createdAt": "asc" },',' "limit": 500',"}","```","","## Funnel","```json","{",' "funnel": {',' "bindingKey": "Events.userId",',' "timeDimension": "Events.timestamp",',' "steps": [',' { "name": "Signup", "filter": [{ "member": "Events.eventType", "operator": "equals", "values": ["signup"] }] },',' { "name": "Purchase", "filter": [{ "member": "Events.eventType", "operator": "equals", "values": ["purchase"] }] }'," ],",' "includeTimeMetrics": true'," }","}","```","","## Flow","```json","{",' "flow": {',' "bindingKey": "Events.sessionId",',' "eventDimension": "Events.eventType",',' "steps": ["view", "add_to_cart", "checkout"],',' "window": { "unit": "minute", "value": 30 }'," }","}","```","","## Retention","```json","{",' "retention": {',' "bindingKey": "Users.id",',' "timeDimension": "Events.timestamp",',' "periods": 8,',' "granularity": "week",',' "retentionType": "rolling",',' "breakdownDimensions": ["Events.country"]'," }","}","```","","### Filter rules","- Always a flat array of filter objects: [{ member, operator, values }]","- For funnels, put time filter (inDateRange) only on step 0","- Operators: equals, notEquals, inDateRange, gt, gte, lt, lte, contains, notContains, set, notSet","","### Time handling",'- Relative ranges ("last 3 months") -> add ONLY an inDateRange filter on the time dimension (do NOT add timeDimensions unless grouping is requested).','- Grouping ("by month/week/day") -> add timeDimensions entry with granularity.',"- Both can be combined: inDateRange filter + timeDimensions granularity."].join(`
|
|
257
|
+
`)}];function ni(){return bt}function ii(){return gt}exports.MCP_SESSION_ID_HEADER=Wn;exports.SemanticLayerCompiler=Ie;exports.buildJsonRpcError=Vn;exports.buildJsonRpcResult=Gn;exports.dispatchMcpMethod=Yn;exports.getDefaultPrompts=ii;exports.getDefaultResources=ni;exports.isNotification=Zn;exports.negotiateProtocol=Qn;exports.parseJsonRpc=Hn;exports.primeEventId=ht;exports.serializeSseEvent=qn;exports.validateAcceptHeader=Jn;exports.validateOriginHeader=zn;exports.wantsEventStream=Kn;
|