Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@uwdata/mosaic-sql

Package Overview
Dependencies
Maintainers
2
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@uwdata/mosaic-sql - npm Package Compare versions

Comparing version 0.7.0 to 0.8.0

242

dist/mosaic-sql.js

@@ -6,9 +6,7 @@ // src/ref.js

* @param {string|Ref|null} table The table name.
* @param {string|null} column The column name.
* @param {string|null} [column] The column name.
*/
constructor(table, column2) {
if (table)
this.table = String(table);
if (column2)
this.column = column2;
if (table) this.table = String(table);
if (column2) this.column = column2;
}

@@ -52,3 +50,3 @@ /**

}
function column(table, column2) {
function column(table, column2 = null) {
if (arguments.length === 1) {

@@ -81,4 +79,3 @@ column2 = table;

const ts = +value;
if (Number.isNaN(ts))
return "NULL";
if (Number.isNaN(ts)) return "NULL";
const y2 = value.getUTCFullYear();

@@ -104,3 +101,3 @@ const m = value.getUTCMonth();

* Create a new SQL expression instance.
* @param {(string|SQLExpression|Ref)[]} parts The parts of the expression.
* @param {(string | ParamLike | SQLExpression | import('./ref.js').Ref)[]} parts The parts of the expression.
* @param {string[]} [columns=[]] The column dependencies

@@ -297,2 +294,12 @@ * @param {object} [props] Additional properties for this expression.

var WindowFunction = class _WindowFunction extends SQLExpression {
/**
* Create a new WindowFunction instance.
* @param {string} op The window operation indicator.
* @param {*} func The window function expression.
* @param {*} [type] The SQL data type to cast to.
* @param {string} [name] The window definition name.
* @param {*} [group] Grouping (partition by) expressions.
* @param {*} [order] Sorting (order by) expressions.
* @param {*} [frame] The window frame definition.
*/
constructor(op, func, type, name, group = "", order = "", frame = "") {

@@ -312,3 +319,10 @@ let expr;

const { _expr, _deps } = expr;
super(_expr, _deps, { window: op, func, type, name, group, order, frame });
super(_expr, _deps);
this.window = op;
this.func = func;
this.type = type;
this.name = name;
this.group = group;
this.order = order;
this.frame = frame;
}

@@ -322,2 +336,7 @@ get basis() {

}
/**
* Return an updated window function over a named window definition.
* @param {string} name The window definition name.
* @returns {WindowFunction} A new window function.
*/
over(name) {

@@ -327,2 +346,7 @@ const { window: op, func, type, group, order, frame } = this;

}
/**
* Return an updated window function with the given partitioning.
* @param {*} expr The grouping (partition by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
partitionby(...expr) {

@@ -337,2 +361,7 @@ const exprs = expr.flat().filter((x2) => x2).map(asColumn);

}
/**
* Return an updated window function with the given ordering.
* @param {*} expr The sorting (order by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
orderby(...expr) {

@@ -347,2 +376,7 @@ const exprs = expr.flat().filter((x2) => x2).map(asColumn);

}
/**
* Return an updated window function with the given rows frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} expr The row-based window frame.
* @returns {WindowFunction} A new window function.
*/
rows(expr) {

@@ -353,2 +387,7 @@ const frame = windowFrame("ROWS", expr);

}
/**
* Return an updated window function with the given range frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} expr The range-based window frame.
* @returns {WindowFunction} A new window function.
*/
range(expr) {

@@ -397,2 +436,10 @@ const frame = windowFrame("RANGE", expr);

var AggregateFunction = class _AggregateFunction extends SQLExpression {
/**
* Create a new AggregateFunction instance.
* @param {*} op The aggregate operation.
* @param {*} [args] The aggregate function arguments.
* @param {*} [type] The SQL data type to cast to.
* @param {boolean} [isDistinct] Flag indicating if this is a distinct value aggregate.
* @param {*} [filter] Filtering expression to apply prior to aggregation.
*/
constructor(op, args, type, isDistinct2, filter) {

@@ -402,3 +449,8 @@ args = (args || []).map(asColumn);

const { spans, cols } = parseSQL(strings, exprs);
super(spans, cols, { aggregate: op, args, type, isDistinct: isDistinct2, filter });
super(spans, cols);
this.aggregate = op;
this.args = args;
this.type = type;
this.isDistinct = isDistinct2;
this.filter = filter;
}

@@ -414,2 +466,6 @@ get basis() {

}
/**
* Return a new derived aggregate function over distinct values.
* @returns {AggregateFunction} A new aggregate function.
*/
distinct() {

@@ -419,2 +475,7 @@ const { aggregate: op, args, type, filter } = this;

}
/**
* Return a new derived aggregate function that filters values.
* @param {*} filter The filter expresion.
* @returns {AggregateFunction} A new aggregate function.
*/
where(filter) {

@@ -424,2 +485,6 @@ const { aggregate: op, args, type, isDistinct: isDistinct2 } = this;

}
/**
* Return a new window function over this aggregate.
* @returns {WindowFunction} A new aggregate function.
*/
window() {

@@ -430,13 +495,33 @@ const { aggregate: op, args, type, isDistinct: isDistinct2 } = this;

}
/**
* Return a window function over this aggregate with the given partitioning.
* @param {*} expr The grouping (partition by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
partitionby(...expr) {
return this.window().partitionby(...expr);
}
/**
* Return a window function over this aggregate with the given ordering.
* @param {*} expr The sorting (order by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
orderby(...expr) {
return this.window().orderby(...expr);
}
rows(prev, next) {
return this.window().rows(prev, next);
/**
* Return a window function over this aggregate with the given row frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} frame The row-based window frame.
* @returns {WindowFunction} A new window function.
*/
rows(frame) {
return this.window().rows(frame);
}
range(prev, next) {
return this.window().range(prev, next);
/**
* Return a window function over this aggregate with the given range frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} frame The range-based window frame.
* @returns {WindowFunction} A new window function.
*/
range(frame) {
return this.window().range(frame);
}

@@ -593,2 +678,3 @@ };

};
this.cteFor = null;
}

@@ -600,2 +686,11 @@ clone() {

}
/**
* Retrieve current WITH common table expressions (CTEs).
* @returns {any[]}
*/
/**
* Add WITH common table expressions (CTEs).
* @param {...any} expr Expressions to add.
* @returns {this}
*/
with(...expr) {

@@ -626,2 +721,11 @@ const { query } = this;

}
/**
* Retrieve current SELECT expressions.
* @returns {any[]}
*/
/**
* Add SELECT expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
select(...expr) {

@@ -659,2 +763,11 @@ const { query } = this;

}
/**
* Retrieve current from expressions.
* @returns {any[]}
*/
/**
* Provide table from expressions.
* @param {...any} expr
* @returns {this}
*/
from(...expr) {

@@ -690,2 +803,12 @@ const { query } = this;

}
/**
* Retrieve current SAMPLE settings.
* @returns {any[]}
*/
/**
* Set SAMPLE settings.
* @param {number|object} value The percentage or number of rows to sample.
* @param {string} [method] The sampling method to use.
* @returns {this}
*/
sample(value, method) {

@@ -704,2 +827,11 @@ const { query } = this;

}
/**
* Retrieve current WHERE expressions.
* @returns {any[]}
*/
/**
* Add WHERE expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
where(...expr) {

@@ -720,2 +852,11 @@ const { query } = this;

}
/**
* Retrieve current GROUP BY expressions.
* @returns {any[]}
*/
/**
* Add GROUP BY expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
groupby(...expr) {

@@ -736,2 +877,11 @@ const { query } = this;

}
/**
* Retrieve current HAVING expressions.
* @returns {any[]}
*/
/**
* Add HAVING expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
having(...expr) {

@@ -748,2 +898,11 @@ const { query } = this;

}
/**
* Retrieve current WINDOW definitions.
* @returns {any[]}
*/
/**
* Add WINDOW definitions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
window(...expr) {

@@ -767,2 +926,11 @@ const { query } = this;

}
/**
* Retrieve current QUALIFY expressions.
* @returns {any[]}
*/
/**
* Add QUALIFY expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
qualify(...expr) {

@@ -779,2 +947,11 @@ const { query } = this;

}
/**
* Retrieve current ORDER BY expressions.
* @returns {any[]}
*/
/**
* Add ORDER BY expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
orderby(...expr) {

@@ -791,2 +968,11 @@ const { query } = this;

}
/**
* Retrieve current LIMIT value.
* @returns {number|null}
*/
/**
* Set the query result LIMIT.
* @param {number} value The limit value.
* @returns {this}
*/
limit(value) {

@@ -801,2 +987,11 @@ const { query } = this;

}
/**
* Retrieve current OFFSET value.
* @returns {number|null}
*/
/**
* Set the query result OFFSET.
* @param {number} value The offset value.
* @returns {this}
*/
offset(value) {

@@ -860,4 +1055,3 @@ const { query } = this;

const clauses = where.map(String).filter((x2) => x2).join(" AND ");
if (clauses)
sql2.push(`WHERE ${clauses}`);
if (clauses) sql2.push(`WHERE ${clauses}`);
}

