@uwdata/mosaic-sql 0.3.0 → 0.3.2
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/mosaic-sql.js +23 -19
- package/dist/mosaic-sql.min.js +1 -1
- package/package.json +2 -2
- package/src/ref.js +12 -2
package/dist/mosaic-sql.js
CHANGED
|
@@ -26,12 +26,16 @@ var Ref = class {
|
|
|
26
26
|
const { table, column: column2 } = this;
|
|
27
27
|
if (column2) {
|
|
28
28
|
const col = column2.startsWith("*") ? column2 : `"${column2}"`;
|
|
29
|
-
return `${table ?
|
|
29
|
+
return `${table ? `${quoteTableName(table)}.` : ""}${col}`;
|
|
30
30
|
} else {
|
|
31
|
-
return table ?
|
|
31
|
+
return table ? quoteTableName(table) : "NULL";
|
|
32
32
|
}
|
|
33
33
|
}
|
|
34
34
|
};
|
|
35
|
+
function quoteTableName(table) {
|
|
36
|
+
const pieces = table.split(".");
|
|
37
|
+
return pieces.map((p) => `"${p}"`).join(".");
|
|
38
|
+
}
|
|
35
39
|
function isColumnRefFor(ref, name) {
|
|
36
40
|
return ref instanceof Ref && ref.column === name;
|
|
37
41
|
}
|
|
@@ -281,7 +285,7 @@ var isFinite = functionCall("ISFINITE");
|
|
|
281
285
|
var isInfinite = functionCall("ISINF");
|
|
282
286
|
|
|
283
287
|
// src/windows.js
|
|
284
|
-
var WindowFunction = class extends SQLExpression {
|
|
288
|
+
var WindowFunction = class _WindowFunction extends SQLExpression {
|
|
285
289
|
constructor(op, func, type, name, group = "", order = "", frame = "") {
|
|
286
290
|
let expr;
|
|
287
291
|
const noWindowParams = !(group || order || frame);
|
|
@@ -307,7 +311,7 @@ var WindowFunction = class extends SQLExpression {
|
|
|
307
311
|
}
|
|
308
312
|
over(name) {
|
|
309
313
|
const { window: op, func, type, group, order, frame } = this;
|
|
310
|
-
return new
|
|
314
|
+
return new _WindowFunction(op, func, type, name, group, order, frame);
|
|
311
315
|
}
|
|
312
316
|
partitionby(...expr) {
|
|
313
317
|
const exprs = expr.flat().filter((x) => x).map(asColumn);
|
|
@@ -316,7 +320,7 @@ var WindowFunction = class extends SQLExpression {
|
|
|
316
320
|
...exprs
|
|
317
321
|
);
|
|
318
322
|
const { window: op, func, type, name, order, frame } = this;
|
|
319
|
-
return new
|
|
323
|
+
return new _WindowFunction(op, func, type, name, group, order, frame);
|
|
320
324
|
}
|
|
321
325
|
orderby(...expr) {
|
|
322
326
|
const exprs = expr.flat().filter((x) => x).map(asColumn);
|
|
@@ -325,17 +329,17 @@ var WindowFunction = class extends SQLExpression {
|
|
|
325
329
|
...exprs
|
|
326
330
|
);
|
|
327
331
|
const { window: op, func, type, name, group, frame } = this;
|
|
328
|
-
return new
|
|
332
|
+
return new _WindowFunction(op, func, type, name, group, order, frame);
|
|
329
333
|
}
|
|
330
334
|
rows(expr) {
|
|
331
335
|
const frame = windowFrame("ROWS", expr);
|
|
332
336
|
const { window: op, func, type, name, group, order } = this;
|
|
333
|
-
return new
|
|
337
|
+
return new _WindowFunction(op, func, type, name, group, order, frame);
|
|
334
338
|
}
|
|
335
339
|
range(expr) {
|
|
336
340
|
const frame = windowFrame("RANGE", expr);
|
|
337
341
|
const { window: op, func, type, name, group, order } = this;
|
|
338
|
-
return new
|
|
342
|
+
return new _WindowFunction(op, func, type, name, group, order, frame);
|
|
339
343
|
}
|
|
340
344
|
};
|
|
341
345
|
function windowFrame(type, frame) {
|
|
@@ -374,7 +378,7 @@ var nth_value = winf("NTH_VALUE");
|
|
|
374
378
|
function agg(strings, ...exprs) {
|
|
375
379
|
return sql(strings, ...exprs).annotate({ aggregate: true });
|
|
376
380
|
}
|
|
377
|
-
var AggregateFunction = class extends SQLExpression {
|
|
381
|
+
var AggregateFunction = class _AggregateFunction extends SQLExpression {
|
|
378
382
|
constructor(op, args, type, isDistinct2, filter) {
|
|
379
383
|
args = (args || []).map(asColumn);
|
|
380
384
|
const { strings, exprs } = aggExpr(op, args, type, isDistinct2, filter);
|
|
@@ -392,15 +396,15 @@ var AggregateFunction = class extends SQLExpression {
|
|
|
392
396
|
}
|
|
393
397
|
distinct() {
|
|
394
398
|
const { aggregate: op, args, type, filter } = this;
|
|
395
|
-
return new
|
|
399
|
+
return new _AggregateFunction(op, args, type, true, filter);
|
|
396
400
|
}
|
|
397
401
|
where(filter) {
|
|
398
402
|
const { aggregate: op, args, type, isDistinct: isDistinct2 } = this;
|
|
399
|
-
return new
|
|
403
|
+
return new _AggregateFunction(op, args, type, isDistinct2, filter);
|
|
400
404
|
}
|
|
401
405
|
window() {
|
|
402
406
|
const { aggregate: op, args, type, isDistinct: isDistinct2 } = this;
|
|
403
|
-
const func = new
|
|
407
|
+
const func = new _AggregateFunction(op, args, null, isDistinct2);
|
|
404
408
|
return new WindowFunction(op, func, type);
|
|
405
409
|
}
|
|
406
410
|
partitionby(...expr) {
|
|
@@ -515,15 +519,15 @@ var dateDay = (expr) => {
|
|
|
515
519
|
};
|
|
516
520
|
|
|
517
521
|
// src/Query.js
|
|
518
|
-
var Query = class {
|
|
522
|
+
var Query = class _Query {
|
|
519
523
|
static select(...expr) {
|
|
520
|
-
return new
|
|
524
|
+
return new _Query().select(...expr);
|
|
521
525
|
}
|
|
522
526
|
static from(...expr) {
|
|
523
|
-
return new
|
|
527
|
+
return new _Query().from(...expr);
|
|
524
528
|
}
|
|
525
529
|
static with(...expr) {
|
|
526
|
-
return new
|
|
530
|
+
return new _Query().with(...expr);
|
|
527
531
|
}
|
|
528
532
|
static union(...queries) {
|
|
529
533
|
return new SetOperation("UNION", queries.flat());
|
|
@@ -551,7 +555,7 @@ var Query = class {
|
|
|
551
555
|
};
|
|
552
556
|
}
|
|
553
557
|
clone() {
|
|
554
|
-
const q = new
|
|
558
|
+
const q = new _Query();
|
|
555
559
|
q.query = { ...this.query };
|
|
556
560
|
return q;
|
|
557
561
|
}
|
|
@@ -841,14 +845,14 @@ var Query = class {
|
|
|
841
845
|
return sql2.join(" ");
|
|
842
846
|
}
|
|
843
847
|
};
|
|
844
|
-
var SetOperation = class {
|
|
848
|
+
var SetOperation = class _SetOperation {
|
|
845
849
|
constructor(op, queries) {
|
|
846
850
|
this.op = op;
|
|
847
851
|
this.queries = queries.map((q) => q.clone());
|
|
848
852
|
this.query = { orderby: [] };
|
|
849
853
|
}
|
|
850
854
|
clone() {
|
|
851
|
-
const q = new
|
|
855
|
+
const q = new _SetOperation(this.op, this.queries);
|
|
852
856
|
q.query = { ...this.query };
|
|
853
857
|
return q;
|
|
854
858
|
}
|
package/dist/mosaic-sql.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var w=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?`"${t}".`:""}${n}`}else return t?`"${t}"`:"NULL"}};function B(r,t){return r instanceof w&&r.column===t}function l(r){return typeof r=="string"?X(r):r}function _(r){return typeof r=="string"?V(r):r}function V(r){return new w(r)}function X(r,t){return arguments.length===1&&(t=r,r=null),new w(r,t)}function et(r){return new w(r,"*")}function rt(r){return typeof r=="string"?`"${r}"`:E(r)}function E(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 q=r=>typeof r?.addEventListener=="function";function U(r){return r instanceof A}var A=class{constructor(t,e,n){this._expr=Array.isArray(t)?t:[t],this._deps=e||[],this.annotate(n);let o=this._expr.filter(s=>q(s));o.length>0?(this._params=Array.from(new Set(o)),this._params.forEach(s=>{s.addEventListener("value",()=>nt(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=>q(t)&&!U(t)?E(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 nt(r,t){if(t?.size)return Promise.allSettled(Array.from(t,e=>e(r)))}function j(r,t){let e=[r[0]],n=new Set,o=t.length;for(let s=0,i=0;s<o;){let c=t[s];q(c)?e[++i]=c:(Array.isArray(c?.columns)&&c.columns.forEach(g=>n.add(g)),e[i]+=typeof c=="string"?c:E(c));let p=r[++s];q(e[i])?e[++i]=p:e[i]+=p}return{spans:e,cols:Array.from(n)}}function u(r,...t){let{spans:e,cols:n}=j(r,t);return new A(e,n)}function ot(r){let t=l(r);return u`${t} DESC NULLS LAST`.annotate({label:t?.label,desc:!0})}var st=r=>({value:r,toString:()=>E(r)});function P(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function Q(r,t){let e=t.filter(o=>o!=null).map(l),n=e.map((o,s)=>s?` ${r} `:"");return t.length&&n.push(""),u(n,...e).annotate({op:r,children:e,visit:P})}var it=(...r)=>Q("AND",r.flat()),ct=(...r)=>Q("OR",r.flat()),at=r=>t=>u`(${r} ${l(t)})`.annotate({op:r,a:t,visit:P}),ut=at("NOT"),k=r=>t=>u`(${l(t)} ${r})`.annotate({op:r,a:t,visit:P}),lt=k("IS NULL"),pt=k("IS NOT NULL"),T=r=>(t,e)=>u`(${l(t)} ${r} ${l(e)})`.annotate({op:r,a:t,b:e,visit:P}),ft=T("="),ht=T("<>"),mt=T("<"),gt=T(">"),xt=T("<="),dt=T(">="),Et=T("IS DISTINCT FROM"),$t=T("IS NOT DISTINCT FROM");function v(r,t,e,n){t=l(t);let o=r.startsWith("NOT ")?"NOT ":"";return(e?n?u`${o}(${e[0]} <= ${t} AND ${t} < ${e[1]})`:u`(${t} ${r} ${e[0]} AND ${e[1]})`:u``).annotate({op:r,visit:P,field:t,range:e})}var Nt=(r,t,e)=>v("BETWEEN",r,t,e),yt=(r,t,e)=>v("NOT BETWEEN",r,t,e);function L(r,t){return Array.from({length:r},()=>t)}function x(r,t){return(...e)=>{let n=e.map(l),o=t?`::${t}`:"";return(n.length?u([`${r}(`,...L(n.length-1,", "),`)${o}`],...n):u`${r}()${o}`).annotate({func:r,args:n})}}var wt=x("REGEXP_MATCHES"),St=x("CONTAINS"),Rt=x("PREFIX"),At=x("SUFFIX"),Tt=x("LOWER"),bt=x("UPPER"),qt=x("LENGTH"),Lt=x("ISNAN"),Ot=x("ISFINITE"),It=x("ISINF");var $=class extends A{constructor(t,e,n,o,s="",i="",c=""){let p;if(o&&!(s||i||c))p=o?u`${e} OVER "${o}"`:u`${e} OVER ()`;else{let I=s&&i?" ":"",D=(s||i)&&c?" ":"";p=u`${e} OVER (${o?`"${o}" `:""}${s}${I}${i}${D}${c})`}n&&(p=u`(${p})::${n}`);let{_expr:y,_deps:b}=p;super(y,b,{window:t,func:e,type:n,name:o,group:s,order:i,frame:c})}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:c}=this;return new $(e,n,o,t,s,i,c)}partitionby(...t){let e=t.flat().filter(y=>y).map(l),n=u(["PARTITION BY ",L(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:c,order:p,frame:g}=this;return new $(o,s,i,c,n,p,g)}orderby(...t){let e=t.flat().filter(y=>y).map(l),n=u(["ORDER BY ",L(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:c,group:p,frame:g}=this;return new $(o,s,i,c,p,n,g)}rows(t){let e=H("ROWS",t),{window:n,func:o,type:s,name:i,group:c,order:p}=this;return new $(n,o,s,i,c,p,e)}range(t){let e=H("RANGE",t),{window:n,func:o,type:s,name:i,group:c,order:p}=this;return new $(n,o,s,i,c,p,e)}};function H(r,t){if(q(t)){let e=u`${t}`;return e.toString=()=>`${r} ${K(t.value)}`,e}return`${r} ${K(t)}`}function K(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 N(r,t){return(...e)=>{let n=x(r)(...e);return new $(r,n,t)}}var Dt=N("ROW_NUMBER","INTEGER"),Ct=N("RANK","INTEGER"),_t=N("DENSE_RANK","INTEGER"),Pt=N("PERCENT_RANK"),Ut=N("CUME_DIST"),Mt=N("NTILE"),Ft=N("LAG"),Gt=N("LEAD"),jt=N("FIRST_VALUE"),Yt=N("LAST_VALUE"),Wt=N("NTH_VALUE");function Bt(r,...t){return u(r,...t).annotate({aggregate:!0})}var O=class extends A{constructor(t,e,n,o,s){e=(e||[]).map(l);let{strings:i,exprs:c}=Vt(t,e,n,o,s),{spans:p,cols:g}=j(i,c);super(p,g,{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(Xt).join(", ")})`:"";return`${t.toLowerCase()}${s}`}distinct(){let{aggregate:t,args:e,type:n,filter:o}=this;return new O(t,e,n,!0,o)}where(t){let{aggregate:e,args:n,type:o,isDistinct:s}=this;return new O(e,n,o,s,t)}window(){let{aggregate:t,args:e,type:n,isDistinct:o}=this,s=new O(t,e,null,o);return new $(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 Vt(r,t,e,n,o){let s=`)${e?`::${e}`:""}`,i=[`${r}(${n?"DISTINCT ":""}`],c=[];return t.length?(i=i.concat([...L(t.length-1,", "),`${s}${o?" FILTER (WHERE ":""}`,...o?[")"]:[]]),c=[...t,...o?[o]:[]]):i[0]+="*"+s,{exprs:c,strings:i}}function Xt(r){let t=E(r);return t&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function a(r,t){return(...e)=>new O(r,e,t)}var Qt=a("COUNT","INTEGER"),kt=a("AVG"),vt=a("AVG"),Ht=a("MAD"),Kt=a("MAX"),zt=a("MIN"),Jt=a("SUM","DOUBLE"),Zt=a("PRODUCT"),te=a("MEDIAN"),ee=a("QUANTILE"),re=a("MODE"),ne=a("VARIANCE"),oe=a("STDDEV"),se=a("SKEWNESS"),ie=a("KURTOSIS"),ce=a("ENTROPY"),ae=a("VAR_POP"),ue=a("STDDEV_POP"),le=a("CORR"),pe=a("COVAR_POP"),fe=a("REGR_INTERCEPT"),he=a("REGR_SLOPE"),me=a("REGR_COUNT"),ge=a("REGR_R2"),xe=a("REGR_SYY"),de=a("REGR_SXX"),Ee=a("REGR_SXY"),$e=a("REGR_AVGX"),Ne=a("REGR_AVGY"),ye=a("FIRST"),we=a("LAST"),Se=a("ARG_MIN"),Re=a("ARG_MAX"),Ae=a("STRING_AGG"),Te=a("ARRAY_AGG");function Y(r,t){let e=l(r),n=u`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 be=r=>Y(r,"DOUBLE"),qe=r=>Y(r,"INTEGER");var Le=r=>{let t=l(r);return u`(1000 * (epoch(${t}) - second(${t})) + millisecond(${t}))::DOUBLE`},Oe=r=>{let t=l(r);return u`MAKE_DATE(2012, MONTH(${t}), 1)`.annotate({label:"month"})},Ie=r=>{let t=l(r);return u`MAKE_DATE(2012, MONTH(${t}), DAY(${t}))`.annotate({label:"date"})},De=r=>{let t=l(r);return u`MAKE_DATE(2012, 1, DAY(${t}))`.annotate({label:"date"})};var S=class{static select(...t){return new S().select(...t)}static from(...t){return new S().from(...t)}static with(...t){return new S().with(...t)}static union(...t){return new R("UNION",t.flat())}static unionAll(...t){return new R("UNION ALL",t.flat())}static intersect(...t){return new R("INTERSECT",t.flat())}static except(...t){return new R("EXCEPT",t.flat())}constructor(){this.query={with:[],select:[],from:[],where:[],groupby:[],having:[],window:[],qualify:[],orderby:[]}}clone(){let t=new S;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 c=i.clone();c.cteFor=this,n.push({as:s,query:c})};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:l(o)});else if(o instanceof w)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:M(s),expr:l(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)});else if(o instanceof w)n.push({as:o.table,from:o});else if(F(o)||U(o))n.push({from:o});else if(Array.isArray(o))n.push({as:M(o[0]),from:_(o[1])});else for(let s in o)n.push({as:M(s),from:_(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(l)),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:M(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(l)),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:c,query:p})=>(i[c]=p,i),{}),s=[];return t.from.forEach(({from:i})=>{if(F(i))s.push(i);else if(o[i.table]){let c=o[i.table];s.push(c)}}),s}toString(){let{select:t,distinct:e,from:n,sample:o,where:s,groupby:i,having:c,window:p,qualify:g,orderby:y,limit:b,offset:I,with:D}=this.query,m=[];if(D.length){let f=D.map(({as:h,query:d})=>`"${h}" AS (${d})`);m.push(`WITH ${f.join(", ")}`)}let J=t.map(({as:f,expr:h})=>B(h,f)&&!h.table?`${h}`:`${h} AS "${f}"`);if(m.push(`SELECT${e?" DISTINCT":""} ${J.join(", ")}`),n.length){let f=n.map(({as:h,from:d})=>{let C=F(d)?`(${d})`:`${d}`;return!h||h===d.table?C:`${C} AS "${h}"`});m.push(`FROM ${f.join(", ")}`)}if(s.length){let f=s.map(String).filter(h=>h).join(" AND ");f&&m.push(`WHERE ${f}`)}if(o){let{rows:f,perc:h,method:d,seed:C}=o,Z=f?`${f} ROWS`:`${h} PERCENT`,tt=d?` (${d}${C!=null?`, ${C}`:""})`:"";m.push(`USING SAMPLE ${Z}${tt}`)}if(i.length&&m.push(`GROUP BY ${i.join(", ")}`),c.length){let f=c.map(String).filter(h=>h).join(" AND ");f&&m.push(`HAVING ${f}`)}if(p.length){let f=p.map(({as:h,expr:d})=>`"${h}" AS (${d})`);m.push(`WINDOW ${f.join(", ")}`)}if(g.length){let f=g.map(String).filter(h=>h).join(" AND ");f&&m.push(`QUALIFY ${f}`)}return y.length&&m.push(`ORDER BY ${y.join(", ")}`),Number.isFinite(b)&&m.push(`LIMIT ${b}`),Number.isFinite(I)&&m.push(`OFFSET ${I}`),m.join(" ")}},R=class{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(l)),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 F(r){return r instanceof S||r instanceof R}function M(r){return Ce(r)?r.slice(1,-1):r}function Ce(r){return r[0]==='"'&&r[r.length-1]==='"'}function G(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 z(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=>`${E(o[i])} AS "${t[i]}"`);n.push(`(SELECT ${s.join(", ")})`)}return n.join(" UNION ALL ")}function W(r,t,e,n={},o={}){let{select:s=["*"],where:i,view:c,temp:p,replace:g,...y}=n,b=Fe({...o,...y}),I=`${r}('${e}'${b?", "+b:""})`,D=i?` WHERE ${i}`:"",m=`SELECT ${s.join(", ")} FROM ${I}${D}`;return G(t,m,{view:c,temp:p,replace:g})}function _e(r,t,e){return W("read_csv",r,t,e,{auto_detect:!0,sample_size:-1})}function Pe(r,t,e){return W("read_json",r,t,e,{auto_detect:!0,json_format:"auto"})}function Ue(r,t,e){return W("read_parquet",r,t,e)}function Me(r,t,e={}){let{select:n=["*"],...o}=e,s=z(t),i=n.length===1&&n[0]==="*"?s:`SELECT ${n} FROM ${s}`;return G(r,i,o)}function Fe(r){return Object.entries(r).map(([t,e])=>{let n=typeof e,o=n==="boolean"?String(e):n==="string"?`'${e}'`:e;return`${t}=${o}`}).join(", ")}export{S as Query,w as Ref,Bt as agg,et as all,it as and,Re as argmax,Se as argmin,Te as arrayAgg,l as asColumn,_ as asRelation,kt as avg,Y as cast,be as castDouble,qe as castInteger,X as column,St as contains,le as corr,Qt as count,pe as covarPop,G as create,Ut as cume_dist,De as dateDay,Oe as dateMonth,Ie as dateMonthDay,_t as dense_rank,ot as desc,ce as entropy,Le as epoch_ms,ft as eq,ye as first,jt as first_value,gt,dt as gte,Nt as isBetween,Et as isDistinct,Ot as isFinite,It as isInfinite,Lt as isNaN,yt as isNotBetween,$t as isNotDistinct,pt as isNotNull,lt as isNull,q as isParamLike,F as isQuery,U as isSQLExpression,ie as kurtosis,Ft as lag,we as last,Yt as last_value,Gt as lead,qt as length,st as literal,E as literalToSQL,_e as loadCSV,Pe as loadJSON,Me as loadObjects,Ue as loadParquet,Tt as lower,mt as lt,xt as lte,Ht as mad,Kt as max,vt as mean,te as median,zt as min,re as mode,ht as neq,ut as not,Wt as nth_value,Mt as ntile,ct as or,Pt as percent_rank,Rt as prefix,Zt as product,ee as quantile,Ct as rank,wt as regexp_matches,$e as regrAvgX,Ne as regrAvgY,me as regrCount,fe as regrIntercept,ge as regrR2,de as regrSXX,Ee as regrSXY,xe as regrSYY,he as regrSlope,V as relation,Dt as row_number,se as skewness,u as sql,oe as stddev,ue as stddevPop,Ae as stringAgg,At as suffix,Jt as sum,rt as toSQL,bt as upper,ae as varPop,ne as variance};
|
|
1
|
+
var y=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?`${Q(t)}.`:""}${n}`}else return t?Q(t):"NULL"}};function Q(r){return r.split(".").map(e=>`"${e}"`).join(".")}function B(r,t){return r instanceof y&&r.column===t}function l(r){return typeof r=="string"?X(r):r}function I(r){return typeof r=="string"?V(r):r}function V(r){return new y(r)}function X(r,t){return arguments.length===1&&(t=r,r=null),new y(r,t)}function rt(r){return new y(r,"*")}function nt(r){return typeof r=="string"?`"${r}"`:E(r)}function E(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 A=r=>typeof r?.addEventListener=="function";function _(r){return r instanceof w}var w=class{constructor(t,e,n){this._expr=Array.isArray(t)?t:[t],this._deps=e||[],this.annotate(n);let o=this._expr.filter(s=>A(s));o.length>0?(this._params=Array.from(new Set(o)),this._params.forEach(s=>{s.addEventListener("value",()=>ot(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=>A(t)&&!_(t)?E(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 ot(r,t){if(t?.size)return Promise.allSettled(Array.from(t,e=>e(r)))}function G(r,t){let e=[r[0]],n=new Set,o=t.length;for(let s=0,i=0;s<o;){let c=t[s];A(c)?e[++i]=c:(Array.isArray(c?.columns)&&c.columns.forEach(g=>n.add(g)),e[i]+=typeof c=="string"?c:E(c));let p=r[++s];A(e[i])?e[++i]=p:e[i]+=p}return{spans:e,cols:Array.from(n)}}function a(r,...t){let{spans:e,cols:n}=G(r,t);return new w(e,n)}function st(r){let t=l(r);return a`${t} DESC NULLS LAST`.annotate({label:t?.label,desc:!0})}var it=r=>({value:r,toString:()=>E(r)});function D(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function k(r,t){let e=t.filter(o=>o!=null).map(l),n=e.map((o,s)=>s?` ${r} `:"");return t.length&&n.push(""),a(n,...e).annotate({op:r,children:e,visit:D})}var ct=(...r)=>k("AND",r.flat()),ut=(...r)=>k("OR",r.flat()),at=r=>t=>a`(${r} ${l(t)})`.annotate({op:r,a:t,visit:D}),lt=at("NOT"),v=r=>t=>a`(${l(t)} ${r})`.annotate({op:r,a:t,visit:D}),pt=v("IS NULL"),ft=v("IS NOT NULL"),S=r=>(t,e)=>a`(${l(t)} ${r} ${l(e)})`.annotate({op:r,a:t,b:e,visit:D}),ht=S("="),mt=S("<>"),gt=S("<"),xt=S(">"),dt=S("<="),Et=S(">="),$t=S("IS DISTINCT FROM"),Nt=S("IS NOT DISTINCT FROM");function H(r,t,e,n){t=l(t);let o=r.startsWith("NOT ")?"NOT ":"";return(e?n?a`${o}(${e[0]} <= ${t} AND ${t} < ${e[1]})`:a`(${t} ${r} ${e[0]} AND ${e[1]})`:a``).annotate({op:r,visit:D,field:t,range:e})}var yt=(r,t,e)=>H("BETWEEN",r,t,e),wt=(r,t,e)=>H("NOT BETWEEN",r,t,e);function T(r,t){return Array.from({length:r},()=>t)}function x(r,t){return(...e)=>{let n=e.map(l),o=t?`::${t}`:"";return(n.length?a([`${r}(`,...T(n.length-1,", "),`)${o}`],...n):a`${r}()${o}`).annotate({func:r,args:n})}}var St=x("REGEXP_MATCHES"),Rt=x("CONTAINS"),At=x("PREFIX"),Tt=x("SUFFIX"),bt=x("LOWER"),qt=x("UPPER"),Lt=x("LENGTH"),Ot=x("ISNAN"),It=x("ISFINITE"),Dt=x("ISINF");var C=class r extends w{constructor(t,e,n,o,s="",i="",c=""){let p;if(o&&!(s||i||c))p=o?a`${e} OVER "${o}"`:a`${e} OVER ()`;else{let q=s&&i?" ":"",L=(s||i)&&c?" ":"";p=a`${e} OVER (${o?`"${o}" `:""}${s}${q}${i}${L}${c})`}n&&(p=a`(${p})::${n}`);let{_expr:N,_deps:R}=p;super(N,R,{window:t,func:e,type:n,name:o,group:s,order:i,frame:c})}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:c}=this;return new r(e,n,o,t,s,i,c)}partitionby(...t){let e=t.flat().filter(N=>N).map(l),n=a(["PARTITION BY ",T(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:c,order:p,frame:g}=this;return new r(o,s,i,c,n,p,g)}orderby(...t){let e=t.flat().filter(N=>N).map(l),n=a(["ORDER BY ",T(e.length-1,", "),""],...e),{window:o,func:s,type:i,name:c,group:p,frame:g}=this;return new r(o,s,i,c,p,n,g)}rows(t){let e=K("ROWS",t),{window:n,func:o,type:s,name:i,group:c,order:p}=this;return new r(n,o,s,i,c,p,e)}range(t){let e=K("RANGE",t),{window:n,func:o,type:s,name:i,group:c,order:p}=this;return new r(n,o,s,i,c,p,e)}};function K(r,t){if(A(t)){let e=a`${t}`;return e.toString=()=>`${r} ${z(t.value)}`,e}return`${r} ${z(t)}`}function z(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 $(r,t){return(...e)=>{let n=x(r)(...e);return new C(r,n,t)}}var Ct=$("ROW_NUMBER","INTEGER"),_t=$("RANK","INTEGER"),Ft=$("DENSE_RANK","INTEGER"),Pt=$("PERCENT_RANK"),Ut=$("CUME_DIST"),Mt=$("NTILE"),Gt=$("LAG"),jt=$("LEAD"),Wt=$("FIRST_VALUE"),Yt=$("LAST_VALUE"),Qt=$("NTH_VALUE");function Bt(r,...t){return a(r,...t).annotate({aggregate:!0})}var j=class r extends w{constructor(t,e,n,o,s){e=(e||[]).map(l);let{strings:i,exprs:c}=Vt(t,e,n,o,s),{spans:p,cols:g}=G(i,c);super(p,g,{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(Xt).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 Vt(r,t,e,n,o){let s=`)${e?`::${e}`:""}`,i=[`${r}(${n?"DISTINCT ":""}`],c=[];return t.length?(i=i.concat([...T(t.length-1,", "),`${s}${o?" FILTER (WHERE ":""}`,...o?[")"]:[]]),c=[...t,...o?[o]:[]]):i[0]+="*"+s,{exprs:c,strings:i}}function Xt(r){let t=E(r);return t&&t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function u(r,t){return(...e)=>new j(r,e,t)}var kt=u("COUNT","INTEGER"),vt=u("AVG"),Ht=u("AVG"),Kt=u("MAD"),zt=u("MAX"),Jt=u("MIN"),Zt=u("SUM","DOUBLE"),te=u("PRODUCT"),ee=u("MEDIAN"),re=u("QUANTILE"),ne=u("MODE"),oe=u("VARIANCE"),se=u("STDDEV"),ie=u("SKEWNESS"),ce=u("KURTOSIS"),ue=u("ENTROPY"),ae=u("VAR_POP"),le=u("STDDEV_POP"),pe=u("CORR"),fe=u("COVAR_POP"),he=u("REGR_INTERCEPT"),me=u("REGR_SLOPE"),ge=u("REGR_COUNT"),xe=u("REGR_R2"),de=u("REGR_SYY"),Ee=u("REGR_SXX"),$e=u("REGR_SXY"),Ne=u("REGR_AVGX"),ye=u("REGR_AVGY"),we=u("FIRST"),Se=u("LAST"),Re=u("ARG_MIN"),Ae=u("ARG_MAX"),Te=u("STRING_AGG"),be=u("ARRAY_AGG");function W(r,t){let e=l(r),n=a`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 qe=r=>W(r,"DOUBLE"),Le=r=>W(r,"INTEGER");var Oe=r=>{let t=l(r);return a`(1000 * (epoch(${t}) - second(${t})) + millisecond(${t}))::DOUBLE`},Ie=r=>{let t=l(r);return a`MAKE_DATE(2012, MONTH(${t}), 1)`.annotate({label:"month"})},De=r=>{let t=l(r);return a`MAKE_DATE(2012, MONTH(${t}), DAY(${t}))`.annotate({label:"date"})},Ce=r=>{let t=l(r);return a`MAKE_DATE(2012, 1, DAY(${t}))`.annotate({label:"date"})};var U=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 b("UNION",t.flat())}static unionAll(...t){return new b("UNION ALL",t.flat())}static intersect(...t){return new b("INTERSECT",t.flat())}static except(...t){return new b("EXCEPT",t.flat())}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 c=i.clone();c.cteFor=this,n.push({as:s,query:c})};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:l(o)});else if(o instanceof y)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:F(s),expr:l(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:I(o)});else if(o instanceof y)n.push({as:o.table,from:o});else if(P(o)||_(o))n.push({from:o});else if(Array.isArray(o))n.push({as:F(o[0]),from:I(o[1])});else for(let s in o)n.push({as:F(s),from:I(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(l)),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:F(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(l)),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:c,query:p})=>(i[c]=p,i),{}),s=[];return t.from.forEach(({from:i})=>{if(P(i))s.push(i);else if(o[i.table]){let c=o[i.table];s.push(c)}}),s}toString(){let{select:t,distinct:e,from:n,sample:o,where:s,groupby:i,having:c,window:p,qualify:g,orderby:N,limit:R,offset:q,with:L}=this.query,m=[];if(L.length){let f=L.map(({as:h,query:d})=>`"${h}" AS (${d})`);m.push(`WITH ${f.join(", ")}`)}let Z=t.map(({as:f,expr:h})=>B(h,f)&&!h.table?`${h}`:`${h} AS "${f}"`);if(m.push(`SELECT${e?" DISTINCT":""} ${Z.join(", ")}`),n.length){let f=n.map(({as:h,from:d})=>{let O=P(d)?`(${d})`:`${d}`;return!h||h===d.table?O:`${O} AS "${h}"`});m.push(`FROM ${f.join(", ")}`)}if(s.length){let f=s.map(String).filter(h=>h).join(" AND ");f&&m.push(`WHERE ${f}`)}if(o){let{rows:f,perc:h,method:d,seed:O}=o,tt=f?`${f} ROWS`:`${h} PERCENT`,et=d?` (${d}${O!=null?`, ${O}`:""})`:"";m.push(`USING SAMPLE ${tt}${et}`)}if(i.length&&m.push(`GROUP BY ${i.join(", ")}`),c.length){let f=c.map(String).filter(h=>h).join(" AND ");f&&m.push(`HAVING ${f}`)}if(p.length){let f=p.map(({as:h,expr:d})=>`"${h}" AS (${d})`);m.push(`WINDOW ${f.join(", ")}`)}if(g.length){let f=g.map(String).filter(h=>h).join(" AND ");f&&m.push(`QUALIFY ${f}`)}return N.length&&m.push(`ORDER BY ${N.join(", ")}`),Number.isFinite(R)&&m.push(`LIMIT ${R}`),Number.isFinite(q)&&m.push(`OFFSET ${q}`),m.join(" ")}},b=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(l)),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 P(r){return r instanceof U||r instanceof b}function F(r){return _e(r)?r.slice(1,-1):r}function _e(r){return r[0]==='"'&&r[r.length-1]==='"'}function M(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 J(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=>`${E(o[i])} AS "${t[i]}"`);n.push(`(SELECT ${s.join(", ")})`)}return n.join(" UNION ALL ")}function Y(r,t,e,n={},o={}){let{select:s=["*"],where:i,view:c,temp:p,replace:g,...N}=n,R=Ge({...o,...N}),q=`${r}('${e}'${R?", "+R:""})`,L=i?` WHERE ${i}`:"",m=`SELECT ${s.join(", ")} FROM ${q}${L}`;return M(t,m,{view:c,temp:p,replace:g})}function Fe(r,t,e){return Y("read_csv",r,t,e,{auto_detect:!0,sample_size:-1})}function Pe(r,t,e){return Y("read_json",r,t,e,{auto_detect:!0,json_format:"auto"})}function Ue(r,t,e){return Y("read_parquet",r,t,e)}function Me(r,t,e={}){let{select:n=["*"],...o}=e,s=J(t),i=n.length===1&&n[0]==="*"?s:`SELECT ${n} FROM ${s}`;return M(r,i,o)}function Ge(r){return Object.entries(r).map(([t,e])=>{let n=typeof e,o=n==="boolean"?String(e):n==="string"?`'${e}'`:e;return`${t}=${o}`}).join(", ")}export{U as Query,y as Ref,Bt as agg,rt as all,ct as and,Ae as argmax,Re as argmin,be as arrayAgg,l as asColumn,I as asRelation,vt as avg,W as cast,qe as castDouble,Le as castInteger,X as column,Rt as contains,pe as corr,kt as count,fe as covarPop,M as create,Ut as cume_dist,Ce as dateDay,Ie as dateMonth,De as dateMonthDay,Ft as dense_rank,st as desc,ue as entropy,Oe as epoch_ms,ht as eq,we as first,Wt as first_value,xt as gt,Et as gte,yt as isBetween,$t as isDistinct,It as isFinite,Dt as isInfinite,Ot as isNaN,wt as isNotBetween,Nt as isNotDistinct,ft as isNotNull,pt as isNull,A as isParamLike,P as isQuery,_ as isSQLExpression,ce as kurtosis,Gt as lag,Se as last,Yt as last_value,jt as lead,Lt as length,it as literal,E as literalToSQL,Fe as loadCSV,Pe as loadJSON,Me as loadObjects,Ue as loadParquet,bt as lower,gt as lt,dt as lte,Kt as mad,zt as max,Ht as mean,ee as median,Jt as min,ne as mode,mt as neq,lt as not,Qt as nth_value,Mt as ntile,ut as or,Pt as percent_rank,At as prefix,te as product,re as quantile,_t as rank,St as regexp_matches,Ne as regrAvgX,ye as regrAvgY,ge as regrCount,he as regrIntercept,xe as regrR2,Ee as regrSXX,$e as regrSXY,de as regrSYY,me as regrSlope,V as relation,Ct as row_number,ie as skewness,a as sql,se as stddev,le as stddevPop,Te as stringAgg,Tt as suffix,Zt as sum,nt as toSQL,qt as upper,ae as varPop,oe as variance};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@uwdata/mosaic-sql",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "SQL query construction and analysis.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sql",
|
|
@@ -25,5 +25,5 @@
|
|
|
25
25
|
"test": "mocha 'test/**/*-test.js'",
|
|
26
26
|
"prepublishOnly": "npm run test && npm run lint && npm run build"
|
|
27
27
|
},
|
|
28
|
-
"gitHead": "
|
|
28
|
+
"gitHead": "788bb137cc402b472fc7e4d84844c78151707c82"
|
|
29
29
|
}
|
package/src/ref.js
CHANGED
|
@@ -28,13 +28,23 @@ export class Ref {
|
|
|
28
28
|
const { table, column } = this;
|
|
29
29
|
if (column) {
|
|
30
30
|
const col = column.startsWith('*') ? column : `"${column}"`;
|
|
31
|
-
return `${table ?
|
|
31
|
+
return `${table ? `${quoteTableName(table)}.` : ''}${col}`;
|
|
32
32
|
} else {
|
|
33
|
-
return table ?
|
|
33
|
+
return table ? quoteTableName(table) : 'NULL';
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
}
|
|
37
37
|
|
|
38
|
+
/**
|
|
39
|
+
* Quote a table name. For example, `foo.bar` becomes `"foo"."bar".
|
|
40
|
+
* @param {string} table the name of the table which may contain a database reference
|
|
41
|
+
* @returns The quoted table name.
|
|
42
|
+
*/
|
|
43
|
+
function quoteTableName(table) {
|
|
44
|
+
const pieces = table.split('.');
|
|
45
|
+
return pieces.map(p => `"${p}"`).join('.');
|
|
46
|
+
}
|
|
47
|
+
|
|
38
48
|
/**
|
|
39
49
|
* Test is a reference refers to a given column name.
|
|
40
50
|
* @param {*} ref The reference to test.
|