@uwdata/mosaic-sql
Advanced tools
Comparing version 0.3.4 to 0.3.5
@@ -233,4 +233,8 @@ // src/ref.js | ||
const strings = children.map((c, i) => i ? ` ${op} ` : ""); | ||
if (clauses.length) | ||
if (children.length === 1) { | ||
strings.push(""); | ||
} else if (children.length > 1) { | ||
strings[0] = "("; | ||
strings.push(")"); | ||
} | ||
return sql(strings, ...children).annotate({ op, children, visit }); | ||
@@ -237,0 +241,0 @@ } |
@@ -1,1 +0,1 @@ | ||
var N=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 V(r,t){return r instanceof N&&r.column===t}function l(r){return typeof r=="string"?k(r):r}function I(r){return typeof r=="string"?X(r):r}function X(r){return new N(r)}function k(r,t){return arguments.length===1&&(t=r,r=null),new N(r,t)}function nt(r){return new N(r,"*")}function ot(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",()=>st(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 st(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 it(r){let t=l(r);return a`${t} DESC NULLS LAST`.annotate({label:t?.label,desc:!0})}var ct=r=>({value:r,toString:()=>E(r)});function D(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function H(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 ut=(...r)=>H("AND",r.flat()),at=(...r)=>H("OR",r.flat()),lt=r=>t=>a`(${r} ${l(t)})`.annotate({op:r,a:t,visit:D}),pt=lt("NOT"),K=r=>t=>a`(${l(t)} ${r})`.annotate({op:r,a:t,visit:D}),ft=K("IS NULL"),ht=K("IS NOT NULL"),S=r=>(t,e)=>a`(${l(t)} ${r} ${l(e)})`.annotate({op:r,a:t,b:e,visit:D}),mt=S("="),gt=S("<>"),dt=S("<"),xt=S(">"),Et=S("<="),$t=S(">="),yt=S("IS DISTINCT FROM"),Nt=S("IS NOT DISTINCT FROM");function v(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 wt=(r,t,e)=>v("BETWEEN",r,t,e),St=(r,t,e)=>v("NOT BETWEEN",r,t,e);function T(r,t){return Array.from({length:r},()=>t)}function d(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 Rt=d("REGEXP_MATCHES"),At=d("CONTAINS"),Tt=d("PREFIX"),bt=d("SUFFIX"),qt=d("LOWER"),Lt=d("UPPER"),Ot=d("LENGTH"),It=d("ISNAN"),Dt=d("ISFINITE"),Ct=d("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:y,_deps:R}=p;super(y,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(y=>y).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(y=>y).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=z("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=z("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 z(r,t){if(A(t)){let e=a`${t}`;return e.toString=()=>`${r} ${J(t.value)}`,e}return`${r} ${J(t)}`}function J(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=d(r)(...e);return new C(r,n,t)}}var _t=$("ROW_NUMBER","INTEGER"),Ft=$("RANK","INTEGER"),Pt=$("DENSE_RANK","INTEGER"),Ut=$("PERCENT_RANK"),Mt=$("CUME_DIST"),Gt=$("NTILE"),jt=$("LAG"),Wt=$("LEAD"),Yt=$("FIRST_VALUE"),Bt=$("LAST_VALUE"),Qt=$("NTH_VALUE");function Vt(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}=Xt(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(kt).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 Xt(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 kt(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 Ht=u("COUNT","INTEGER"),Kt=u("AVG"),vt=u("AVG"),zt=u("MAD"),Jt=u("MAX"),Zt=u("MIN"),te=u("SUM","DOUBLE"),ee=u("PRODUCT"),re=u("MEDIAN"),ne=u("QUANTILE"),oe=u("MODE"),se=u("VARIANCE"),ie=u("STDDEV"),ce=u("SKEWNESS"),ue=u("KURTOSIS"),ae=u("ENTROPY"),le=u("VAR_POP"),pe=u("STDDEV_POP"),fe=u("CORR"),he=u("COVAR_POP"),me=u("REGR_INTERCEPT"),ge=u("REGR_SLOPE"),de=u("REGR_COUNT"),xe=u("REGR_R2"),Ee=u("REGR_SYY"),$e=u("REGR_SXX"),ye=u("REGR_SXY"),Ne=u("REGR_AVGX"),we=u("REGR_AVGY"),Se=u("FIRST"),Re=u("LAST"),Ae=u("ARG_MIN"),Te=u("ARG_MAX"),be=u("STRING_AGG"),qe=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 Le=r=>W(r,"DOUBLE"),Oe=r=>W(r,"INTEGER");var Ie=r=>{let t=l(r);return a`(1000 * (epoch(${t}) - second(${t})) + millisecond(${t}))::DOUBLE`},De=r=>{let t=l(r);return a`MAKE_DATE(2012, MONTH(${t}), 1)`.annotate({label:"month"})},Ce=r=>{let t=l(r);return a`MAKE_DATE(2012, MONTH(${t}), DAY(${t}))`.annotate({label:"date"})},_e=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 N)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 N)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:y,limit:R,offset:q,with:L}=this.query,m=[];if(L.length){let f=L.map(({as:h,query:x})=>`"${h}" AS (${x})`);m.push(`WITH ${f.join(", ")}`)}let tt=t.map(({as:f,expr:h})=>V(h,f)&&!h.table?`${h}`:`${h} AS "${f}"`);if(m.push(`SELECT${e?" DISTINCT":""} ${tt.join(", ")}`),n.length){let f=n.map(({as:h,from:x})=>{let O=P(x)?`(${x})`:`${x}`;return!h||h===x.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:x,seed:O}=o,et=f?`${f} ROWS`:`${h} PERCENT`,rt=x?` (${x}${O!=null?`, ${O}`:""})`:"";m.push(`USING SAMPLE ${et}${rt}`)}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:x})=>`"${h}" AS (${x})`);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(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 Fe(r)?r.slice(1,-1):r}function Fe(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 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 B(r,t,e,n={},o={}){let{select:s=["*"],where:i,view:c,temp:p,replace:g,...y}=n,R=je({...o,...y}),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 Pe(r,t,e){return B("read_csv",r,t,e,{auto_detect:!0,sample_size:-1})}function Ue(r,t,e){return B("read_json",r,t,e,{auto_detect:!0,json_format:"auto"})}function Me(r,t,e){return B("read_parquet",r,t,e)}function Ge(r,t,e={}){let{select:n=["*"],...o}=e,s=Z(t),i=n.length===1&&n[0]==="*"?s:`SELECT ${n} FROM ${s}`;return M(r,i,o)}function je(r){return Object.entries(r).map(([t,e])=>`${t}=${Y(e)}`).join(", ")}function Y(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=>Y(t)).join(", ")+"]":"{"+Object.entries(r).map(([t,e])=>`'${t}': ${Y(e)}`).join(", ")+"}";default:return r}}export{U as Query,N as Ref,Vt as agg,nt as all,ut as and,Te as argmax,Ae as argmin,qe as arrayAgg,l as asColumn,I as asRelation,Kt as avg,W as cast,Le as castDouble,Oe as castInteger,k as column,At as contains,fe as corr,Ht as count,he as covarPop,M as create,Mt as cume_dist,_e as dateDay,De as dateMonth,Ce as dateMonthDay,Pt as dense_rank,it as desc,ae as entropy,Ie as epoch_ms,mt as eq,Se as first,Yt as first_value,xt as gt,$t as gte,wt as isBetween,yt as isDistinct,Dt as isFinite,Ct as isInfinite,It as isNaN,St as isNotBetween,Nt as isNotDistinct,ht as isNotNull,ft as isNull,A as isParamLike,P as isQuery,_ as isSQLExpression,ue as kurtosis,jt as lag,Re as last,Bt as last_value,Wt as lead,Ot as length,ct as literal,E as literalToSQL,Pe as loadCSV,Ue as loadJSON,Ge as loadObjects,Me as loadParquet,qt as lower,dt as lt,Et as lte,zt as mad,Jt as max,vt as mean,re as median,Zt as min,oe as mode,gt as neq,pt as not,Qt as nth_value,Gt as ntile,at as or,Ut as percent_rank,Tt as prefix,ee as product,ne as quantile,Ft as rank,Rt as regexp_matches,Ne as regrAvgX,we as regrAvgY,de as regrCount,me as regrIntercept,xe as regrR2,$e as regrSXX,ye as regrSXY,Ee as regrSYY,ge as regrSlope,X as relation,_t as row_number,ce as skewness,a as sql,ie as stddev,pe as stddevPop,be as stringAgg,bt as suffix,te as sum,ot as toSQL,Lt as upper,le as varPop,se as variance}; | ||
var N=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 V(r,t){return r instanceof N&&r.column===t}function l(r){return typeof r=="string"?k(r):r}function I(r){return typeof r=="string"?X(r):r}function X(r){return new N(r)}function k(r,t){return arguments.length===1&&(t=r,r=null),new N(r,t)}function nt(r){return new N(r,"*")}function ot(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",()=>st(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 st(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 it(r){let t=l(r);return a`${t} DESC NULLS LAST`.annotate({label:t?.label,desc:!0})}var ct=r=>({value:r,toString:()=>E(r)});function D(r){r(this.op,this),this.children?.forEach(t=>t.visit(r))}function H(r,t){let e=t.filter(o=>o!=null).map(l),n=e.map((o,s)=>s?` ${r} `:"");return e.length===1?n.push(""):e.length>1&&(n[0]="(",n.push(")")),a(n,...e).annotate({op:r,children:e,visit:D})}var ut=(...r)=>H("AND",r.flat()),at=(...r)=>H("OR",r.flat()),lt=r=>t=>a`(${r} ${l(t)})`.annotate({op:r,a:t,visit:D}),pt=lt("NOT"),K=r=>t=>a`(${l(t)} ${r})`.annotate({op:r,a:t,visit:D}),ft=K("IS NULL"),ht=K("IS NOT NULL"),S=r=>(t,e)=>a`(${l(t)} ${r} ${l(e)})`.annotate({op:r,a:t,b:e,visit:D}),mt=S("="),gt=S("<>"),dt=S("<"),xt=S(">"),Et=S("<="),$t=S(">="),yt=S("IS DISTINCT FROM"),Nt=S("IS NOT DISTINCT FROM");function v(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 wt=(r,t,e)=>v("BETWEEN",r,t,e),St=(r,t,e)=>v("NOT BETWEEN",r,t,e);function T(r,t){return Array.from({length:r},()=>t)}function d(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 Rt=d("REGEXP_MATCHES"),At=d("CONTAINS"),Tt=d("PREFIX"),bt=d("SUFFIX"),qt=d("LOWER"),Lt=d("UPPER"),Ot=d("LENGTH"),It=d("ISNAN"),Dt=d("ISFINITE"),Ct=d("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:y,_deps:R}=p;super(y,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(y=>y).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(y=>y).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=z("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=z("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 z(r,t){if(A(t)){let e=a`${t}`;return e.toString=()=>`${r} ${J(t.value)}`,e}return`${r} ${J(t)}`}function J(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=d(r)(...e);return new C(r,n,t)}}var _t=$("ROW_NUMBER","INTEGER"),Ft=$("RANK","INTEGER"),Pt=$("DENSE_RANK","INTEGER"),Ut=$("PERCENT_RANK"),Mt=$("CUME_DIST"),Gt=$("NTILE"),jt=$("LAG"),Wt=$("LEAD"),Yt=$("FIRST_VALUE"),Bt=$("LAST_VALUE"),Qt=$("NTH_VALUE");function Vt(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}=Xt(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(kt).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 Xt(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 kt(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 Ht=u("COUNT","INTEGER"),Kt=u("AVG"),vt=u("AVG"),zt=u("MAD"),Jt=u("MAX"),Zt=u("MIN"),te=u("SUM","DOUBLE"),ee=u("PRODUCT"),re=u("MEDIAN"),ne=u("QUANTILE"),oe=u("MODE"),se=u("VARIANCE"),ie=u("STDDEV"),ce=u("SKEWNESS"),ue=u("KURTOSIS"),ae=u("ENTROPY"),le=u("VAR_POP"),pe=u("STDDEV_POP"),fe=u("CORR"),he=u("COVAR_POP"),me=u("REGR_INTERCEPT"),ge=u("REGR_SLOPE"),de=u("REGR_COUNT"),xe=u("REGR_R2"),Ee=u("REGR_SYY"),$e=u("REGR_SXX"),ye=u("REGR_SXY"),Ne=u("REGR_AVGX"),we=u("REGR_AVGY"),Se=u("FIRST"),Re=u("LAST"),Ae=u("ARG_MIN"),Te=u("ARG_MAX"),be=u("STRING_AGG"),qe=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 Le=r=>W(r,"DOUBLE"),Oe=r=>W(r,"INTEGER");var Ie=r=>{let t=l(r);return a`(1000 * (epoch(${t}) - second(${t})) + millisecond(${t}))::DOUBLE`},De=r=>{let t=l(r);return a`MAKE_DATE(2012, MONTH(${t}), 1)`.annotate({label:"month"})},Ce=r=>{let t=l(r);return a`MAKE_DATE(2012, MONTH(${t}), DAY(${t}))`.annotate({label:"date"})},_e=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 N)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 N)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:y,limit:R,offset:q,with:L}=this.query,m=[];if(L.length){let f=L.map(({as:h,query:x})=>`"${h}" AS (${x})`);m.push(`WITH ${f.join(", ")}`)}let tt=t.map(({as:f,expr:h})=>V(h,f)&&!h.table?`${h}`:`${h} AS "${f}"`);if(m.push(`SELECT${e?" DISTINCT":""} ${tt.join(", ")}`),n.length){let f=n.map(({as:h,from:x})=>{let O=P(x)?`(${x})`:`${x}`;return!h||h===x.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:x,seed:O}=o,et=f?`${f} ROWS`:`${h} PERCENT`,rt=x?` (${x}${O!=null?`, ${O}`:""})`:"";m.push(`USING SAMPLE ${et}${rt}`)}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:x})=>`"${h}" AS (${x})`);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(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 Fe(r)?r.slice(1,-1):r}function Fe(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 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 B(r,t,e,n={},o={}){let{select:s=["*"],where:i,view:c,temp:p,replace:g,...y}=n,R=je({...o,...y}),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 Pe(r,t,e){return B("read_csv",r,t,e,{auto_detect:!0,sample_size:-1})}function Ue(r,t,e){return B("read_json",r,t,e,{auto_detect:!0,json_format:"auto"})}function Me(r,t,e){return B("read_parquet",r,t,e)}function Ge(r,t,e={}){let{select:n=["*"],...o}=e,s=Z(t),i=n.length===1&&n[0]==="*"?s:`SELECT ${n} FROM ${s}`;return M(r,i,o)}function je(r){return Object.entries(r).map(([t,e])=>`${t}=${Y(e)}`).join(", ")}function Y(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=>Y(t)).join(", ")+"]":"{"+Object.entries(r).map(([t,e])=>`'${t}': ${Y(e)}`).join(", ")+"}";default:return r}}export{U as Query,N as Ref,Vt as agg,nt as all,ut as and,Te as argmax,Ae as argmin,qe as arrayAgg,l as asColumn,I as asRelation,Kt as avg,W as cast,Le as castDouble,Oe as castInteger,k as column,At as contains,fe as corr,Ht as count,he as covarPop,M as create,Mt as cume_dist,_e as dateDay,De as dateMonth,Ce as dateMonthDay,Pt as dense_rank,it as desc,ae as entropy,Ie as epoch_ms,mt as eq,Se as first,Yt as first_value,xt as gt,$t as gte,wt as isBetween,yt as isDistinct,Dt as isFinite,Ct as isInfinite,It as isNaN,St as isNotBetween,Nt as isNotDistinct,ht as isNotNull,ft as isNull,A as isParamLike,P as isQuery,_ as isSQLExpression,ue as kurtosis,jt as lag,Re as last,Bt as last_value,Wt as lead,Ot as length,ct as literal,E as literalToSQL,Pe as loadCSV,Ue as loadJSON,Ge as loadObjects,Me as loadParquet,qt as lower,dt as lt,Et as lte,zt as mad,Jt as max,vt as mean,re as median,Zt as min,oe as mode,gt as neq,pt as not,Qt as nth_value,Gt as ntile,at as or,Ut as percent_rank,Tt as prefix,ee as product,ne as quantile,Ft as rank,Rt as regexp_matches,Ne as regrAvgX,we as regrAvgY,de as regrCount,me as regrIntercept,xe as regrR2,$e as regrSXX,ye as regrSXY,Ee as regrSYY,ge as regrSlope,X as relation,_t as row_number,ce as skewness,a as sql,ie as stddev,pe as stddevPop,be as stringAgg,bt as suffix,te as sum,ot as toSQL,Lt as upper,le as varPop,se as variance}; |
{ | ||
"name": "@uwdata/mosaic-sql", | ||
"version": "0.3.4", | ||
"version": "0.3.5", | ||
"description": "SQL query construction and analysis.", | ||
@@ -28,3 +28,3 @@ "keywords": [ | ||
}, | ||
"gitHead": "faed78bc6264faa09a20b385601e03a9e1e15979" | ||
"gitHead": "7cc66d26c687a28036b3c7102045f2196572847b" | ||
} |
@@ -12,3 +12,8 @@ import { sql } from './expression.js'; | ||
const strings = children.map((c, i) => i ? ` ${op} ` : ''); | ||
if (clauses.length) strings.push(''); | ||
if (children.length === 1) { | ||
strings.push('') | ||
} else if (children.length > 1) { | ||
strings[0] = '('; | ||
strings.push(')'); | ||
} | ||
return sql(strings, ...children).annotate({ op, children, visit }); | ||
@@ -15,0 +20,0 @@ } |
89871
2476