@@ -875,4 +1069,3 @@ if (sample) {

const clauses = having.map(String).filter((x2) => x2).join(" AND ");
if (clauses)
sql2.push(`HAVING ${clauses}`);
if (clauses) sql2.push(`HAVING ${clauses}`);
}

@@ -885,4 +1078,3 @@ if (window.length) {

const clauses = qualify.map(String).filter((x2) => x2).join(" AND ");
if (clauses)
sql2.push(`QUALIFY ${clauses}`);
if (clauses) sql2.push(`QUALIFY ${clauses}`);
}

@@ -906,2 +1098,3 @@ if (orderby.length) {

this.query = { orderby: [] };
this.cteFor = null;
}

@@ -944,4 +1137,3 @@ clone() {

const { queries, cteFor } = this;
if (cteFor)
queries.forEach((q) => q.cteFor = cteFor);
if (cteFor) queries.forEach((q) => q.cteFor = cteFor);
return queries;

@@ -987,3 +1179,3 @@ }

}
function scaleLog({ base } = {}) {
function scaleLog({ base = null } = {}) {
if (base == null || base === Math.E) {

@@ -1119,3 +1311,3 @@ return {

const open = Array.isArray(opt) ? opt.join(", ") : typeof opt === "string" ? opt : Object.entries(opt).map(([key, value]) => `${key}=${value}`).join(", ");
rest.open_options = open.toUpperCase();
Object.assign(rest, { open_options: open.toUpperCase() });
}

@@ -1122,0 +1314,0 @@ return load("st_read", tableName, fileName, rest);

2

dist/mosaic-sql.min.js

@@ -1,1 +0,1 @@

var S=class{constructor(t,e){t&&(this.table=String(t)),e&&(this.column=e)}get columns(){return this.column?[this.column]:[]}toString(){let{table:t,column:e}=this;if(e){let n=e.startsWith("*")?e:`"${e}"`;return`${t?`${V(t)}.`:""}${n}`}else return t?V(t):"NULL"}};function V(r){return r.split(".").map(e=>`"${e}"`).join(".")}function k(r,t){return r instanceof S&&r.column===t}function u(r){return typeof r=="string"?K(r):r}function O(r){return typeof r=="string"?H(r):r}function H(r){return new S(r)}function K(r,t){return arguments.length===1&&(t=r,r=null),new S(r,t)}function ut(r){return new S(r,"*")}function lt(r){return typeof r=="string"?`"${r}"`:$(r)}function $(r){switch(typeof r){case"boolean":return r?"TRUE":"FALSE";case"string":return`'${r}'`;case"number":return Number.isFinite(r)?String(r):"NULL";default:if(r==null)return"NULL";if(r instanceof Date){let t=+r;if(Number.isNaN(t))return"NULL";let e=r.getUTCFullYear(),n=r.getUTCMonth(),o=r.getUTCDate();return t===Date.UTC(e,n,o)?`MAKE_DATE(${e}, ${n+1}, ${o})`:`EPOCH_MS(${t})`}else return r instanceof RegExp?`'${r.source}'`:String(r)}}var T=r=>typeof r?.addEventListener=="function";function _(r){return r instanceof N}var N=class{constructor(t,e,n){this._expr=Array.isArray(t)?t:[t],this._deps=e||[],this.annotate(n);let o=this._expr.filter(s=>T(s));o.length>0?(this._params=Array.from(new Set(o)),this._params.forEach(s=>{s.addEventListener("value",()=>pt(this,this.map?.get("value")))})):this.addEventListener=void 0}get value(){return this}get columns(){let{_params:t,_deps:e}=this;if(t){let n=new Set(t.flatMap(o=>{let s=o.value?.columns;return Array.isArray(s)?s:[]}));if(n.size){let o=new Set(e);return n.forEach(s=>o.add(s)),Array.from(o)}}return e}get column(){return this._deps.length?this._deps[0]:this.columns[0]}annotate(...t){return Object.assign(this,...t)}toString(){return this._expr.map(t=>T(t)&&!_(t)?$(t.value):t).join("")}addEventListener(t,e){let n=this.map||(this.map=new Map);(n.get(t)||(n.set(t,new Set),n.get(t))).add(e)}};function pt(r,t){if(t?.size)return Promise.allSettled(Array.from(t,e=>e(r)))}function W(r,t){let e=[r[0]],n=new Set,o=t.length;for(let s=0,i=0;s<o;){let a=t[s];T(a)?e[++i]=a:(Array.isArray(a?.columns)&&a.columns.forEach(d=>n.add(d)),e[i]+=typeof a=="string"?a:$(a));let p=r[++s];T(e[i])?e[++i]=p:e[i]+=p}return{spans:e,cols:Array.from(n)}}function c(r,...t){let{spans:e,cols:n}=W(r,t);return new N(e,n)}function ft(r){let t=u(r);return c`${t} DESC NULLS LAST`.annotate({label:t?.label,desc:!0})}var ht=r=>({value:r,toString:()=>$(r)});function D(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function z(r,t){let e=t.filter(o=>o!=null).map(u),n=e.map((o,s)=>s?` ${r} `:"");return e.length===1?n.push(""):e.length>1&&(n[0]="(",n.push(")")),c(n,...e).annotate({op:r,children:e,visit:D})}var mt=(...r)=>z("AND",r.flat()),gt=(...r)=>z("OR",r.flat()),dt=r=>t=>c`(${r} ${u(t)})`.annotate({op:r,a:t,visit:D}),xt=dt("NOT"),J=r=>t=>c`(${u(t)} ${r})`.annotate({op:r,a:t,visit:D}),$t=J("IS NULL"),Et=J("IS NOT NULL"),w=r=>(t,e)=>c`(${u(t)} ${r} ${u(e)})`.annotate({op:r,a:t,b:e,visit:D}),yt=w("="),St=w("<>"),Nt=w("<"),wt=w(">"),At=w("<="),Tt=w(">="),Rt=w("IS DISTINCT FROM"),qt=w("IS NOT DISTINCT FROM");function Z(r,t,e,n){t=u(t);let o=r.startsWith("NOT ")?"NOT ":"";return(e?n?c`${o}(${e[0]} <= ${t} AND ${t} < ${e[1]})`:c`(${t} ${r} ${e[0]} AND ${e[1]})`:c``).annotate({op:r,visit:D,field:t,range:e})}var bt=(r,t,e)=>Z("BETWEEN",r,t,e),It=(r,t,e)=>Z("NOT BETWEEN",r,t,e);function R(r,t){return Array.from({length:r},()=>t)}function m(r,t){return(...e)=>{let n=e.map(u),o=t?`::${t}`:"";return(n.length?c([`${r}(`,...R(n.length-1,", "),`)${o}`],...n):c`${r}()${o}`).annotate({func:r,args:n})}}var Lt=m("REGEXP_MATCHES"),Ot=m("CONTAINS"),Dt=m("PREFIX"),Ct=m("SUFFIX"),Mt=m("LOWER"),_t=m("UPPER"),Pt=m("LENGTH"),Ft=m("ISNAN"),Gt=m("ISFINITE"),Ut=m("ISINF");var C=class r extends N{constructor(t,e,n,o,s="",i="",a=""){let p;if(o&&!(s||i||a))p=o?c`${e} OVER "${o}"`:c`${e} OVER ()`;else{let b=s&&i?" ":"",I=(s||i)&&a?" ":"";p=c`${e} OVER (${o?`"${o}" `:""}${s}${b}${i}${I}${a})`}n&&(p=c`(${p})::${n}`);let{_expr:y,_deps:A}=p;super(y,A,{window:t,func:e,type:n,name:o,group:s,order:i,frame:a})}get basis(){return this.column}get label(){let{func:t}=this;return t.label??t.toString()}over(t){let{window:e,func:n,type:o,group:s,order:i,frame:a}=this;return new r(e,n,o,t,s,i,a)}partitionby(...t){let e=t.flat().filter(y=>y).map(u),n=c(["PARTITION BY ",R(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:a,order:p,frame:d}=this;return new r(o,s,i,a,n,p,d)}orderby(...t){let e=t.flat().filter(y=>y).map(u),n=c(["ORDER BY ",R(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:a,group:p,frame:d}=this;return new r(o,s,i,a,p,n,d)}rows(t){let e=tt("ROWS",t),{window:n,func:o,type:s,name:i,group:a,order:p}=this;return new r(n,o,s,i,a,p,e)}range(t){let e=tt("RANGE",t),{window:n,func:o,type:s,name:i,group:a,order:p}=this;return new r(n,o,s,i,a,p,e)}};function tt(r,t){if(T(t)){let e=c`${t}`;return e.toString=()=>`${r} ${et(t.value)}`,e}return`${r} ${et(t)}`}function et(r){let[t,e]=r,n=t===0?"CURRENT ROW":Number.isFinite(t)?`${Math.abs(t)} PRECEDING`:"UNBOUNDED PRECEDING",o=e===0?"CURRENT ROW":Number.isFinite(e)?`${Math.abs(e)} FOLLOWING`:"UNBOUNDED FOLLOWING";return`BETWEEN ${n} AND ${o}`}function E(r,t){return(...e)=>{let n=m(r)(...e);return new C(r,n,t)}}var jt=E("ROW_NUMBER","INTEGER"),Wt=E("RANK","INTEGER"),Yt=E("DENSE_RANK","INTEGER"),Bt=E("PERCENT_RANK"),Xt=E("CUME_DIST"),vt=E("NTILE"),Qt=E("LAG"),Vt=E("LEAD"),kt=E("FIRST_VALUE"),Ht=E("LAST_VALUE"),Kt=E("NTH_VALUE");function zt(r,...t){return c(r,...t).annotate({aggregate:!0})}var Y=class r extends N{constructor(t,e,n,o,s){e=(e||[]).map(u);let{strings:i,exprs:a}=Jt(t,e,n,o,s),{spans:p,cols:d}=W(i,a);super(p,d,{aggregate:t,args:e,type:n,isDistinct:o,filter:s})}get basis(){return this.column}get label(){let{aggregate:t,args:e,isDistinct:n}=this,o=n?"DISTINCT"+(e.length?" ":""):"",s=e.length?`(${o}${e.map(Zt).join(", ")})`:"";return`${t.toLowerCase()}${s}`}distinct(){let{aggregate:t,args:e,type:n,filter:o}=this;return new r(t,e,n,!0,o)}where(t){let{aggregate:e,args:n,type:o,isDistinct:s}=this;return new r(e,n,o,s,t)}window(){let{aggregate:t,args:e,type:n,isDistinct:o}=this,s=new r(t,e,null,o);return new C(t,s,n)}partitionby(...t){return this.window().partitionby(...t)}orderby(...t){return this.window().orderby(...t)}rows(t,e){return this.window().rows(t,e)}range(t,e){return this.window().range(t,e)}};function Jt(r,t,e,n,o){let s=`)${e?`::${e}`:""}`,i=[`${r}(${n?"DISTINCT ":""}`],a=[];return t.length?(i=i.concat([...R(t.length-1,", "),`${s}${o?" FILTER (WHERE ":""}`,...o?[")"]:[]]),a=[...t,...o?[o]:[]]):i[0]+="*"+s,{exprs:a,strings:i}}function Zt(r){let t=$(r);return t&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function l(r,t){return(...e)=>new Y(r,e,t)}var te=l("COUNT","INTEGER"),ee=l("AVG"),re=l("AVG"),ne=l("MAD"),oe=l("MAX"),se=l("MIN"),ie=l("SUM","DOUBLE"),ce=l("PRODUCT"),ae=l("MEDIAN"),ue=l("QUANTILE"),le=l("MODE"),pe=l("VARIANCE"),fe=l("STDDEV"),he=l("SKEWNESS"),me=l("KURTOSIS"),ge=l("ENTROPY"),de=l("VAR_POP"),xe=l("STDDEV_POP"),$e=l("CORR"),Ee=l("COVAR_POP"),ye=l("REGR_INTERCEPT"),Se=l("REGR_SLOPE"),Ne=l("REGR_COUNT"),we=l("REGR_R2"),Ae=l("REGR_SYY"),Te=l("REGR_SXX"),Re=l("REGR_SXY"),qe=l("REGR_AVGX"),be=l("REGR_AVGY"),Ie=l("FIRST"),Le=l("LAST"),Oe=l("ARG_MIN"),De=l("ARG_MAX"),Ce=l("STRING_AGG"),Me=l("ARRAY_AGG");function B(r,t){let e=u(r),n=c`CAST(${e} AS ${t})`;return Object.defineProperty(n,"label",{enumerable:!0,get(){return r.label}}),Object.defineProperty(n,"aggregate",{enumerable:!0,get(){return r.aggregate||!1}}),n}var _e=r=>B(r,"DOUBLE"),Pe=r=>B(r,"INTEGER");var X=r=>c`epoch_ms(${u(r)})`,Fe=r=>{let t=u(r);return c`MAKE_DATE(2012, MONTH(${t}), 1)`.annotate({label:"month"})},Ge=r=>{let t=u(r);return c`MAKE_DATE(2012, MONTH(${t}), DAY(${t}))`.annotate({label:"date"})},Ue=r=>{let t=u(r);return c`MAKE_DATE(2012, 1, DAY(${t}))`.annotate({label:"date"})};var je=m("ST_AsGeoJSON"),rt=m("ST_X"),nt=m("ST_Y"),v=m("ST_CENTROID"),We=r=>rt(v(r)),Ye=r=>nt(v(r));var F=class r{static select(...t){return new r().select(...t)}static from(...t){return new r().from(...t)}static with(...t){return new r().with(...t)}static union(...t){return new q("UNION",t.flat())}static unionAll(...t){return new q("UNION ALL",t.flat())}static intersect(...t){return new q("INTERSECT",t.flat())}static except(...t){return new q("EXCEPT",t.flat())}static describe(t){let e=t.clone(),{clone:n,toString:o}=e;return Object.assign(e,{describe:!0,clone:()=>r.describe(n.call(e)),toString:()=>`DESCRIBE ${o.call(e)}`})}constructor(){this.query={with:[],select:[],from:[],where:[],groupby:[],having:[],window:[],qualify:[],orderby:[]}}clone(){let t=new r;return t.query={...this.query},t}with(...t){let{query:e}=this;if(t.length===0)return e.with;{let n=[],o=(s,i)=>{let a=i.clone();a.cteFor=this,n.push({as:s,query:a})};return t.flat().forEach(s=>{if(s!=null)if(s.as&&s.query)o(s.as,s.query);else for(let i in s)o(i,s[i])}),e.with=e.with.concat(n),this}}select(...t){let{query:e}=this;if(t.length===0)return e.select;{let n=[];for(let o of t.flat())if(o!=null)if(typeof o=="string")n.push({as:o,expr:u(o)});else if(o instanceof S)n.push({as:o.column,expr:o});else if(Array.isArray(o))n.push({as:o[0],expr:o[1]});else for(let s in o)n.push({as:P(s),expr:u(o[s])});return e.select=e.select.concat(n),this}}$select(...t){return this.query.select=[],this.select(...t)}distinct(t=!0){return this.query.distinct=!!t,this}from(...t){let{query:e}=this;if(t.length===0)return e.from;{let n=[];return t.flat().forEach(o=>{if(o!=null)if(typeof o=="string")n.push({as:o,from:O(o)});else if(o instanceof S)n.push({as:o.table,from:o});else if(M(o)||_(o))n.push({from:o});else if(Array.isArray(o))n.push({as:P(o[0]),from:O(o[1])});else for(let s in o)n.push({as:P(s),from:O(o[s])})}),e.from=e.from.concat(n),this}}$from(...t){return this.query.from=[],this.from(...t)}sample(t,e){let{query:n}=this;if(arguments.length===0)return n.sample;{let o=t;return typeof t=="number"&&(o=t>0&&t<1?{perc:100*t,method:e}:{rows:Math.round(t),method:e}),n.sample=o,this}}where(...t){let{query:e}=this;return t.length===0?e.where:(e.where=e.where.concat(t.flat().filter(n=>n)),this)}$where(...t){return this.query.where=[],this.where(...t)}groupby(...t){let{query:e}=this;return t.length===0?e.groupby:(e.groupby=e.groupby.concat(t.flat().filter(n=>n).map(u)),this)}$groupby(...t){return this.query.groupby=[],this.groupby(...t)}having(...t){let{query:e}=this;return t.length===0?e.having:(e.having=e.having.concat(t.flat().filter(n=>n)),this)}window(...t){let{query:e}=this;if(t.length===0)return e.window;{let n=[];return t.flat().forEach(o=>{if(o!=null)for(let s in o)n.push({as:P(s),expr:o[s]})}),e.window=e.window.concat(n),this}}qualify(...t){let{query:e}=this;return t.length===0?e.qualify:(e.qualify=e.qualify.concat(t.flat().filter(n=>n)),this)}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(n=>n).map(u)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{query:t,cteFor:e}=this,o=(e?.query||t).with?.reduce((i,{as:a,query:p})=>(i[a]=p,i),{}),s=[];return t.from.forEach(({from:i})=>{if(M(i))s.push(i);else if(o[i.table]){let a=o[i.table];s.push(a)}}),s}toString(){let{with:t,select:e,distinct:n,from:o,sample:s,where:i,groupby:a,having:p,window:d,qualify:y,orderby:A,limit:b,offset:I}=this.query,g=[];if(t.length){let f=t.map(({as:h,query:x})=>`"${h}" AS (${x})`);g.push(`WITH ${f.join(", ")}`)}let it=e.map(({as:f,expr:h})=>k(h,f)&&!h.table?`${h}`:`${h} AS "${f}"`);if(g.push(`SELECT${n?" DISTINCT":""} ${it.join(", ")}`),o.length){let f=o.map(({as:h,from:x})=>{let L=M(x)?`(${x})`:`${x}`;return!h||h===x.table?L:`${L} AS "${h}"`});g.push(`FROM ${f.join(", ")}`)}if(i.length){let f=i.map(String).filter(h=>h).join(" AND ");f&&g.push(`WHERE ${f}`)}if(s){let{rows:f,perc:h,method:x,seed:L}=s,ct=f?`${f} ROWS`:`${h} PERCENT`,at=x?` (${x}${L!=null?`, ${L}`:""})`:"";g.push(`USING SAMPLE ${ct}${at}`)}if(a.length&&g.push(`GROUP BY ${a.join(", ")}`),p.length){let f=p.map(String).filter(h=>h).join(" AND ");f&&g.push(`HAVING ${f}`)}if(d.length){let f=d.map(({as:h,expr:x})=>`"${h}" AS (${x})`);g.push(`WINDOW ${f.join(", ")}`)}if(y.length){let f=y.map(String).filter(h=>h).join(" AND ");f&&g.push(`QUALIFY ${f}`)}return A.length&&g.push(`ORDER BY ${A.join(", ")}`),Number.isFinite(b)&&g.push(`LIMIT ${b}`),Number.isFinite(I)&&g.push(`OFFSET ${I}`),g.join(" ")}},q=class r{constructor(t,e){this.op=t,this.queries=e.map(n=>n.clone()),this.query={orderby:[]}}clone(){let t=new r(this.op,this.queries);return t.query={...this.query},t}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(n=>n).map(u)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{queries:t,cteFor:e}=this;return e&&t.forEach(n=>n.cteFor=e),t}toString(){let{op:t,queries:e,query:{orderby:n,limit:o,offset:s}}=this,i=[e.join(` ${t} `)];return n.length&&i.push(`ORDER BY ${n.join(", ")}`),Number.isFinite(o)&&i.push(`LIMIT ${o}`),Number.isFinite(s)&&i.push(`OFFSET ${s}`),i.join(" ")}};function M(r){return r instanceof F||r instanceof q}function Be(r){return M(r)&&r.describe}function P(r){return Xe(r)?r.slice(1,-1):r}function Xe(r){return r[0]==='"'&&r[r.length-1]==='"'}var G=r=>r;function ve(){return{apply:G,invert:G,sqlApply:u,sqlInvert:G}}function Qe({base:r}={}){if(r==null||r===Math.E)return{apply:Math.log,invert:Math.exp,sqlApply:t=>c`LN(${u(t)})`,sqlInvert:t=>c`EXP(${t})`};if(r===10)return{apply:Math.log10,invert:t=>Math.pow(10,t),sqlApply:t=>c`LOG(${u(t)})`,sqlInvert:t=>c`POW(10, ${t})`};{let t=+r;return{apply:e=>Math.log(e)/Math.log(t),invert:e=>Math.pow(t,e),sqlApply:e=>c`LN(${u(e)}) / LN(${t})`,sqlInvert:e=>c`POW(${t}, ${e})`}}}function Ve({constant:r=1}={}){let t=+r;return{apply:e=>Math.sign(e)*Math.log1p(Math.abs(e)),invert:e=>Math.sign(e)*Math.exp(Math.abs(e)-t),sqlApply:e=>(e=u(e),c`SIGN(${e}) * LN(${t} + ABS(${e}))`),sqlInvert:e=>c`SIGN(${e}) * (EXP(ABS(${e})) - ${t})`}}function ke(){return{apply:r=>Math.sign(r)*Math.sqrt(Math.abs(r)),invert:r=>Math.sign(r)*r*r,sqlApply:r=>(r=u(r),c`SIGN(${r}) * SQRT(ABS(${r}))`),sqlInvert:r=>c`SIGN(${r}) * (${r}) ** 2`}}function He({exponent:r=1}={}){let t=+r;return{apply:e=>Math.sign(e)*Math.pow(Math.abs(e),t),invert:e=>Math.sign(e)*Math.pow(Math.abs(e),1/t),sqlApply:e=>(e=u(e),c`SIGN(${e}) * POW(ABS(${e}), ${t})`),sqlInvert:e=>c`SIGN(${e}) * POW(ABS(${e}), 1/${t})`}}function ot(){return{apply:r=>+r,invert:r=>new Date(r),sqlApply:r=>r instanceof Date?+r:X(u(r)),sqlInvert:G}}var Ke={linear:ve,log:Qe,symlog:Ve,sqrt:ke,pow:He,time:ot,utc:ot};function ze(r){let t=Ke[r.type];return t?{...r,...t(r)}:null}function U(r,t,{replace:e=!1,temp:n=!0,view:o=!1}={}){return"CREATE"+(e?" OR REPLACE ":" ")+(n?"TEMP ":"")+(o?"VIEW":"TABLE")+(e?" ":" IF NOT EXISTS ")+r+" AS "+t}function Je(r){return`INSTALL ${r}; LOAD ${r}`}function st(r,{columns:t=Object.keys(r?.[0]||{})}={}){let e=[];if(Array.isArray(t)?(e=t,t=e.reduce((o,s)=>(o[s]=s,o),{})):t&&(e=Object.keys(t)),!e.length)throw new Error("Can not create table from empty column set.");let n=[];for(let o of r){let s=e.map(i=>`${$(o[i])} AS "${t[i]}"`);n.push(`(SELECT ${s.join(", ")})`)}return n.join(" UNION ALL ")}function j(r,t,e,n={},o={}){let{select:s=["*"],where:i,view:a,temp:p,replace:d,...y}=n,A=or({...o,...y}),b=`${r}('${e}'${A?", "+A:""})`,I=i?` WHERE ${i}`:"",g=`SELECT ${s.join(", ")} FROM ${b}${I}`;return U(t,g,{view:a,temp:p,replace:d})}function Ze(r,t,e){return j("read_csv",r,t,e,{auto_detect:!0,sample_size:-1})}function tr(r,t,e){return j("read_json",r,t,e,{auto_detect:!0,json_format:"auto"})}function er(r,t,e){return j("read_parquet",r,t,e)}function rr(r,t,e={}){let{options:n,...o}=e;if(n){let s=Array.isArray(n)?n.join(", "):typeof n=="string"?n:Object.entries(n).map(([i,a])=>`${i}=${a}`).join(", ");o.open_options=s.toUpperCase()}return j("st_read",r,t,o)}function nr(r,t,e={}){let{select:n=["*"],...o}=e,s=st(t),i=n.length===1&&n[0]==="*"?s:`SELECT ${n} FROM ${s}`;return U(r,i,o)}function or(r){return Object.entries(r).map(([t,e])=>`${t}=${Q(e)}`).join(", ")}function Q(r){switch(typeof r){case"boolean":return String(r);case"string":return`'${r}'`;case"undefined":case"object":return r==null?"NULL":Array.isArray(r)?"["+r.map(t=>Q(t)).join(", ")+"]":"{"+Object.entries(r).map(([t,e])=>`'${t}': ${Q(e)}`).join(", ")+"}";default:return r}}export{F as Query,S as Ref,zt as agg,ut as all,mt as and,De as argmax,Oe as argmin,Me as arrayAgg,u as asColumn,O as asRelation,ee as avg,B as cast,_e as castDouble,Pe as castInteger,v as centroid,We as centroidX,Ye as centroidY,K as column,Ot as contains,$e as corr,te as count,Ee as covarPop,U as create,Xt as cume_dist,Ue as dateDay,Fe as dateMonth,Ge as dateMonthDay,Yt as dense_rank,ft as desc,ge as entropy,X as epoch_ms,yt as eq,Ie as first,kt as first_value,je as geojson,wt as gt,Tt as gte,bt as isBetween,Be as isDescribeQuery,Rt as isDistinct,Gt as isFinite,Ut as isInfinite,Ft as isNaN,It as isNotBetween,qt as isNotDistinct,Et as isNotNull,$t as isNull,T as isParamLike,M as isQuery,_ as isSQLExpression,me as kurtosis,Qt as lag,Le as last,Ht as last_value,Vt as lead,Pt as length,ht as literal,$ as literalToSQL,Ze as loadCSV,Je as loadExtension,tr as loadJSON,nr as loadObjects,er as loadParquet,rr as loadSpatial,Mt as lower,Nt as lt,At as lte,ne as mad,oe as max,re as mean,ae as median,se as min,le as mode,St as neq,xt as not,Kt as nth_value,vt as ntile,gt as or,Bt as percent_rank,Dt as prefix,ce as product,ue as quantile,Wt as rank,Lt as regexp_matches,qe as regrAvgX,be as regrAvgY,Ne as regrCount,ye as regrIntercept,we as regrR2,Te as regrSXX,Re as regrSXY,Ae as regrSYY,Se as regrSlope,H as relation,jt as row_number,ze as scaleTransform,he as skewness,c as sql,fe as stddev,xe as stddevPop,Ce as stringAgg,Ct as suffix,ie as sum,lt as toSQL,_t as upper,de as varPop,pe as variance,rt as x,nt as y};
var S=class{constructor(t,e){t&&(this.table=String(t)),e&&(this.column=e)}get columns(){return this.column?[this.column]:[]}toString(){let{table:t,column:e}=this;if(e){let n=e.startsWith("*")?e:`"${e}"`;return`${t?`${V(t)}.`:""}${n}`}else return t?V(t):"NULL"}};function V(r){return r.split(".").map(e=>`"${e}"`).join(".")}function k(r,t){return r instanceof S&&r.column===t}function u(r){return typeof r=="string"?K(r):r}function O(r){return typeof r=="string"?H(r):r}function H(r){return new S(r)}function K(r,t=null){return arguments.length===1&&(t=r,r=null),new S(r,t)}function ut(r){return new S(r,"*")}function lt(r){return typeof r=="string"?`"${r}"`:$(r)}function $(r){switch(typeof r){case"boolean":return r?"TRUE":"FALSE";case"string":return`'${r}'`;case"number":return Number.isFinite(r)?String(r):"NULL";default:if(r==null)return"NULL";if(r instanceof Date){let t=+r;if(Number.isNaN(t))return"NULL";let e=r.getUTCFullYear(),n=r.getUTCMonth(),o=r.getUTCDate();return t===Date.UTC(e,n,o)?`MAKE_DATE(${e}, ${n+1}, ${o})`:`EPOCH_MS(${t})`}else return r instanceof RegExp?`'${r.source}'`:String(r)}}var T=r=>typeof r?.addEventListener=="function";function _(r){return r instanceof N}var N=class{constructor(t,e,n){this._expr=Array.isArray(t)?t:[t],this._deps=e||[],this.annotate(n);let o=this._expr.filter(s=>T(s));o.length>0?(this._params=Array.from(new Set(o)),this._params.forEach(s=>{s.addEventListener("value",()=>pt(this,this.map?.get("value")))})):this.addEventListener=void 0}get value(){return this}get columns(){let{_params:t,_deps:e}=this;if(t){let n=new Set(t.flatMap(o=>{let s=o.value?.columns;return Array.isArray(s)?s:[]}));if(n.size){let o=new Set(e);return n.forEach(s=>o.add(s)),Array.from(o)}}return e}get column(){return this._deps.length?this._deps[0]:this.columns[0]}annotate(...t){return Object.assign(this,...t)}toString(){return this._expr.map(t=>T(t)&&!_(t)?$(t.value):t).join("")}addEventListener(t,e){let n=this.map||(this.map=new Map);(n.get(t)||(n.set(t,new Set),n.get(t))).add(e)}};function pt(r,t){if(t?.size)return Promise.allSettled(Array.from(t,e=>e(r)))}function W(r,t){let e=[r[0]],n=new Set,o=t.length;for(let s=0,i=0;s<o;){let a=t[s];T(a)?e[++i]=a:(Array.isArray(a?.columns)&&a.columns.forEach(d=>n.add(d)),e[i]+=typeof a=="string"?a:$(a));let p=r[++s];T(e[i])?e[++i]=p:e[i]+=p}return{spans:e,cols:Array.from(n)}}function c(r,...t){let{spans:e,cols:n}=W(r,t);return new N(e,n)}function ft(r){let t=u(r);return c`${t} DESC NULLS LAST`.annotate({label:t?.label,desc:!0})}var ht=r=>({value:r,toString:()=>$(r)});function D(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function z(r,t){let e=t.filter(o=>o!=null).map(u),n=e.map((o,s)=>s?` ${r} `:"");return e.length===1?n.push(""):e.length>1&&(n[0]="(",n.push(")")),c(n,...e).annotate({op:r,children:e,visit:D})}var mt=(...r)=>z("AND",r.flat()),gt=(...r)=>z("OR",r.flat()),dt=r=>t=>c`(${r} ${u(t)})`.annotate({op:r,a:t,visit:D}),xt=dt("NOT"),J=r=>t=>c`(${u(t)} ${r})`.annotate({op:r,a:t,visit:D}),$t=J("IS NULL"),Et=J("IS NOT NULL"),w=r=>(t,e)=>c`(${u(t)} ${r} ${u(e)})`.annotate({op:r,a:t,b:e,visit:D}),yt=w("="),St=w("<>"),Nt=w("<"),wt=w(">"),At=w("<="),Tt=w(">="),Rt=w("IS DISTINCT FROM"),qt=w("IS NOT DISTINCT FROM");function Z(r,t,e,n){t=u(t);let o=r.startsWith("NOT ")?"NOT ":"";return(e?n?c`${o}(${e[0]} <= ${t} AND ${t} < ${e[1]})`:c`(${t} ${r} ${e[0]} AND ${e[1]})`:c``).annotate({op:r,visit:D,field:t,range:e})}var bt=(r,t,e)=>Z("BETWEEN",r,t,e),It=(r,t,e)=>Z("NOT BETWEEN",r,t,e);function R(r,t){return Array.from({length:r},()=>t)}function m(r,t){return(...e)=>{let n=e.map(u),o=t?`::${t}`:"";return(n.length?c([`${r}(`,...R(n.length-1,", "),`)${o}`],...n):c`${r}()${o}`).annotate({func:r,args:n})}}var Lt=m("REGEXP_MATCHES"),Ot=m("CONTAINS"),Dt=m("PREFIX"),Ct=m("SUFFIX"),Mt=m("LOWER"),_t=m("UPPER"),Pt=m("LENGTH"),Ft=m("ISNAN"),Gt=m("ISFINITE"),jt=m("ISINF");var C=class r extends N{constructor(t,e,n,o,s="",i="",a=""){let p;if(o&&!(s||i||a))p=o?c`${e} OVER "${o}"`:c`${e} OVER ()`;else{let b=s&&i?" ":"",I=(s||i)&&a?" ":"";p=c`${e} OVER (${o?`"${o}" `:""}${s}${b}${i}${I}${a})`}n&&(p=c`(${p})::${n}`);let{_expr:y,_deps:A}=p;super(y,A),this.window=t,this.func=e,this.type=n,this.name=o,this.group=s,this.order=i,this.frame=a}get basis(){return this.column}get label(){let{func:t}=this;return t.label??t.toString()}over(t){let{window:e,func:n,type:o,group:s,order:i,frame:a}=this;return new r(e,n,o,t,s,i,a)}partitionby(...t){let e=t.flat().filter(y=>y).map(u),n=c(["PARTITION BY ",R(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:a,order:p,frame:d}=this;return new r(o,s,i,a,n,p,d)}orderby(...t){let e=t.flat().filter(y=>y).map(u),n=c(["ORDER BY ",R(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:a,group:p,frame:d}=this;return new r(o,s,i,a,p,n,d)}rows(t){let e=tt("ROWS",t),{window:n,func:o,type:s,name:i,group:a,order:p}=this;return new r(n,o,s,i,a,p,e)}range(t){let e=tt("RANGE",t),{window:n,func:o,type:s,name:i,group:a,order:p}=this;return new r(n,o,s,i,a,p,e)}};function tt(r,t){if(T(t)){let e=c`${t}`;return e.toString=()=>`${r} ${et(t.value)}`,e}return`${r} ${et(t)}`}function et(r){let[t,e]=r,n=t===0?"CURRENT ROW":Number.isFinite(t)?`${Math.abs(t)} PRECEDING`:"UNBOUNDED PRECEDING",o=e===0?"CURRENT ROW":Number.isFinite(e)?`${Math.abs(e)} FOLLOWING`:"UNBOUNDED FOLLOWING";return`BETWEEN ${n} AND ${o}`}function E(r,t){return(...e)=>{let n=m(r)(...e);return new C(r,n,t)}}var Ut=E("ROW_NUMBER","INTEGER"),Wt=E("RANK","INTEGER"),Yt=E("DENSE_RANK","INTEGER"),Bt=E("PERCENT_RANK"),Xt=E("CUME_DIST"),vt=E("NTILE"),Qt=E("LAG"),Vt=E("LEAD"),kt=E("FIRST_VALUE"),Ht=E("LAST_VALUE"),Kt=E("NTH_VALUE");function zt(r,...t){return c(r,...t).annotate({aggregate:!0})}var Y=class r extends N{constructor(t,e,n,o,s){e=(e||[]).map(u);let{strings:i,exprs:a}=Jt(t,e,n,o,s),{spans:p,cols:d}=W(i,a);super(p,d),this.aggregate=t,this.args=e,this.type=n,this.isDistinct=o,this.filter=s}get basis(){return this.column}get label(){let{aggregate:t,args:e,isDistinct:n}=this,o=n?"DISTINCT"+(e.length?" ":""):"",s=e.length?`(${o}${e.map(Zt).join(", ")})`:"";return`${t.toLowerCase()}${s}`}distinct(){let{aggregate:t,args:e,type:n,filter:o}=this;return new r(t,e,n,!0,o)}where(t){let{aggregate:e,args:n,type:o,isDistinct:s}=this;return new r(e,n,o,s,t)}window(){let{aggregate:t,args:e,type:n,isDistinct:o}=this,s=new r(t,e,null,o);return new C(t,s,n)}partitionby(...t){return this.window().partitionby(...t)}orderby(...t){return this.window().orderby(...t)}rows(t){return this.window().rows(t)}range(t){return this.window().range(t)}};function Jt(r,t,e,n,o){let s=`)${e?`::${e}`:""}`,i=[`${r}(${n?"DISTINCT ":""}`],a=[];return t.length?(i=i.concat([...R(t.length-1,", "),`${s}${o?" FILTER (WHERE ":""}`,...o?[")"]:[]]),a=[...t,...o?[o]:[]]):i[0]+="*"+s,{exprs:a,strings:i}}function Zt(r){let t=$(r);return t&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function l(r,t){return(...e)=>new Y(r,e,t)}var te=l("COUNT","INTEGER"),ee=l("AVG"),re=l("AVG"),ne=l("MAD"),oe=l("MAX"),se=l("MIN"),ie=l("SUM","DOUBLE"),ce=l("PRODUCT"),ae=l("MEDIAN"),ue=l("QUANTILE"),le=l("MODE"),pe=l("VARIANCE"),fe=l("STDDEV"),he=l("SKEWNESS"),me=l("KURTOSIS"),ge=l("ENTROPY"),de=l("VAR_POP"),xe=l("STDDEV_POP"),$e=l("CORR"),Ee=l("COVAR_POP"),ye=l("REGR_INTERCEPT"),Se=l("REGR_SLOPE"),Ne=l("REGR_COUNT"),we=l("REGR_R2"),Ae=l("REGR_SYY"),Te=l("REGR_SXX"),Re=l("REGR_SXY"),qe=l("REGR_AVGX"),be=l("REGR_AVGY"),Ie=l("FIRST"),Le=l("LAST"),Oe=l("ARG_MIN"),De=l("ARG_MAX"),Ce=l("STRING_AGG"),Me=l("ARRAY_AGG");function B(r,t){let e=u(r),n=c`CAST(${e} AS ${t})`;return Object.defineProperty(n,"label",{enumerable:!0,get(){return r.label}}),Object.defineProperty(n,"aggregate",{enumerable:!0,get(){return r.aggregate||!1}}),n}var _e=r=>B(r,"DOUBLE"),Pe=r=>B(r,"INTEGER");var X=r=>c`epoch_ms(${u(r)})`,Fe=r=>{let t=u(r);return c`MAKE_DATE(2012, MONTH(${t}), 1)`.annotate({label:"month"})},Ge=r=>{let t=u(r);return c`MAKE_DATE(2012, MONTH(${t}), DAY(${t}))`.annotate({label:"date"})},je=r=>{let t=u(r);return c`MAKE_DATE(2012, 1, DAY(${t}))`.annotate({label:"date"})};var Ue=m("ST_AsGeoJSON"),rt=m("ST_X"),nt=m("ST_Y"),v=m("ST_CENTROID"),We=r=>rt(v(r)),Ye=r=>nt(v(r));var F=class r{static select(...t){return new r().select(...t)}static from(...t){return new r().from(...t)}static with(...t){return new r().with(...t)}static union(...t){return new q("UNION",t.flat())}static unionAll(...t){return new q("UNION ALL",t.flat())}static intersect(...t){return new q("INTERSECT",t.flat())}static except(...t){return new q("EXCEPT",t.flat())}static describe(t){let e=t.clone(),{clone:n,toString:o}=e;return Object.assign(e,{describe:!0,clone:()=>r.describe(n.call(e)),toString:()=>`DESCRIBE ${o.call(e)}`})}constructor(){this.query={with:[],select:[],from:[],where:[],groupby:[],having:[],window:[],qualify:[],orderby:[]},this.cteFor=null}clone(){let t=new r;return t.query={...this.query},t}with(...t){let{query:e}=this;if(t.length===0)return e.with;{let n=[],o=(s,i)=>{let a=i.clone();a.cteFor=this,n.push({as:s,query:a})};return t.flat().forEach(s=>{if(s!=null)if(s.as&&s.query)o(s.as,s.query);else for(let i in s)o(i,s[i])}),e.with=e.with.concat(n),this}}select(...t){let{query:e}=this;if(t.length===0)return e.select;{let n=[];for(let o of t.flat())if(o!=null)if(typeof o=="string")n.push({as:o,expr:u(o)});else if(o instanceof S)n.push({as:o.column,expr:o});else if(Array.isArray(o))n.push({as:o[0],expr:o[1]});else for(let s in o)n.push({as:P(s),expr:u(o[s])});return e.select=e.select.concat(n),this}}$select(...t){return this.query.select=[],this.select(...t)}distinct(t=!0){return this.query.distinct=!!t,this}from(...t){let{query:e}=this;if(t.length===0)return e.from;{let n=[];return t.flat().forEach(o=>{if(o!=null)if(typeof o=="string")n.push({as:o,from:O(o)});else if(o instanceof S)n.push({as:o.table,from:o});else if(M(o)||_(o))n.push({from:o});else if(Array.isArray(o))n.push({as:P(o[0]),from:O(o[1])});else for(let s in o)n.push({as:P(s),from:O(o[s])})}),e.from=e.from.concat(n),this}}$from(...t){return this.query.from=[],this.from(...t)}sample(t,e){let{query:n}=this;if(arguments.length===0)return n.sample;{let o=t;return typeof t=="number"&&(o=t>0&&t<1?{perc:100*t,method:e}:{rows:Math.round(t),method:e}),n.sample=o,this}}where(...t){let{query:e}=this;return t.length===0?e.where:(e.where=e.where.concat(t.flat().filter(n=>n)),this)}$where(...t){return this.query.where=[],this.where(...t)}groupby(...t){let{query:e}=this;return t.length===0?e.groupby:(e.groupby=e.groupby.concat(t.flat().filter(n=>n).map(u)),this)}$groupby(...t){return this.query.groupby=[],this.groupby(...t)}having(...t){let{query:e}=this;return t.length===0?e.having:(e.having=e.having.concat(t.flat().filter(n=>n)),this)}window(...t){let{query:e}=this;if(t.length===0)return e.window;{let n=[];return t.flat().forEach(o=>{if(o!=null)for(let s in o)n.push({as:P(s),expr:o[s]})}),e.window=e.window.concat(n),this}}qualify(...t){let{query:e}=this;return t.length===0?e.qualify:(e.qualify=e.qualify.concat(t.flat().filter(n=>n)),this)}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(n=>n).map(u)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{query:t,cteFor:e}=this,o=(e?.query||t).with?.reduce((i,{as:a,query:p})=>(i[a]=p,i),{}),s=[];return t.from.forEach(({from:i})=>{if(M(i))s.push(i);else if(o[i.table]){let a=o[i.table];s.push(a)}}),s}toString(){let{with:t,select:e,distinct:n,from:o,sample:s,where:i,groupby:a,having:p,window:d,qualify:y,orderby:A,limit:b,offset:I}=this.query,g=[];if(t.length){let f=t.map(({as:h,query:x})=>`"${h}" AS (${x})`);g.push(`WITH ${f.join(", ")}`)}let it=e.map(({as:f,expr:h})=>k(h,f)&&!h.table?`${h}`:`${h} AS "${f}"`);if(g.push(`SELECT${n?" DISTINCT":""} ${it.join(", ")}`),o.length){let f=o.map(({as:h,from:x})=>{let L=M(x)?`(${x})`:`${x}`;return!h||h===x.table?L:`${L} AS "${h}"`});g.push(`FROM ${f.join(", ")}`)}if(i.length){let f=i.map(String).filter(h=>h).join(" AND ");f&&g.push(`WHERE ${f}`)}if(s){let{rows:f,perc:h,method:x,seed:L}=s,ct=f?`${f} ROWS`:`${h} PERCENT`,at=x?` (${x}${L!=null?`, ${L}`:""})`:"";g.push(`USING SAMPLE ${ct}${at}`)}if(a.length&&g.push(`GROUP BY ${a.join(", ")}`),p.length){let f=p.map(String).filter(h=>h).join(" AND ");f&&g.push(`HAVING ${f}`)}if(d.length){let f=d.map(({as:h,expr:x})=>`"${h}" AS (${x})`);g.push(`WINDOW ${f.join(", ")}`)}if(y.length){let f=y.map(String).filter(h=>h).join(" AND ");f&&g.push(`QUALIFY ${f}`)}return A.length&&g.push(`ORDER BY ${A.join(", ")}`),Number.isFinite(b)&&g.push(`LIMIT ${b}`),Number.isFinite(I)&&g.push(`OFFSET ${I}`),g.join(" ")}},q=class r{constructor(t,e){this.op=t,this.queries=e.map(n=>n.clone()),this.query={orderby:[]},this.cteFor=null}clone(){let t=new r(this.op,this.queries);return t.query={...this.query},t}orderby(...t){let{query:e}=this;return t.length===0?e.orderby:(e.orderby=e.orderby.concat(t.flat().filter(n=>n).map(u)),this)}limit(t){let{query:e}=this;return arguments.length===0?e.limit:(e.limit=Number.isFinite(t)?t:void 0,this)}offset(t){let{query:e}=this;return arguments.length===0?e.offset:(e.offset=Number.isFinite(t)?t:void 0,this)}get subqueries(){let{queries:t,cteFor:e}=this;return e&&t.forEach(n=>n.cteFor=e),t}toString(){let{op:t,queries:e,query:{orderby:n,limit:o,offset:s}}=this,i=[e.join(` ${t} `)];return n.length&&i.push(`ORDER BY ${n.join(", ")}`),Number.isFinite(o)&&i.push(`LIMIT ${o}`),Number.isFinite(s)&&i.push(`OFFSET ${s}`),i.join(" ")}};function M(r){return r instanceof F||r instanceof q}function Be(r){return M(r)&&r.describe}function P(r){return Xe(r)?r.slice(1,-1):r}function Xe(r){return r[0]==='"'&&r[r.length-1]==='"'}var G=r=>r;function ve(){return{apply:G,invert:G,sqlApply:u,sqlInvert:G}}function Qe({base:r=null}={}){if(r==null||r===Math.E)return{apply:Math.log,invert:Math.exp,sqlApply:t=>c`LN(${u(t)})`,sqlInvert:t=>c`EXP(${t})`};if(r===10)return{apply:Math.log10,invert:t=>Math.pow(10,t),sqlApply:t=>c`LOG(${u(t)})`,sqlInvert:t=>c`POW(10, ${t})`};{let t=+r;return{apply:e=>Math.log(e)/Math.log(t),invert:e=>Math.pow(t,e),sqlApply:e=>c`LN(${u(e)}) / LN(${t})`,sqlInvert:e=>c`POW(${t}, ${e})`}}}function Ve({constant:r=1}={}){let t=+r;return{apply:e=>Math.sign(e)*Math.log1p(Math.abs(e)),invert:e=>Math.sign(e)*Math.exp(Math.abs(e)-t),sqlApply:e=>(e=u(e),c`SIGN(${e}) * LN(${t} + ABS(${e}))`),sqlInvert:e=>c`SIGN(${e}) * (EXP(ABS(${e})) - ${t})`}}function ke(){return{apply:r=>Math.sign(r)*Math.sqrt(Math.abs(r)),invert:r=>Math.sign(r)*r*r,sqlApply:r=>(r=u(r),c`SIGN(${r}) * SQRT(ABS(${r}))`),sqlInvert:r=>c`SIGN(${r}) * (${r}) ** 2`}}function He({exponent:r=1}={}){let t=+r;return{apply:e=>Math.sign(e)*Math.pow(Math.abs(e),t),invert:e=>Math.sign(e)*Math.pow(Math.abs(e),1/t),sqlApply:e=>(e=u(e),c`SIGN(${e}) * POW(ABS(${e}), ${t})`),sqlInvert:e=>c`SIGN(${e}) * POW(ABS(${e}), 1/${t})`}}function ot(){return{apply:r=>+r,invert:r=>new Date(r),sqlApply:r=>r instanceof Date?+r:X(u(r)),sqlInvert:G}}var Ke={linear:ve,log:Qe,symlog:Ve,sqrt:ke,pow:He,time:ot,utc:ot};function ze(r){let t=Ke[r.type];return t?{...r,...t(r)}:null}function j(r,t,{replace:e=!1,temp:n=!0,view:o=!1}={}){return"CREATE"+(e?" OR REPLACE ":" ")+(n?"TEMP ":"")+(o?"VIEW":"TABLE")+(e?" ":" IF NOT EXISTS ")+r+" AS "+t}function Je(r){return`INSTALL ${r}; LOAD ${r}`}function st(r,{columns:t=Object.keys(r?.[0]||{})}={}){let e=[];if(Array.isArray(t)?(e=t,t=e.reduce((o,s)=>(o[s]=s,o),{})):t&&(e=Object.keys(t)),!e.length)throw new Error("Can not create table from empty column set.");let n=[];for(let o of r){let s=e.map(i=>`${$(o[i])} AS "${t[i]}"`);n.push(`(SELECT ${s.join(", ")})`)}return n.join(" UNION ALL ")}function U(r,t,e,n={},o={}){let{select:s=["*"],where:i,view:a,temp:p,replace:d,...y}=n,A=or({...o,...y}),b=`${r}('${e}'${A?", "+A:""})`,I=i?` WHERE ${i}`:"",g=`SELECT ${s.join(", ")} FROM ${b}${I}`;return j(t,g,{view:a,temp:p,replace:d})}function Ze(r,t,e){return U("read_csv",r,t,e,{auto_detect:!0,sample_size:-1})}function tr(r,t,e){return U("read_json",r,t,e,{auto_detect:!0,json_format:"auto"})}function er(r,t,e){return U("read_parquet",r,t,e)}function rr(r,t,e={}){let{options:n,...o}=e;if(n){let s=Array.isArray(n)?n.join(", "):typeof n=="string"?n:Object.entries(n).map(([i,a])=>`${i}=${a}`).join(", ");Object.assign(o,{open_options:s.toUpperCase()})}return U("st_read",r,t,o)}function nr(r,t,e={}){let{select:n=["*"],...o}=e,s=st(t),i=n.length===1&&n[0]==="*"?s:`SELECT ${n} FROM ${s}`;return j(r,i,o)}function or(r){return Object.entries(r).map(([t,e])=>`${t}=${Q(e)}`).join(", ")}function Q(r){switch(typeof r){case"boolean":return String(r);case"string":return`'${r}'`;case"undefined":case"object":return r==null?"NULL":Array.isArray(r)?"["+r.map(t=>Q(t)).join(", ")+"]":"{"+Object.entries(r).map(([t,e])=>`'${t}': ${Q(e)}`).join(", ")+"}";default:return r}}export{F as Query,S as Ref,zt as agg,ut as all,mt as and,De as argmax,Oe as argmin,Me as arrayAgg,u as asColumn,O as asRelation,ee as avg,B as cast,_e as castDouble,Pe as castInteger,v as centroid,We as centroidX,Ye as centroidY,K as column,Ot as contains,$e as corr,te as count,Ee as covarPop,j as create,Xt as cume_dist,je as dateDay,Fe as dateMonth,Ge as dateMonthDay,Yt as dense_rank,ft as desc,ge as entropy,X as epoch_ms,yt as eq,Ie as first,kt as first_value,Ue as geojson,wt as gt,Tt as gte,bt as isBetween,Be as isDescribeQuery,Rt as isDistinct,Gt as isFinite,jt as isInfinite,Ft as isNaN,It as isNotBetween,qt as isNotDistinct,Et as isNotNull,$t as isNull,T as isParamLike,M as isQuery,_ as isSQLExpression,me as kurtosis,Qt as lag,Le as last,Ht as last_value,Vt as lead,Pt as length,ht as literal,$ as literalToSQL,Ze as loadCSV,Je as loadExtension,tr as loadJSON,nr as loadObjects,er as loadParquet,rr as loadSpatial,Mt as lower,Nt as lt,At as lte,ne as mad,oe as max,re as mean,ae as median,se as min,le as mode,St as neq,xt as not,Kt as nth_value,vt as ntile,gt as or,Bt as percent_rank,Dt as prefix,ce as product,ue as quantile,Wt as rank,Lt as regexp_matches,qe as regrAvgX,be as regrAvgY,Ne as regrCount,ye as regrIntercept,we as regrR2,Te as regrSXX,Re as regrSXY,Ae as regrSYY,Se as regrSlope,H as relation,Ut as row_number,ze as scaleTransform,he as skewness,c as sql,fe as stddev,xe as stddevPop,Ce as stringAgg,Ct as suffix,ie as sum,lt as toSQL,_t as upper,de as varPop,pe as variance,rt as x,nt as y};
{
"name": "@uwdata/mosaic-sql",
"version": "0.7.0",
"version": "0.8.0",
"description": "SQL query construction and analysis.",

@@ -24,7 +24,7 @@ "keywords": [

"build": "node ../../esbuild.js mosaic-sql",
"lint": "eslint src test --ext .js",
"lint": "eslint src test",
"test": "mocha 'test/**/*-test.js'",
"prepublishOnly": "npm run test && npm run lint && npm run build"
},
"gitHead": "4680b922f15579b7b527f31507ed71a12230ec35"
"gitHead": "a24b4c9f7dfa1c38c6af96ec17e075326c1af9b0"
}

@@ -22,2 +22,10 @@ import { SQLExpression, parseSQL, sql } from './expression.js';

export class AggregateFunction extends SQLExpression {
/**
* Create a new AggregateFunction instance.
* @param {*} op The aggregate operation.
* @param {*} [args] The aggregate function arguments.
* @param {*} [type] The SQL data type to cast to.
* @param {boolean} [isDistinct] Flag indicating if this is a distinct value aggregate.
* @param {*} [filter] Filtering expression to apply prior to aggregation.
*/
constructor(op, args, type, isDistinct, filter) {

@@ -27,3 +35,8 @@ args = (args || []).map(asColumn);

const { spans, cols } = parseSQL(strings, exprs);
super(spans, cols, { aggregate: op, args, type, isDistinct, filter });
super(spans, cols);
this.aggregate = op;
this.args = args;
this.type = type;
this.isDistinct = isDistinct;
this.filter = filter;
}

@@ -42,2 +55,6 @@

/**
* Return a new derived aggregate function over distinct values.
* @returns {AggregateFunction} A new aggregate function.
*/
distinct() {

@@ -48,2 +65,7 @@ const { aggregate: op, args, type, filter } = this;

/**
* Return a new derived aggregate function that filters values.
* @param {*} filter The filter expresion.
* @returns {AggregateFunction} A new aggregate function.
*/
where(filter) {

@@ -54,2 +76,6 @@ const { aggregate: op, args, type, isDistinct } = this;

/**
* Return a new window function over this aggregate.
* @returns {WindowFunction} A new aggregate function.
*/
window() {

@@ -61,2 +87,7 @@ const { aggregate: op, args, type, isDistinct } = this;

/**
* Return a window function over this aggregate with the given partitioning.
* @param {*} expr The grouping (partition by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
partitionby(...expr) {

@@ -66,2 +97,7 @@ return this.window().partitionby(...expr);

/**
* Return a window function over this aggregate with the given ordering.
* @param {*} expr The sorting (order by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
orderby(...expr) {

@@ -71,8 +107,18 @@ return this.window().orderby(...expr);

rows(prev, next) {
return this.window().rows(prev, next);
/**
* Return a window function over this aggregate with the given row frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} frame The row-based window frame.
* @returns {WindowFunction} A new window function.
*/
rows(frame) {
return this.window().rows(frame);
}
range(prev, next) {
return this.window().range(prev, next);
/**
* Return a window function over this aggregate with the given range frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} frame The range-based window frame.
* @returns {WindowFunction} A new window function.
*/
range(frame) {
return this.window().range(frame);
}

@@ -79,0 +125,0 @@ }

@@ -7,4 +7,4 @@ import { sql } from './expression.js';

* Null values are ordered last.
* @param {SQLExpression|string} expr A SQL expression or column name string.
* @returns {SQLExpression} An expression with descending order.
* @param {import('./expression.js').SQLExpression|string} expr A SQL expression or column name string.
* @returns {import('./expression.js').SQLExpression} An expression with descending order.
*/

@@ -11,0 +11,0 @@ export function desc(expr) {

import { literalToSQL } from './to-sql.js';
/**
* @typedef {{
* value: any;
* addEventListener(type: string, callback: Function): any;
* column?: string,
* columns?: string[]
* }} ParamLike
*/
/**
* Test if a value is parameter-like. Parameters have addEventListener methods.
* @param {*} value The value to test.
* @returns True if the value is param-like, false otherwise.
* @returns {value is ParamLike} True if the value is param-like, false otherwise.
*/

@@ -13,3 +22,3 @@ export const isParamLike = value => typeof value?.addEventListener === 'function';

* @param {*} value The value to test.
* @returns {boolean} True if value is a SQL expression, false otherwise.
* @returns {value is SQLExpression} True if value is a SQL expression, false otherwise.
*/

@@ -28,3 +37,3 @@ export function isSQLExpression(value) {

* Create a new SQL expression instance.
* @param {(string|SQLExpression|Ref)[]} parts The parts of the expression.
* @param {(string | ParamLike | SQLExpression | import('./ref.js').Ref)[]} parts The parts of the expression.
* @param {string[]} [columns=[]] The column dependencies

@@ -40,2 +49,4 @@ * @param {object} [props] Additional properties for this expression.

if (params.length > 0) {
/** @type {ParamLike[]} */
// @ts-ignore
this._params = Array.from(new Set(params));

@@ -42,0 +53,0 @@ this._params.forEach(param => {

@@ -41,3 +41,3 @@ import { create } from './create.js';

.join(', ');
rest.open_options = open.toUpperCase();
Object.assign(rest, { open_options: open.toUpperCase() });
}

@@ -44,0 +44,0 @@ // TODO: handle box_2d for spatial_filter_box option

import { literalToSQL } from '../to-sql.js';
/**
* Create a SQL query that embeds the given data for loading.
* @param {*} data The dataset
* @param {object} [options] Loading options
* @param {string[]|object} [options.columns] The columns to include
* @returns {string} SQL query string to load data
*/
export function sqlFrom(data, {

@@ -4,0 +11,0 @@ columns = Object.keys(data?.[0] || {})

@@ -56,2 +56,3 @@ import { isSQLExpression } from './expression.js';

};
this.cteFor = null;
}

@@ -65,5 +66,14 @@

/**
* Retrieve current WITH common table expressions (CTEs).
* @returns {any[]}
*//**
* Add WITH common table expressions (CTEs).
* @param {...any} expr Expressions to add.
* @returns {this}
*/
with(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.with;

@@ -93,5 +103,14 @@ } else {

/**
* Retrieve current SELECT expressions.
* @returns {any[]}
*//**
* Add SELECT expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
select(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.select;

@@ -130,5 +149,14 @@ } else {

/**
* Retrieve current from expressions.
* @returns {any[]}
*//**
* Provide table from expressions.
* @param {...any} expr
* @returns {this}
*/
from(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.from;

@@ -164,5 +192,15 @@ } else {

/**
* Retrieve current SAMPLE settings.
* @returns {any[]}
*//**
* Set SAMPLE settings.
* @param {number|object} value The percentage or number of rows to sample.
* @param {string} [method] The sampling method to use.
* @returns {this}
*/
sample(value, method) {
const { query } = this;
if (arguments.length === 0) {
// @ts-ignore
return query.sample;

@@ -181,5 +219,14 @@ } else {

/**
* Retrieve current WHERE expressions.
* @returns {any[]}
*//**
* Add WHERE expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
where(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.where;

@@ -199,5 +246,14 @@ } else {

/**
* Retrieve current GROUP BY expressions.
* @returns {any[]}
*//**
* Add GROUP BY expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
groupby(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.groupby;

@@ -217,5 +273,14 @@ } else {

/**
* Retrieve current HAVING expressions.
* @returns {any[]}
*//**
* Add HAVING expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
having(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.having;

@@ -230,5 +295,14 @@ } else {

/**
* Retrieve current WINDOW definitions.
* @returns {any[]}
*//**
* Add WINDOW definitions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
window(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.window;

@@ -251,5 +325,14 @@ } else {

/**
* Retrieve current QUALIFY expressions.
* @returns {any[]}
*//**
* Add QUALIFY expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
qualify(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.qualify;

@@ -264,5 +347,14 @@ } else {

/**
* Retrieve current ORDER BY expressions.
* @returns {any[]}
*//**
* Add ORDER BY expressions.
* @param {...any} expr Expressions to add.
* @returns {this}
*/
orderby(...expr) {
const { query } = this;
if (expr.length === 0) {
// @ts-ignore
return query.orderby;

@@ -277,2 +369,10 @@ } else {

/**
* Retrieve current LIMIT value.
* @returns {number|null}
*//**
* Set the query result LIMIT.
* @param {number} value The limit value.
* @returns {this}
*/
limit(value) {

@@ -288,2 +388,10 @@ const { query } = this;

/**
* Retrieve current OFFSET value.
* @returns {number|null}
*//**
* Set the query result OFFSET.
* @param {number} value The offset value.
* @returns {this}
*/
offset(value) {

@@ -407,2 +515,3 @@ const { query } = this;

this.query = { orderby: [] };
this.cteFor = null;
}

@@ -409,0 +518,0 @@

@@ -8,3 +8,3 @@ /**

* @param {string|Ref|null} table The table name.
* @param {string|null} column The column name.
* @param {string|null} [column] The column name.
*/

@@ -91,7 +91,7 @@ constructor(table, column) {

* Create a column reference.
* @param {string} [table] The table name (optional).
* @param {string} column The column name.
* @param {string} table The table name (optional).
* @param {string} [column] The column name.
* @returns {Ref} The generated column reference.
*/
export function column(table, column) {
export function column(table, column = null) {
if (arguments.length === 1) {

@@ -98,0 +98,0 @@ column = table;

@@ -16,3 +16,3 @@ import { epoch_ms } from './datetime.js';

function scaleLog({ base } = {}) {
function scaleLog({ base = null } = {}) {
if (base == null || base === Math.E) {

@@ -19,0 +19,0 @@ return {

@@ -12,2 +12,12 @@ import { SQLExpression, isParamLike, sql } from './expression.js';

export class WindowFunction extends SQLExpression {
/**
* Create a new WindowFunction instance.
* @param {string} op The window operation indicator.
* @param {*} func The window function expression.
* @param {*} [type] The SQL data type to cast to.
* @param {string} [name] The window definition name.
* @param {*} [group] Grouping (partition by) expressions.
* @param {*} [order] Sorting (order by) expressions.
* @param {*} [frame] The window frame definition.
*/
constructor(op, func, type, name, group = '', order = '', frame = '') {

@@ -28,3 +38,10 @@ // build and parse expression

const { _expr, _deps } = expr;
super(_expr, _deps, { window: op, func, type, name, group, order, frame });
super(_expr, _deps);
this.window = op;
this.func = func;
this.type = type;
this.name = name;
this.group = group;
this.order = order;
this.frame = frame;
}

@@ -41,2 +58,7 @@

/**
* Return an updated window function over a named window definition.
* @param {string} name The window definition name.
* @returns {WindowFunction} A new window function.
*/
over(name) {

@@ -47,2 +69,7 @@ const { window: op, func, type, group, order, frame } = this;

/**
* Return an updated window function with the given partitioning.
* @param {*} expr The grouping (partition by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
partitionby(...expr) {

@@ -58,2 +85,7 @@ const exprs = expr.flat().filter(x => x).map(asColumn);

/**
* Return an updated window function with the given ordering.
* @param {*} expr The sorting (order by) criteria for the window function.
* @returns {WindowFunction} A new window function.
*/
orderby(...expr) {

@@ -69,2 +101,7 @@ const exprs = expr.flat().filter(x => x).map(asColumn);

/**
* Return an updated window function with the given rows frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} expr The row-based window frame.
* @returns {WindowFunction} A new window function.
*/
rows(expr) {

@@ -76,2 +113,7 @@ const frame = windowFrame('ROWS', expr);

/**
* Return an updated window function with the given range frame.
* @param {(number|null)[] | import('./expression.js').ParamLike} expr The range-based window frame.
* @returns {WindowFunction} A new window function.
*/
range(expr) {

@@ -78,0 +120,0 @@ const frame = windowFrame('RANGE', expr);

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc