palgres 0.81.1 → 0.82.1
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/chunks/{P2LMMSM6.js → 5P4M3O6D.js} +1 -1
- package/dist/chunks/{4AOJR22N.js → 7FSDHACP.js} +2 -2
- package/dist/chunks/{RVEWGWBM.js → 7WZUSO4S.js} +1 -1
- package/dist/chunks/{I2IEMIXK.js → HGB6RJ4X.js} +2 -2
- package/dist/chunks/{BRFJFLD6.js → IUXPTGUJ.js} +2 -2
- package/dist/chunks/{34H3ENWF.js → YXBLVWLV.js} +1 -1
- package/dist/cli.js +2 -2
- package/dist/dsl.js +2 -2
- package/dist/index.js +31 -31
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/palgres/src/query/admission.d.ts +29 -2
- package/types/palgres/src/query/request.d.ts +7 -1
package/dist/testing.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{D as J,G as Se,H as Ue,a as ae,b as Ee,d as Me,l as ee,m as Ie,n as ue,r as le,s as ne,t as fe,u as Ne,w as H}from"./chunks/BRFJFLD6.js";import{n as Te,p as Ae}from"./chunks/34H3ENWF.js";import{G as Q,H as G,I as Oe,J as ce,K as xe,q as $e,u as ke}from"./chunks/P2LMMSM6.js";import{randomUUID as He}from"node:crypto";var Pe=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,De="access: its time passed",Ce="user";function Fe(t){let o=t.filter(u=>u!=null);return o.length===0?"text":o.every(u=>typeof u=="boolean")?"bool":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isInteger(u))?"int":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isFinite(u))?"numeric":o.every(u=>typeof u=="string"&&Pe.test(u))?"uuid":"text"}function Le(t,o){return o==null?null:t==="bool"||t==="int"||t==="numeric"||typeof o=="string"?o:String(o)}var de=t=>t.schema==="public"?t.name:`${t.schema}.${t.name}`;function _e(t,o){let u=ke($e(t)),d=Ee(t,"memory"),p,f=[],w=[],m=0,O=new Map,k=[...u.types.values()].filter(e=>e.table),_=e=>{let r=u.types.get(e),i=new Set;if(!r?.table)return[];i.add(r.table.key??"id");let s=a=>{let g=a;g.parts?g.parts.forEach(s):g.part?s(g.part):g.column&&i.add(g.column)};for(let a of r.relations.values())a.kind!=="stored"&&(a.kind==="column"&&i.add(a.column),a.where&&s(a.where));return[...i]},F=()=>{let e=new Map;for(let r of k){let i=r.table,s=o.rows(de(i)),a=i.key??"id",g={};for(let b of _(r.name))g[b]=Fe(s.map(y=>y[b]));let h={key:a,columns:g};e.set(r.name,{shape:h,rows:s.map(b=>Object.fromEntries(Object.entries(g).map(([y,j])=>[y,Le(j,b[y])])))})}return{tables:e,relationships:f,now:Date.now()}},C=(e,r,i)=>{let s=e.tables.get(r);if(!s)return i;let a=s.shape.columns[s.shape.key],g=Q(a,i);return g===null?null:s.rows.some(b=>{let y=b[s.shape.key];return y!==null&&Q(a,String(y))===g})?g:void 0},M=()=>{for(let r of k){let i=r.table,s=de(i),a=i.key??"id",g=o.deleted(s),h=Math.min(O.get(s)??0,g.length),b=j=>Pe.test(j)?j.toLowerCase():j,y=new Set(g.slice(h).map(j=>j[a]).filter(j=>j!=null).map(j=>b(String(j))));O.set(s,g.length),y.size>0&&V(r.name,j=>y.has(b(j)),"access: row deleted")}let e=F();for(let r of k)V(r.name,i=>C(e,r.name,i)===void 0,"access: row deleted");return F()},T=e=>e.expiresAt!==void 0&&e.expiresAt!==null&&e.expiresAt<=Date.now(),E=(e,r)=>T(e)?W("expire",e,De,e.expiresAt):W("revoke",e,r),N=(e,r)=>{let i=[],s=0;for(let a of f)e(a)?(E(a,r),s++):i.push(a);return f=i,s},V=(e,r,i)=>{N(s=>s.objectType===e&&r(s.objectId)||s.subjectType===e&&r(s.subjectId),i)},U=e=>new Date(e).toISOString().replace("Z","000Z"),B=e=>e==null?null:U(e),W=(e,r,i,s)=>{w.push({seq:++m,at:U(s??Date.now()),action:e,object:{type:r.objectType,id:r.objectId},relation:r.relation,subject:{type:r.subjectType,id:r.subjectId},by:i,until:B(r.expiresAt)})},X=(e,r)=>(e.object_type===void 0||e.object_type===r.objectType)&&(e.object_id===void 0||e.object_id===r.objectId)&&(e.relation===void 0||e.relation===r.relation)&&(e.subject_type===void 0||e.subject_type===r.subjectType)&&(e.subject_id===void 0||e.subject_id===r.subjectId),n=(e,r)=>{for(let i of["objectType","objectId","relation","subjectType","subjectId"])if(e[i]!==r[i])return e[i]<r[i]?-1:1;return 0},c={caller:()=>p,check(e,r,i,s){let a=M(),g=C(a,i,s);return g==null?!1:G(u,a).check(e,i,g,r)},objects:(e,r,i)=>G(u,M()).objects(e,i,r),subjects(e,r,i){let s=M(),a=C(s,r,i);return a==null?[]:G(u,s).subjects(r,a,e)},open(e,r,i){let s=M(),a=C(s,r,i);return a==null?null:G(u,s).open(r,a,e)},change(e,r,i,s,a,g){let h=M(),b=(R,I,S)=>{if(I===Ce)return S;let A=C(h,I,S);if(A==null)throw new ae("no_object",`Database.$access: there is no ${I} ${JSON.stringify(S)} (${R}) \u2014 a relationship is given on an object that exists`);return A};if(e==="revoke"){let R=(L,je)=>{let ie=L===Ce?void 0:h.tables.get(L);return ie?Q(ie.shape.columns[ie.shape.key],je):je},I=R(r.type,r.id),S=R(s.type,s.id);if(I===null||S===null)return!1;let A={objectType:r.type,objectId:I,relation:i,subjectType:s.type,subjectId:S},D=f.find(L=>n(L,A)===0);if(!D)return!1;let Ve=!T(D);return N(L=>L===D,a??p??null),Ve}let y={objectType:r.type,objectId:b("the object",r.type,r.id),relation:i,subjectType:s.type,subjectId:b("the subject",s.type,s.id),expiresAt:g??null},j=u.trees.find(R=>R.type===y.objectType&&R.relation===y.relation&&u.types.get(R.type)?.relations.get(R.relation)?.kind==="stored");if(j&&y.subjectType===y.objectType){let R=Date.now(),I=f.filter(A=>A.objectType===j.type&&A.relation===j.relation&&A.subjectType===j.type&&!T(A)),S=xe(j,I,y.objectId,y.subjectId,R)??ce(j.type,j.depth,y.objectId,y.subjectId,A=>I.filter(D=>D.objectId===A).map(D=>D.subjectId),A=>I.filter(D=>D.subjectId===A).map(D=>D.objectId));if(S)throw new ae(Me[S.code],`Database.$access: ${S.message}`)}N(R=>R.objectType===y.objectType&&R.objectId===y.objectId&&T(R),null);let $=f.find(R=>n(R,y)===0);return $?(($.expiresAt??null)!==(y.expiresAt??null)&&($.expiresAt=y.expiresAt,W("grant",y,a??p??null)),!1):(f.push({...y,since:U(Date.now())}),W("grant",y,a??p??null),!0)},sweep(e){M();let r=f.filter(T).sort((i,s)=>i.expiresAt-s.expiresAt).slice(0,e);return N(i=>r.includes(i),null)},relationships(e,r){return M(),f.filter(i=>!T(i)&&X(e,i)).sort(n).slice(0,r).map(i=>({object:{type:i.objectType,id:i.objectId},relation:i.relation,subject:{type:i.subjectType,id:i.subjectId},since:i.since,until:B(i.expiresAt)}))},history(e,r){M();let i=f.filter(T).map(s=>({seq:Number.POSITIVE_INFINITY,at:B(s.expiresAt),action:"expire",object:{type:s.objectType,id:s.objectId},relation:s.relation,subject:{type:s.subjectType,id:s.subjectId},by:De,until:B(s.expiresAt)}));return[...w,...i].filter(s=>X(e,{objectType:s.object.type,objectId:s.object.id,relation:s.relation,subjectType:s.subject.type,subjectId:s.subject.id})).sort((s,a)=>s.at!==a.at?s.at<a.at?1:-1:a.seq===s.seq?0:a.seq>s.seq?1:-1).slice(0,r).map(({seq:s,...a})=>({...a,object:{...a.object},subject:{...a.subject}}))}},l=e=>{let r=k.find(i=>de(i.table)===e);return r?u.trees.flatMap(i=>{let s=i.type===r.name?r.relations.get(i.relation):void 0;return s?.kind==="column"?[{type:r.name,key:r.table?.key??"id",column:s.column,depth:i.depth}]:[]}):[]};return{names:d,via:c,nested:e=>l(e).length>0,misplaced(e,r,i){for(let s of l(e)){let a=Fe(i.map($=>$[s.key])),g=$=>$==null?null:Q(a,String($)),h=new Map;for(let $ of i){let R=g($[s.key]);R!==null&&h.set(R,g($[s.column]))}let b=new Map;for(let $ of r){let R=g($[s.key]);R!==null&&b.set(R,g($[s.column]))}let y=$=>[...h].filter(([,R])=>R===$).map(([R])=>R),j=$=>$!==null&&h.has($)?$:null;for(let[$,R]of h){if(b.has($)&&b.get($)===R||R===null&&y($).length===0)continue;if(R!==null&&!h.has(R))return Oe(s.type,$,R);let I=ce(s.type,s.depth,$,j(R),S=>[j(h.get(S)??null)].filter(A=>A!==null),y);if(I)return I}}return null},signedInAs(e){p=e},snapshot(){let e={relationships:f.map(r=>({...r})),history:w.map(r=>({...r})),written:m,seen:new Map(O),user:p};return()=>{f=e.relationships,w=e.history,m=e.written,O=e.seen,p=e.user}}}}var Ke=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,ve=/^([+-]?)(\d*)(?:\.(\d*))?$/;function Z(t){if(t instanceof Date)return t.getTime();if(typeof t=="string"&&Ke.test(t)){let o=Date.parse(t);return Number.isNaN(o)?null:o}return null}function v(t){if(typeof t=="number")return Number.isFinite(t)?v(String(t)):null;if(typeof t!="string"||/e/i.test(t))return null;let o=ve.exec(t.trim());if(o===null||o[2]===""&&(o[3]??"")==="")return null;let u=o[3]??"";return{unit:BigInt(`${o[1]==="-"?"-":""}${o[2]===""?"0":o[2]}${u}`),scale:u.length}}function se(t,o){return t.unit*10n**BigInt(o-t.scale)}function ye(t,o){if(t==null||o===null||o===void 0)return null;let u=Z(t),d=Z(o);if(u!==null&&d!==null)return Math.sign(u-d);let p=v(t),f=v(o);if(p!==null&&f!==null){let w=Math.max(p.scale,f.scale),m=se(p,w)-se(f,w);return m===0n?0:m<0n?-1:1}return typeof t==typeof o&&(typeof t=="string"||typeof t=="boolean"||typeof t=="number")?t<o?-1:t>o?1:0:null}function q(t,o){return t==null||o===null||o===void 0?!1:t instanceof Date||o instanceof Date?Z(t)!==null&&Z(t)===Z(o):Array.isArray(t)&&Array.isArray(o)?t.length===o.length&&t.every((u,d)=>q(u,o[d])):t===o}function oe(t){let o=((t?.days??0)*86400+(t?.hours??0)*3600+(t?.minutes??0)*60+(t?.seconds??0))*1e3;return new Date(Date.now()-o).toISOString()}function ge(t,o,u){if(t==null)return null;if(typeof t=="number"&&typeof o=="number")return t+u*o;let d=v(t),p=v(o);if(d===null||p===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(t)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(d.scale,p.scale),w=se(d,f)+BigInt(u)*se(p,f);if(f===0)return typeof t=="number"?Number(w):w.toString();let m=w<0n,O=(m?-w:w).toString().padStart(f+1,"0"),k=`${m?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof t=="number"?Number(k):k}function Qe(t,o){let u=E=>{let N=(E.unit<0n?-E.unit:E.unit).toString().padStart(E.scale+1,"0"),V=N.slice(0,N.length-E.scale),U=N.slice(N.length-E.scale),B=V.padStart(Math.ceil(V.length/4)*4,"0").match(/.{4}/g)??[],W=U.padEnd(Math.ceil(U.length/4)*4,"0").match(/.{4}/g)??[],n=[...B.map((c,l)=>[B.length-1-l,Number(c)]),...W.map((c,l)=>[-1-l,Number(c)])].find(([,c])=>c!==0);return n?[n[0],n[1]]:[0,0]},[d,p]=u(t),[f,w]=u(o),m=d-f-(p<=w?1:0),O=Math.min(Math.max(16-m*4,t.scale,o.scale,0),1e3),k=t.unit*10n**BigInt(O+o.scale),_=o.unit*10n**BigInt(t.scale),F=k/_,C=k%_;2n*(C<0n?-C:C)>=(_<0n?-_:_)&&(F+=k<0n!=_<0n?-1n:1n);let M=F<0n,T=(M?-F:F).toString().padStart(O+1,"0");return`${M?"-":""}${O===0?T:`${T.slice(0,-O)}.${T.slice(-O)}`}`}var x=t=>structuredClone(t);function he(t,o,u){if(Ie(u))throw new Error(`${t}(${o}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(u===null||typeof u!="object"))for(let[d,p]of Object.entries(u))if(d==="OR"||d==="AND")for(let f of Array.isArray(p)?p:[])he(t,o,f);else d==="NOT"&&he(t,o,p)}function K(t,o,u){return Te(new Ae({fields:[{field:o,message:u}]},`${t}: ${o} ${u}`))}function be(t,o,u="where"){for(let[d,p]of Object.entries(o))if(d==="OR"||d==="AND"){let f=p;if(d==="AND"&&f.length===0)throw K(t,`${u}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((w,m)=>{if(Object.keys(w).length===0)throw K(t,`${u}.${d}[${m}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");be(t,w,`${u}.${d}[${m}]`)})}else if(d==="NOT"){if(Array.isArray(p))throw K(t,`${u}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(p).length===0)throw K(t,`${u}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");be(t,p,`${u}.NOT`)}else if(d==="has"&&Object.keys(p??{}).length===0)throw K(t,`${u}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function Y(t,o){if(Object.keys(o).length===0)throw K(t,"where",`holds no condition, so ${t} would reach EVERY row of the table. Name a condition.`)}function Re(t){let o=!1;for(let u of t){if(u===!1)return!1;u===null&&(o=!0)}return o?null:!0}function We(t){let o=!1;for(let u of t){if(u===!0)return!0;u===null&&(o=!0)}return o?null:!1}var P=t=>t==null;function z(t,o,u,d){return Re(Object.entries(d).map(([p,f])=>{if(p==="OR")return We(f.map(w=>z(t,o,u,w)));if(p==="AND")return Re(f.map(w=>z(t,o,u,w)));if(p==="NOT"){let w=z(t,o,u,f);return w===null?null:!w}if(p==="has")throw new Error(`${t}(${o}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Ge(t,o,u,p,f)}))}var Be=["neq","gt","gte","lt","lte"];function te(t,o){return P(t)||P(o)?null:q(t,o)}function Ge(t,o,u,d,p){let f=u[d];return p===null?P(f):ee(p)?te(f,u[p.$col]):ne(p)?te(f,oe(J(p)?.minus)):typeof p=="object"&&!Array.isArray(p)&&!(p instanceof Date)?Re(Object.entries(p).map(([w,m])=>{if(ne(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take now()`);return re(w,f,oe(J(m)?.minus))}if(le(m))throw new Error(`${t}(${o}): where.${d}.${w} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(ee(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take col()`);return re(w,f,u[m.$col])}switch(w){case"in":{if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.in is a list`);return We(m.map(O=>te(f,O)))}case"neq":return m===null?!P(f):re(w,f,m);case"gt":case"gte":case"lt":case"lte":return re(w,f,m);case"isNull":if(typeof m!="boolean")throw new Error(`${t}(${o}): where.${d}.isNull is true or false`);return m?P(f):!P(f);case"overlaps":if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${t}(${o}): where.${d}: "overlaps" is an array column's operator`);return P(f)?null:m.some(O=>f.some(k=>q(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(w==="contains"&&Array.isArray(m))return P(f)?null:Array.isArray(f)&&m.every(O=>f.some(k=>q(O,k)));if(typeof m!="string")throw new Error(`${t}(${o}): where.${d}.${w} is text`);return P(f)?null:typeof f!="string"?!1:w==="contains"?f.includes(m):w==="icontains"?f.toLowerCase().includes(m.toLowerCase()):w==="startsWith"?f.startsWith(m):f.endsWith(m)}default:throw new Error(`${t}(${o}): where.${d} has no operator "${w}"`)}})):te(f,p)}function re(t,o,u){if(P(o)||P(u))return null;if(t==="neq")return!q(o,u);let d=ye(o,u);return d===null?!1:t==="gt"?d>0:t==="gte"?d>=0:t==="lt"?d<0:d<=0}function Je(t={}){let o=new Map,u=new Map,d=new Map,p=new Map,f=new Map,w=[],m=t.access===void 0?void 0:_e(t.access,{rows:n=>o.get(n)??[],deleted:n=>f.get(n)??[]});m?.signedInAs(t.user);let O=n=>{let c=o.get(n);return c||o.set(n,c=[]),c},k=(n,c,l)=>{let e=n.get(c);e?e.push(l):n.set(c,[l])},_=n=>n.id===void 0?{id:He(),...n}:{...n},F=()=>{let n={store:new Map([...o].map(([l,e])=>[l,e.map(x)])),inserted:pe(u),updated:pe(d),deleted:new Map([...p].map(([l,e])=>[l,[...e]])),removed:pe(f)},c=m?.snapshot();return()=>{o=n.store,u=n.inserted,d=n.updated,p=n.deleted,f=n.removed,c?.()}};function C(n,c,l){let e={};for(let[r,i]of Object.entries(l)){let s=J(i);if(s!==null&&s.fn==="now")e[r]=oe(s.minus);else{if(s!==null)throw new Error(`${n}(${c}): "${r}" was given ${s.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);e[r]=i}}return H(n,c,Object.keys(e),e),fe(n,c,Object.keys(e),e),e}function M(n,c,l,e){H(n,c,Object.keys(e),e);let r={};for(let[i,s]of Object.entries(e)){let a=J(s);a!==null&&a.fn==="now"?r[i]=oe(a.minus):a!==null?r[i]=ge(l[i],a.by,a.fn==="inc"?1:-1):r[i]=s}return fe(n,c,Object.keys(r),r),r}function T(n,c,l){let e=_(C(n,c,l));return O(c).push(e),k(u,c,x(e)),x(e)}function E(n,c,l){return Ne(n,c,l),he(n,c,l),l!==void 0&&be(n,l),(o.get(c)??[]).filter(e=>l===void 0||z(n,c,e,l)===!0)}let N=n=>async(c,...l)=>{if(!m?.nested(c))return n(c,...l);let e=(o.get(c)??[]).map(x),r=F(),i=await n(c,...l),s=m.misplaced(c,e,o.get(c)??[]);if(s)throw r(),Object.assign(new Error(s.message),{code:s.code});return i},V={diagnostics:()=>null,async query(n,c=[]){return w.push({sql:n,params:c}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,c){let l=(o.get(n)??[]).find(e=>e.id===c);return l?x(l):null},async findMany(n,c,l){let{limit:e,offset:r}=l??{};if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(e)})`);if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(r)})`);if(e===void 0)throw new Error(`findMany(${n}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(l?.with!==void 0&&Object.keys(l.with).length>0)throw new Error(`findMany(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let i=E("findMany",n,c),s=l?.orderBy===void 0?[]:Array.isArray(l.orderBy)?l.orderBy:[l.orderBy];s.length>0&&(i=[...i].sort((h,b)=>{for(let y of s){let j=y.direction==="desc"?-1:1,$=h[y.column],R=b[y.column],I=$==null,S=R==null;if(I||S){if(I&&S)continue;let D=y.nulls===void 0?j===-1:y.nulls==="first";return(I?1:-1)*(D?-1:1)}let A=ye($,R)??(String($)<String(R)?-1:String($)>String(R)?1:0);if(A!==0)return A*j}return 0}));let a=e===void 0?i:i.slice(r??0,(r??0)+e),g=l?.select;return a.map(h=>g===void 0||g.length===0?x(h):Object.fromEntries(g.map(b=>[b,structuredClone(h[b])])))},async count(n,c={}){return E("count",n,c).length},async aggregate(n,c){let l=E("aggregate",n,c.where),e=c.groupBy??[],r=s=>{let a={},g=h=>s.map(b=>b[h]).filter(b=>b!=null);for(let h of c.sum??[]){let b=g(h);(a.sum??={})[h]=b.length===0?null:String(b.reduce((y,j)=>ge(y,j,1),"0"))}for(let h of c.avg??[]){let b=g(h),y=b.some(j=>typeof j=="number"&&!Number.isInteger(j));(a.avg??={})[h]=b.length===0?null:y?b.reduce((j,$)=>j+$,0)/b.length:Qe(v(b.reduce((j,$)=>ge(j,$,1),"0")),{unit:BigInt(b.length),scale:0})}for(let[h,b]of[["min",-1],["max",1]])for(let y of c[h]??[]){let j=g(y);(a[h]??={})[y]=j.length===0?null:j.reduce(($,R)=>(ye(R,$)??0)*b>0?R:$)}return c.count===!0?a.count=s.length:c.count!==void 0&&c.count!==!1&&(a.count=Object.fromEntries(Object.entries(c.count).map(([h,b])=>[h,s.filter(y=>z("aggregate",n,y,b)===!0).length]))),a};if(e.length===0)return r(l);let i=new Map;for(let s of l){let a=JSON.stringify(e.map(g=>s[g]));i.set(a,[...i.get(a)??[],s])}return[...i.values()].map(s=>({...r(s),...Object.fromEntries(e.map(a=>[a,s[0][a]]))}))},insert:N(async(n,c)=>T("insert",n,c)),insertMany:N(async(n,c,l)=>{if(Se(l),l?.onConflict?.length||l?.action!==void 0)throw new Error(`insertMany(${n}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(c.length===0)return l?.returning===!1?0:[];let e=Object.keys(c[0]);c.forEach((i,s)=>{let a=e.filter(h=>!(h in i)),g=Object.keys(i).filter(h=>!e.includes(h));if(a.length>0||g.length>0)throw new Error(`insertMany(${n}): row ${s} has not the first row's columns${a.length?` (missing ${a.join(", ")})`:""}${g.length?` (extra ${g.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let r=c.map(i=>T("insertMany",n,i));return l?.returning===!1?r.length:r}),put:N(async(n,c,l)=>{if(!l?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let e=C("put",n,c),r=O(n).find(i=>l.onConflict.every(s=>q(i[s],e[s])));if(!r)return T("put",n,c);for(let[i,s]of Object.entries(e))l.onConflict.includes(i)||(r[i]=s);return k(d,n,x(r)),x(r)}),update:N(async(n,c,l)=>{let e=o.get(n)??[],r=e.findIndex(i=>i.id===c);return r<0?(H("update",n,Object.keys(l),l),null):(e[r]={...e[r],...M("update",n,e[r],l)},k(d,n,x(e[r])),x(e[r]))}),updateMany:N(async(n,c,l,e)=>{Y("updateMany",c);let r=E("updateMany",n,c),i=O(n),s=[];for(let a of r){let g=i.indexOf(a);i[g]={...a,...M("updateMany",n,a,l)},k(d,n,x(i[g])),s.push(x(i[g]))}return r.length===0&&H("updateMany",n,Object.keys(l),l),e?.returning===!1?s.length:s}),async delete(n,c){let l=o.get(n)??[],e=l.findIndex(i=>i.id===c);if(e<0)return;let[r]=l.splice(e,1);k(p,n,c),k(f,n,r)},async deleteMany(n,c){Y("deleteMany",c);let l=E("deleteMany",n,c);o.set(n,(o.get(n)??[]).filter(e=>!l.includes(e)));for(let e of l)k(p,n,String(e.id)),k(f,n,e);return l.length},claim:N(async(n,c,l={})=>{let e=Object.keys(c);if(e.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);H("claim",n,e,c);let r=(o.get(n)??[]).find(i=>e.every(s=>q(i[s],c[s])));return r?{inserted:!1,row:x(r)}:{inserted:!0,row:T("claim",n,{...c,...l})}}),async lockRows(n,c){if(c.length===0)return;let l=o.get(n)??[],e=[...new Set(c)].filter(r=>!l.some(i=>i.id===r));if(e.length>0&&l.length>0)throw new Error(`lockRows(${n}): no row with id ${e.join(", ")}`)},async lockRowsWhere(n,c,l){let e=l?.mode??"update";if(!["update","share","noKeyUpdate"].includes(e))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(e)}")`);Y("lockRowsWhere",c),E("lockRowsWhere",n,c)},async advisoryXactLock(){}};function U(n){let c=F(),l=[];try{for(let e of n.ops){let r=m?.nested(e.table)?(o.get(e.table)??[]).map(x):null,i=B(e,l),s=r===null?null:m?.misplaced(e.table,r,o.get(e.table)??[])??null;if(s)throw Object.assign(new Error(s.message),{code:s.code});l.push(i);let a=Ye(e.guard,i.rows.length);if(a)throw a}}catch(e){throw c(),e}return{results:l}}function B(n,c){let l=r=>Object.fromEntries(Object.entries(r??{}).map(([i,s])=>[i,qe(s,c)])),e=`transaction plan ${n.op}`;switch(n.op){case"insert":return we(T(e,n.table,l(n.values)));case"insertMany":{let r=(n.rows??[]).map(a=>l(a)),i=n.onConflict??[];if(n.action!==void 0&&i.length===0)throw new Error(`${e}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let s=[];for(let a of r){let g=i.length>0?O(n.table).find(h=>i.every(b=>q(h[b],a[b]))):void 0;if(!(g&&n.action==="ignore")){if(g&&n.action==="update"){Object.assign(g,M(e,n.table,g,Object.fromEntries(Object.entries(a).filter(([h])=>!i.includes(h))))),k(d,n.table,x(g)),s.push(x(g));continue}s.push(T(e,n.table,a))}}return{rows:s,rows_affected:s.length}}case"upsert":{let r=l(n.values),i=n.onConflict??[];if(Object.keys(r).length===0||i.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let s=O(n.table).find(a=>i.every(g=>q(a[g],r[g])));return s?(Object.assign(s,M(e,n.table,s,Object.fromEntries(Object.entries(r).filter(([a])=>!i.includes(a))))),k(d,n.table,x(s)),we(x(s))):we(T(e,n.table,r))}case"update":{let r=l(n.set);if(Object.keys(r).length===0)throw new Error(`update ${n.table}: nothing to set`);let i=me(n.where,c);Y(e,i);let s=O(n.table),a=[];for(let g of E(e,n.table,i)){let h=s.indexOf(g);s[h]={...g,...M(e,n.table,g,r)},k(d,n.table,x(s[h])),a.push(x(s[h]))}return{rows:a,rows_affected:a.length}}case"delete":{let r=me(n.where,c);Y(e,r);let i=E(e,n.table,r);o.set(n.table,O(n.table).filter(s=>!i.includes(s)));for(let s of i)k(p,n.table,String(s.id)),k(f,n.table,s);return{rows:i.map(x),rows_affected:i.length}}case"select":{let r=E(e,n.table,me(n.where,c));return n.limit!==void 0&&(r=r.slice(0,n.limit)),{rows:r.map(x),rows_affected:r.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let W={...V,async txPlan(n){return U(n)},async attempt(n){let c=F();try{return await n(V)}catch(l){throw c(),l}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...W,asService:()=>W,inserted:n=>(u.get(n)??[]).map(x),updated:n=>(d.get(n)??[]).map(x),deleted:n=>[...p.get(n)??[]],seed(n,c){o.set(n,c.map(x))},queries:w,...m===void 0?{}:{access:m}}}function pe(t){return new Map([...t].map(([o,u])=>[o,u.map(x)]))}function we(t){return{rows:[t],rows_affected:1}}function qe(t,o){if(!ue(t))return t;let u=o[t.$ref.op]?.rows[0];if(!u)throw Object.assign(new Error(`transaction plan: operation ${t.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return u[t.$ref.field]}function me(t,o){let u=d=>{if(ue(d)){let p=qe(d,o);if(p==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${d.$ref.op}'s "${d.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return p}return Array.isArray(d)?d.map(u):d!==null&&typeof d=="object"&&!ee(d)&&!le(d)&&!ne(d)&&!(d instanceof Date)?Object.fromEntries(Object.entries(d).map(([p,f])=>[p,u(f)])):d};return u(t??{})}function Ye(t,o){return t?(t.kind==="one"?o===1:t.kind==="none"?o===0:t.kind==="atLeast"?o>=t.n:o<=t.n)?null:Object.assign(new Error(`transaction expectation failed: ${t.kind} (${o} row(s))`),{error_code:"tx_guard_failed",slot:t.slot}):null}export{Je as createFakeClient,Ue as typedDatabase};
|
|
1
|
+
/*! palgres 0.82.1 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{D as J,G as Se,H as Ue,a as ae,b as Ee,d as Me,l as ee,m as Ie,n as ue,r as le,s as ne,t as fe,u as Ne,w as H}from"./chunks/IUXPTGUJ.js";import{n as Te,p as Ae}from"./chunks/YXBLVWLV.js";import{G as Q,H as G,I as Oe,J as ce,K as xe,q as $e,u as ke}from"./chunks/5P4M3O6D.js";import{randomUUID as He}from"node:crypto";var Pe=/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,De="access: its time passed",Ce="user";function Fe(t){let o=t.filter(u=>u!=null);return o.length===0?"text":o.every(u=>typeof u=="boolean")?"bool":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isInteger(u))?"int":o.every(u=>typeof u=="bigint"||typeof u=="number"&&Number.isFinite(u))?"numeric":o.every(u=>typeof u=="string"&&Pe.test(u))?"uuid":"text"}function Le(t,o){return o==null?null:t==="bool"||t==="int"||t==="numeric"||typeof o=="string"?o:String(o)}var de=t=>t.schema==="public"?t.name:`${t.schema}.${t.name}`;function _e(t,o){let u=ke($e(t)),d=Ee(t,"memory"),p,f=[],w=[],m=0,O=new Map,k=[...u.types.values()].filter(e=>e.table),_=e=>{let r=u.types.get(e),i=new Set;if(!r?.table)return[];i.add(r.table.key??"id");let s=a=>{let g=a;g.parts?g.parts.forEach(s):g.part?s(g.part):g.column&&i.add(g.column)};for(let a of r.relations.values())a.kind!=="stored"&&(a.kind==="column"&&i.add(a.column),a.where&&s(a.where));return[...i]},F=()=>{let e=new Map;for(let r of k){let i=r.table,s=o.rows(de(i)),a=i.key??"id",g={};for(let b of _(r.name))g[b]=Fe(s.map(y=>y[b]));let h={key:a,columns:g};e.set(r.name,{shape:h,rows:s.map(b=>Object.fromEntries(Object.entries(g).map(([y,j])=>[y,Le(j,b[y])])))})}return{tables:e,relationships:f,now:Date.now()}},C=(e,r,i)=>{let s=e.tables.get(r);if(!s)return i;let a=s.shape.columns[s.shape.key],g=Q(a,i);return g===null?null:s.rows.some(b=>{let y=b[s.shape.key];return y!==null&&Q(a,String(y))===g})?g:void 0},M=()=>{for(let r of k){let i=r.table,s=de(i),a=i.key??"id",g=o.deleted(s),h=Math.min(O.get(s)??0,g.length),b=j=>Pe.test(j)?j.toLowerCase():j,y=new Set(g.slice(h).map(j=>j[a]).filter(j=>j!=null).map(j=>b(String(j))));O.set(s,g.length),y.size>0&&V(r.name,j=>y.has(b(j)),"access: row deleted")}let e=F();for(let r of k)V(r.name,i=>C(e,r.name,i)===void 0,"access: row deleted");return F()},T=e=>e.expiresAt!==void 0&&e.expiresAt!==null&&e.expiresAt<=Date.now(),E=(e,r)=>T(e)?W("expire",e,De,e.expiresAt):W("revoke",e,r),N=(e,r)=>{let i=[],s=0;for(let a of f)e(a)?(E(a,r),s++):i.push(a);return f=i,s},V=(e,r,i)=>{N(s=>s.objectType===e&&r(s.objectId)||s.subjectType===e&&r(s.subjectId),i)},U=e=>new Date(e).toISOString().replace("Z","000Z"),B=e=>e==null?null:U(e),W=(e,r,i,s)=>{w.push({seq:++m,at:U(s??Date.now()),action:e,object:{type:r.objectType,id:r.objectId},relation:r.relation,subject:{type:r.subjectType,id:r.subjectId},by:i,until:B(r.expiresAt)})},X=(e,r)=>(e.object_type===void 0||e.object_type===r.objectType)&&(e.object_id===void 0||e.object_id===r.objectId)&&(e.relation===void 0||e.relation===r.relation)&&(e.subject_type===void 0||e.subject_type===r.subjectType)&&(e.subject_id===void 0||e.subject_id===r.subjectId),n=(e,r)=>{for(let i of["objectType","objectId","relation","subjectType","subjectId"])if(e[i]!==r[i])return e[i]<r[i]?-1:1;return 0},c={caller:()=>p,check(e,r,i,s){let a=M(),g=C(a,i,s);return g==null?!1:G(u,a).check(e,i,g,r)},objects:(e,r,i)=>G(u,M()).objects(e,i,r),subjects(e,r,i){let s=M(),a=C(s,r,i);return a==null?[]:G(u,s).subjects(r,a,e)},open(e,r,i){let s=M(),a=C(s,r,i);return a==null?null:G(u,s).open(r,a,e)},change(e,r,i,s,a,g){let h=M(),b=(R,I,S)=>{if(I===Ce)return S;let A=C(h,I,S);if(A==null)throw new ae("no_object",`Database.$access: there is no ${I} ${JSON.stringify(S)} (${R}) \u2014 a relationship is given on an object that exists`);return A};if(e==="revoke"){let R=(L,je)=>{let ie=L===Ce?void 0:h.tables.get(L);return ie?Q(ie.shape.columns[ie.shape.key],je):je},I=R(r.type,r.id),S=R(s.type,s.id);if(I===null||S===null)return!1;let A={objectType:r.type,objectId:I,relation:i,subjectType:s.type,subjectId:S},D=f.find(L=>n(L,A)===0);if(!D)return!1;let Ve=!T(D);return N(L=>L===D,a??p??null),Ve}let y={objectType:r.type,objectId:b("the object",r.type,r.id),relation:i,subjectType:s.type,subjectId:b("the subject",s.type,s.id),expiresAt:g??null},j=u.trees.find(R=>R.type===y.objectType&&R.relation===y.relation&&u.types.get(R.type)?.relations.get(R.relation)?.kind==="stored");if(j&&y.subjectType===y.objectType){let R=Date.now(),I=f.filter(A=>A.objectType===j.type&&A.relation===j.relation&&A.subjectType===j.type&&!T(A)),S=xe(j,I,y.objectId,y.subjectId,R)??ce(j.type,j.depth,y.objectId,y.subjectId,A=>I.filter(D=>D.objectId===A).map(D=>D.subjectId),A=>I.filter(D=>D.subjectId===A).map(D=>D.objectId));if(S)throw new ae(Me[S.code],`Database.$access: ${S.message}`)}N(R=>R.objectType===y.objectType&&R.objectId===y.objectId&&T(R),null);let $=f.find(R=>n(R,y)===0);return $?(($.expiresAt??null)!==(y.expiresAt??null)&&($.expiresAt=y.expiresAt,W("grant",y,a??p??null)),!1):(f.push({...y,since:U(Date.now())}),W("grant",y,a??p??null),!0)},sweep(e){M();let r=f.filter(T).sort((i,s)=>i.expiresAt-s.expiresAt).slice(0,e);return N(i=>r.includes(i),null)},relationships(e,r){return M(),f.filter(i=>!T(i)&&X(e,i)).sort(n).slice(0,r).map(i=>({object:{type:i.objectType,id:i.objectId},relation:i.relation,subject:{type:i.subjectType,id:i.subjectId},since:i.since,until:B(i.expiresAt)}))},history(e,r){M();let i=f.filter(T).map(s=>({seq:Number.POSITIVE_INFINITY,at:B(s.expiresAt),action:"expire",object:{type:s.objectType,id:s.objectId},relation:s.relation,subject:{type:s.subjectType,id:s.subjectId},by:De,until:B(s.expiresAt)}));return[...w,...i].filter(s=>X(e,{objectType:s.object.type,objectId:s.object.id,relation:s.relation,subjectType:s.subject.type,subjectId:s.subject.id})).sort((s,a)=>s.at!==a.at?s.at<a.at?1:-1:a.seq===s.seq?0:a.seq>s.seq?1:-1).slice(0,r).map(({seq:s,...a})=>({...a,object:{...a.object},subject:{...a.subject}}))}},l=e=>{let r=k.find(i=>de(i.table)===e);return r?u.trees.flatMap(i=>{let s=i.type===r.name?r.relations.get(i.relation):void 0;return s?.kind==="column"?[{type:r.name,key:r.table?.key??"id",column:s.column,depth:i.depth}]:[]}):[]};return{names:d,via:c,nested:e=>l(e).length>0,misplaced(e,r,i){for(let s of l(e)){let a=Fe(i.map($=>$[s.key])),g=$=>$==null?null:Q(a,String($)),h=new Map;for(let $ of i){let R=g($[s.key]);R!==null&&h.set(R,g($[s.column]))}let b=new Map;for(let $ of r){let R=g($[s.key]);R!==null&&b.set(R,g($[s.column]))}let y=$=>[...h].filter(([,R])=>R===$).map(([R])=>R),j=$=>$!==null&&h.has($)?$:null;for(let[$,R]of h){if(b.has($)&&b.get($)===R||R===null&&y($).length===0)continue;if(R!==null&&!h.has(R))return Oe(s.type,$,R);let I=ce(s.type,s.depth,$,j(R),S=>[j(h.get(S)??null)].filter(A=>A!==null),y);if(I)return I}}return null},signedInAs(e){p=e},snapshot(){let e={relationships:f.map(r=>({...r})),history:w.map(r=>({...r})),written:m,seen:new Map(O),user:p};return()=>{f=e.relationships,w=e.history,m=e.written,O=e.seen,p=e.user}}}}var Ke=/^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?)?(Z|[+-]\d{2}(:?\d{2})?)?$/,ve=/^([+-]?)(\d*)(?:\.(\d*))?$/;function Z(t){if(t instanceof Date)return t.getTime();if(typeof t=="string"&&Ke.test(t)){let o=Date.parse(t);return Number.isNaN(o)?null:o}return null}function v(t){if(typeof t=="number")return Number.isFinite(t)?v(String(t)):null;if(typeof t!="string"||/e/i.test(t))return null;let o=ve.exec(t.trim());if(o===null||o[2]===""&&(o[3]??"")==="")return null;let u=o[3]??"";return{unit:BigInt(`${o[1]==="-"?"-":""}${o[2]===""?"0":o[2]}${u}`),scale:u.length}}function se(t,o){return t.unit*10n**BigInt(o-t.scale)}function ye(t,o){if(t==null||o===null||o===void 0)return null;let u=Z(t),d=Z(o);if(u!==null&&d!==null)return Math.sign(u-d);let p=v(t),f=v(o);if(p!==null&&f!==null){let w=Math.max(p.scale,f.scale),m=se(p,w)-se(f,w);return m===0n?0:m<0n?-1:1}return typeof t==typeof o&&(typeof t=="string"||typeof t=="boolean"||typeof t=="number")?t<o?-1:t>o?1:0:null}function q(t,o){return t==null||o===null||o===void 0?!1:t instanceof Date||o instanceof Date?Z(t)!==null&&Z(t)===Z(o):Array.isArray(t)&&Array.isArray(o)?t.length===o.length&&t.every((u,d)=>q(u,o[d])):t===o}function oe(t){let o=((t?.days??0)*86400+(t?.hours??0)*3600+(t?.minutes??0)*60+(t?.seconds??0))*1e3;return new Date(Date.now()-o).toISOString()}function ge(t,o,u){if(t==null)return null;if(typeof t=="number"&&typeof o=="number")return t+u*o;let d=v(t),p=v(o);if(d===null||p===null)throw new Error(`increment()/decrement() on a value that is not a number (${JSON.stringify(t)}): Postgres refuses it ("operator does not exist")`);let f=Math.max(d.scale,p.scale),w=se(d,f)+BigInt(u)*se(p,f);if(f===0)return typeof t=="number"?Number(w):w.toString();let m=w<0n,O=(m?-w:w).toString().padStart(f+1,"0"),k=`${m?"-":""}${O.slice(0,-f)}.${O.slice(-f)}`;return typeof t=="number"?Number(k):k}function Qe(t,o){let u=E=>{let N=(E.unit<0n?-E.unit:E.unit).toString().padStart(E.scale+1,"0"),V=N.slice(0,N.length-E.scale),U=N.slice(N.length-E.scale),B=V.padStart(Math.ceil(V.length/4)*4,"0").match(/.{4}/g)??[],W=U.padEnd(Math.ceil(U.length/4)*4,"0").match(/.{4}/g)??[],n=[...B.map((c,l)=>[B.length-1-l,Number(c)]),...W.map((c,l)=>[-1-l,Number(c)])].find(([,c])=>c!==0);return n?[n[0],n[1]]:[0,0]},[d,p]=u(t),[f,w]=u(o),m=d-f-(p<=w?1:0),O=Math.min(Math.max(16-m*4,t.scale,o.scale,0),1e3),k=t.unit*10n**BigInt(O+o.scale),_=o.unit*10n**BigInt(t.scale),F=k/_,C=k%_;2n*(C<0n?-C:C)>=(_<0n?-_:_)&&(F+=k<0n!=_<0n?-1n:1n);let M=F<0n,T=(M?-F:F).toString().padStart(O+1,"0");return`${M?"-":""}${O===0?T:`${T.slice(0,-O)}.${T.slice(-O)}`}`}var x=t=>structuredClone(t);function he(t,o,u){if(Ie(u))throw new Error(`${t}(${o}): the fake database runs no SQL, so a sqlFragment cannot be evaluated \u2014 write the filter in the filter language (gt, gte, lt, lte, neq, in, contains, isNull, OR, AND, NOT), or test this against Postgres`);if(!(u===null||typeof u!="object"))for(let[d,p]of Object.entries(u))if(d==="OR"||d==="AND")for(let f of Array.isArray(p)?p:[])he(t,o,f);else d==="NOT"&&he(t,o,p)}function K(t,o,u){return Te(new Ae({fields:[{field:o,message:u}]},`${t}: ${o} ${u}`))}function be(t,o,u="where"){for(let[d,p]of Object.entries(o))if(d==="OR"||d==="AND"){let f=p;if(d==="AND"&&f.length===0)throw K(t,`${u}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");f.forEach((w,m)=>{if(Object.keys(w).length===0)throw K(t,`${u}.${d}[${m}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");be(t,w,`${u}.${d}[${m}]`)})}else if(d==="NOT"){if(Array.isArray(p))throw K(t,`${u}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");if(Object.keys(p).length===0)throw K(t,`${u}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");be(t,p,`${u}.NOT`)}else if(d==="has"&&Object.keys(p??{}).length===0)throw K(t,`${u}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.")}function Y(t,o){if(Object.keys(o).length===0)throw K(t,"where",`holds no condition, so ${t} would reach EVERY row of the table. Name a condition.`)}function Re(t){let o=!1;for(let u of t){if(u===!1)return!1;u===null&&(o=!0)}return o?null:!0}function We(t){let o=!1;for(let u of t){if(u===!0)return!0;u===null&&(o=!0)}return o?null:!1}var P=t=>t==null;function z(t,o,u,d){return Re(Object.entries(d).map(([p,f])=>{if(p==="OR")return We(f.map(w=>z(t,o,u,w)));if(p==="AND")return Re(f.map(w=>z(t,o,u,w)));if(p==="NOT"){let w=z(t,o,u,f);return w===null?null:!w}if(p==="has")throw new Error(`${t}(${o}): the fake database has no relations, so a \`has\` filter cannot be decided for a row \u2014 read the related table first and filter by its ids ({ id: { in: [\u2026] } }), or test this against Postgres`);return Ge(t,o,u,p,f)}))}var Be=["neq","gt","gte","lt","lte"];function te(t,o){return P(t)||P(o)?null:q(t,o)}function Ge(t,o,u,d,p){let f=u[d];return p===null?P(f):ee(p)?te(f,u[p.$col]):ne(p)?te(f,oe(J(p)?.minus)):typeof p=="object"&&!Array.isArray(p)&&!(p instanceof Date)?Re(Object.entries(p).map(([w,m])=>{if(ne(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take now()`);return re(w,f,oe(J(m)?.minus))}if(le(m))throw new Error(`${t}(${o}): where.${d}.${w} was given increment()/decrement() \u2014 a write, not a value to compare with`);if(ee(m)){if(!Be.includes(w))throw new Error(`${t}(${o}): where.${d}.${w} cannot take col()`);return re(w,f,u[m.$col])}switch(w){case"in":{if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.in is a list`);return We(m.map(O=>te(f,O)))}case"neq":return m===null?!P(f):re(w,f,m);case"gt":case"gte":case"lt":case"lte":return re(w,f,m);case"isNull":if(typeof m!="boolean")throw new Error(`${t}(${o}): where.${d}.isNull is true or false`);return m?P(f):!P(f);case"overlaps":if(!Array.isArray(m))throw new Error(`${t}(${o}): where.${d}.overlaps is a list`);if(f!=null&&!Array.isArray(f))throw new Error(`${t}(${o}): where.${d}: "overlaps" is an array column's operator`);return P(f)?null:m.some(O=>f.some(k=>q(O,k)));case"contains":case"icontains":case"startsWith":case"endsWith":{if(w==="contains"&&Array.isArray(m))return P(f)?null:Array.isArray(f)&&m.every(O=>f.some(k=>q(O,k)));if(typeof m!="string")throw new Error(`${t}(${o}): where.${d}.${w} is text`);return P(f)?null:typeof f!="string"?!1:w==="contains"?f.includes(m):w==="icontains"?f.toLowerCase().includes(m.toLowerCase()):w==="startsWith"?f.startsWith(m):f.endsWith(m)}default:throw new Error(`${t}(${o}): where.${d} has no operator "${w}"`)}})):te(f,p)}function re(t,o,u){if(P(o)||P(u))return null;if(t==="neq")return!q(o,u);let d=ye(o,u);return d===null?!1:t==="gt"?d>0:t==="gte"?d>=0:t==="lt"?d<0:d<=0}function Je(t={}){let o=new Map,u=new Map,d=new Map,p=new Map,f=new Map,w=[],m=t.access===void 0?void 0:_e(t.access,{rows:n=>o.get(n)??[],deleted:n=>f.get(n)??[]});m?.signedInAs(t.user);let O=n=>{let c=o.get(n);return c||o.set(n,c=[]),c},k=(n,c,l)=>{let e=n.get(c);e?e.push(l):n.set(c,[l])},_=n=>n.id===void 0?{id:He(),...n}:{...n},F=()=>{let n={store:new Map([...o].map(([l,e])=>[l,e.map(x)])),inserted:pe(u),updated:pe(d),deleted:new Map([...p].map(([l,e])=>[l,[...e]])),removed:pe(f)},c=m?.snapshot();return()=>{o=n.store,u=n.inserted,d=n.updated,p=n.deleted,f=n.removed,c?.()}};function C(n,c,l){let e={};for(let[r,i]of Object.entries(l)){let s=J(i);if(s!==null&&s.fn==="now")e[r]=oe(s.minus);else{if(s!==null)throw new Error(`${n}(${c}): "${r}" was given ${s.fn==="inc"?"increment()":"decrement()"} \u2014 the row does not exist yet, so there is no current value to change`);e[r]=i}}return H(n,c,Object.keys(e),e),fe(n,c,Object.keys(e),e),e}function M(n,c,l,e){H(n,c,Object.keys(e),e);let r={};for(let[i,s]of Object.entries(e)){let a=J(s);a!==null&&a.fn==="now"?r[i]=oe(a.minus):a!==null?r[i]=ge(l[i],a.by,a.fn==="inc"?1:-1):r[i]=s}return fe(n,c,Object.keys(r),r),r}function T(n,c,l){let e=_(C(n,c,l));return O(c).push(e),k(u,c,x(e)),x(e)}function E(n,c,l){return Ne(n,c,l),he(n,c,l),l!==void 0&&be(n,l),(o.get(c)??[]).filter(e=>l===void 0||z(n,c,e,l)===!0)}let N=n=>async(c,...l)=>{if(!m?.nested(c))return n(c,...l);let e=(o.get(c)??[]).map(x),r=F(),i=await n(c,...l),s=m.misplaced(c,e,o.get(c)??[]);if(s)throw r(),Object.assign(new Error(s.message),{code:s.code});return i},V={diagnostics:()=>null,async query(n,c=[]){return w.push({sql:n,params:c}),[]},async findUnique(){throw new Error("the fake database knows no table's declared unique keys \u2014 find the row with findMany, or test this against Postgres")},async page(){throw new Error("the fake database cannot reproduce Postgres' cursor ordering, collation or row-level security \u2014 test pagination against Postgres")},async search(n){throw new Error(`search(${n}): the fake database has neither embeddings nor full text \u2014 test search against Postgres`)},async findById(n,c){let l=(o.get(n)??[]).find(e=>e.id===c);return l?x(l):null},async findMany(n,c,l){let{limit:e,offset:r}=l??{};if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new Error(`findMany(${n}): limit is a whole number, 0 or more (got ${String(e)})`);if(r!==void 0){if(!Number.isInteger(r)||r<0)throw new Error(`findMany(${n}): offset is a whole number, 0 or more (got ${String(r)})`);if(e===void 0)throw new Error(`findMany(${n}): offset comes with limit \u2014 an offset into an unbounded result is not a page`)}if(l?.with!==void 0&&Object.keys(l.with).length>0)throw new Error(`findMany(${n}): the fake database has no relations, so \`with\` cannot be read \u2014 seed and query the related table on its own, or test this against Postgres`);let i=E("findMany",n,c),s=l?.orderBy===void 0?[]:Array.isArray(l.orderBy)?l.orderBy:[l.orderBy];s.length>0&&(i=[...i].sort((h,b)=>{for(let y of s){let j=y.direction==="desc"?-1:1,$=h[y.column],R=b[y.column],I=$==null,S=R==null;if(I||S){if(I&&S)continue;let D=y.nulls===void 0?j===-1:y.nulls==="first";return(I?1:-1)*(D?-1:1)}let A=ye($,R)??(String($)<String(R)?-1:String($)>String(R)?1:0);if(A!==0)return A*j}return 0}));let a=e===void 0?i:i.slice(r??0,(r??0)+e),g=l?.select;return a.map(h=>g===void 0||g.length===0?x(h):Object.fromEntries(g.map(b=>[b,structuredClone(h[b])])))},async count(n,c={}){return E("count",n,c).length},async aggregate(n,c){let l=E("aggregate",n,c.where),e=c.groupBy??[],r=s=>{let a={},g=h=>s.map(b=>b[h]).filter(b=>b!=null);for(let h of c.sum??[]){let b=g(h);(a.sum??={})[h]=b.length===0?null:String(b.reduce((y,j)=>ge(y,j,1),"0"))}for(let h of c.avg??[]){let b=g(h),y=b.some(j=>typeof j=="number"&&!Number.isInteger(j));(a.avg??={})[h]=b.length===0?null:y?b.reduce((j,$)=>j+$,0)/b.length:Qe(v(b.reduce((j,$)=>ge(j,$,1),"0")),{unit:BigInt(b.length),scale:0})}for(let[h,b]of[["min",-1],["max",1]])for(let y of c[h]??[]){let j=g(y);(a[h]??={})[y]=j.length===0?null:j.reduce(($,R)=>(ye(R,$)??0)*b>0?R:$)}return c.count===!0?a.count=s.length:c.count!==void 0&&c.count!==!1&&(a.count=Object.fromEntries(Object.entries(c.count).map(([h,b])=>[h,s.filter(y=>z("aggregate",n,y,b)===!0).length]))),a};if(e.length===0)return r(l);let i=new Map;for(let s of l){let a=JSON.stringify(e.map(g=>s[g]));i.set(a,[...i.get(a)??[],s])}return[...i.values()].map(s=>({...r(s),...Object.fromEntries(e.map(a=>[a,s[0][a]]))}))},insert:N(async(n,c)=>T("insert",n,c)),insertMany:N(async(n,c,l)=>{if(Se(l),l?.onConflict?.length||l?.action!==void 0)throw new Error(`insertMany(${n}): the fake database knows no unique constraint to collide with \u2014 test onConflict against Postgres`);if(c.length===0)return l?.returning===!1?0:[];let e=Object.keys(c[0]);c.forEach((i,s)=>{let a=e.filter(h=>!(h in i)),g=Object.keys(i).filter(h=>!e.includes(h));if(a.length>0||g.length>0)throw new Error(`insertMany(${n}): row ${s} has not the first row's columns${a.length?` (missing ${a.join(", ")})`:""}${g.length?` (extra ${g.join(", ")})`:""} \u2014 write null for an empty one, or insert rows of another shape in a call of their own`)});let r=c.map(i=>T("insertMany",n,i));return l?.returning===!1?r.length:r}),put:N(async(n,c,l)=>{if(!l?.onConflict?.length)throw new Error(`put(${n}): onConflict names at least one column`);let e=C("put",n,c),r=O(n).find(i=>l.onConflict.every(s=>q(i[s],e[s])));if(!r)return T("put",n,c);for(let[i,s]of Object.entries(e))l.onConflict.includes(i)||(r[i]=s);return k(d,n,x(r)),x(r)}),update:N(async(n,c,l)=>{let e=o.get(n)??[],r=e.findIndex(i=>i.id===c);return r<0?(H("update",n,Object.keys(l),l),null):(e[r]={...e[r],...M("update",n,e[r],l)},k(d,n,x(e[r])),x(e[r]))}),updateMany:N(async(n,c,l,e)=>{Y("updateMany",c);let r=E("updateMany",n,c),i=O(n),s=[];for(let a of r){let g=i.indexOf(a);i[g]={...a,...M("updateMany",n,a,l)},k(d,n,x(i[g])),s.push(x(i[g]))}return r.length===0&&H("updateMany",n,Object.keys(l),l),e?.returning===!1?s.length:s}),async delete(n,c){let l=o.get(n)??[],e=l.findIndex(i=>i.id===c);if(e<0)return;let[r]=l.splice(e,1);k(p,n,c),k(f,n,r)},async deleteMany(n,c){Y("deleteMany",c);let l=E("deleteMany",n,c);o.set(n,(o.get(n)??[]).filter(e=>!l.includes(e)));for(let e of l)k(p,n,String(e.id)),k(f,n,e);return l.length},claim:N(async(n,c,l={})=>{let e=Object.keys(c);if(e.length===0)throw new Error(`claim(${n}): no unique field \u2014 claim takes a key; without one, insert(${n}, \u2026)`);H("claim",n,e,c);let r=(o.get(n)??[]).find(i=>e.every(s=>q(i[s],c[s])));return r?{inserted:!1,row:x(r)}:{inserted:!0,row:T("claim",n,{...c,...l})}}),async lockRows(n,c){if(c.length===0)return;let l=o.get(n)??[],e=[...new Set(c)].filter(r=>!l.some(i=>i.id===r));if(e.length>0&&l.length>0)throw new Error(`lockRows(${n}): no row with id ${e.join(", ")}`)},async lockRowsWhere(n,c,l){let e=l?.mode??"update";if(!["update","share","noKeyUpdate"].includes(e))throw new Error(`lockRowsWhere(${n}): mode is "update", "share" or "noKeyUpdate" (got "${String(e)}")`);Y("lockRowsWhere",c),E("lockRowsWhere",n,c)},async advisoryXactLock(){}};function U(n){let c=F(),l=[];try{for(let e of n.ops){let r=m?.nested(e.table)?(o.get(e.table)??[]).map(x):null,i=B(e,l),s=r===null?null:m?.misplaced(e.table,r,o.get(e.table)??[])??null;if(s)throw Object.assign(new Error(s.message),{code:s.code});l.push(i);let a=Ye(e.guard,i.rows.length);if(a)throw a}}catch(e){throw c(),e}return{results:l}}function B(n,c){let l=r=>Object.fromEntries(Object.entries(r??{}).map(([i,s])=>[i,qe(s,c)])),e=`transaction plan ${n.op}`;switch(n.op){case"insert":return we(T(e,n.table,l(n.values)));case"insertMany":{let r=(n.rows??[]).map(a=>l(a)),i=n.onConflict??[];if(n.action!==void 0&&i.length===0)throw new Error(`${e}(${n.table}): the fake database knows no unique key to collide with \u2014 name onConflict columns, or test this against Postgres`);let s=[];for(let a of r){let g=i.length>0?O(n.table).find(h=>i.every(b=>q(h[b],a[b]))):void 0;if(!(g&&n.action==="ignore")){if(g&&n.action==="update"){Object.assign(g,M(e,n.table,g,Object.fromEntries(Object.entries(a).filter(([h])=>!i.includes(h))))),k(d,n.table,x(g)),s.push(x(g));continue}s.push(T(e,n.table,a))}}return{rows:s,rows_affected:s.length}}case"upsert":{let r=l(n.values),i=n.onConflict??[];if(Object.keys(r).length===0||i.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});let s=O(n.table).find(a=>i.every(g=>q(a[g],r[g])));return s?(Object.assign(s,M(e,n.table,s,Object.fromEntries(Object.entries(r).filter(([a])=>!i.includes(a))))),k(d,n.table,x(s)),we(x(s))):we(T(e,n.table,r))}case"update":{let r=l(n.set);if(Object.keys(r).length===0)throw new Error(`update ${n.table}: nothing to set`);let i=me(n.where,c);Y(e,i);let s=O(n.table),a=[];for(let g of E(e,n.table,i)){let h=s.indexOf(g);s[h]={...g,...M(e,n.table,g,r)},k(d,n.table,x(s[h])),a.push(x(s[h]))}return{rows:a,rows_affected:a.length}}case"delete":{let r=me(n.where,c);Y(e,r);let i=E(e,n.table,r);o.set(n.table,O(n.table).filter(s=>!i.includes(s)));for(let s of i)k(p,n.table,String(s.id)),k(f,n.table,s);return{rows:i.map(x),rows_affected:i.length}}case"select":{let r=E(e,n.table,me(n.where,c));return n.limit!==void 0&&(r=r.slice(0,n.limit)),{rows:r.map(x),rows_affected:r.length}}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}}let W={...V,async txPlan(n){return U(n)},async attempt(n){let c=F();try{return await n(V)}catch(l){throw c(),l}},async atomic(){throw new Error("the fake database cannot reproduce a transaction's isolation, COMMIT or retry \u2014 test $atomic against Postgres")}};return{...W,asService:()=>W,inserted:n=>(u.get(n)??[]).map(x),updated:n=>(d.get(n)??[]).map(x),deleted:n=>[...p.get(n)??[]],seed(n,c){o.set(n,c.map(x))},queries:w,...m===void 0?{}:{access:m}}}function pe(t){return new Map([...t].map(([o,u])=>[o,u.map(x)]))}function we(t){return{rows:[t],rows_affected:1}}function qe(t,o){if(!ue(t))return t;let u=o[t.$ref.op]?.rows[0];if(!u)throw Object.assign(new Error(`transaction plan: operation ${t.$ref.op} produced no row to reference`),{error_code:"tx_ref_unresolved"});return u[t.$ref.field]}function me(t,o){let u=d=>{if(ue(d)){let p=qe(d,o);if(p==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${d.$ref.op}'s "${d.$ref.field}" is NULL`),{error_code:"tx_ref_null"});return p}return Array.isArray(d)?d.map(u):d!==null&&typeof d=="object"&&!ee(d)&&!le(d)&&!ne(d)&&!(d instanceof Date)?Object.fromEntries(Object.entries(d).map(([p,f])=>[p,u(f)])):d};return u(t??{})}function Ye(t,o){return t?(t.kind==="one"?o===1:t.kind==="none"?o===0:t.kind==="atLeast"?o>=t.n:o<=t.n)?null:Object.assign(new Error(`transaction expectation failed: ${t.kind} (${o} row(s))`),{error_code:"tx_guard_failed",slot:t.slot}):null}export{Je as createFakeClient,Ue as typedDatabase};
|
package/package.json
CHANGED
|
@@ -8,9 +8,11 @@ export interface AdmissionLease {
|
|
|
8
8
|
*/
|
|
9
9
|
openWithin?: number;
|
|
10
10
|
}
|
|
11
|
+
/** The most connections one request holds at once: its transaction and the two further ones it may hold (request.ts). */
|
|
12
|
+
export declare const MOST_HELD = 3;
|
|
11
13
|
/** Deployment settings, never something a query declares. */
|
|
12
14
|
export interface DatabaseAdmissionOptions {
|
|
13
|
-
/** Requests
|
|
15
|
+
/** Requests at once that may open further transactions; those of a work that opens none fill the rest of the pool. */
|
|
14
16
|
concurrency: number;
|
|
15
17
|
/**
|
|
16
18
|
* Further transactions of requests already admitted, at once, beside
|
|
@@ -42,6 +44,16 @@ export declare class DatabaseAdmission {
|
|
|
42
44
|
private readonly limit;
|
|
43
45
|
private readonly timeout;
|
|
44
46
|
private readonly nestedLimit;
|
|
47
|
+
/** concurrency + nestedConcurrency. */
|
|
48
|
+
private readonly pool;
|
|
49
|
+
/** What a request that may open further transactions keeps of the pool. */
|
|
50
|
+
private readonly claim;
|
|
51
|
+
/** Of `active`, the requests that claim one connection. */
|
|
52
|
+
private singles;
|
|
53
|
+
/** The ones that opened a further transaction, waiting for their whole claim. */
|
|
54
|
+
private readonly widening;
|
|
55
|
+
/** A work's requests in a row that held one transaction at a time, up to SINGLE_AFTER. */
|
|
56
|
+
private readonly works;
|
|
45
57
|
private nestedActive;
|
|
46
58
|
private readonly nestedPending;
|
|
47
59
|
constructor(options: DatabaseAdmissionOptions);
|
|
@@ -49,6 +61,7 @@ export declare class DatabaseAdmission {
|
|
|
49
61
|
get queueTimeoutMs(): number;
|
|
50
62
|
get snapshot(): {
|
|
51
63
|
active: number;
|
|
64
|
+
single: number;
|
|
52
65
|
queued: number;
|
|
53
66
|
nested: {
|
|
54
67
|
active: number;
|
|
@@ -62,8 +75,19 @@ export declare class DatabaseAdmission {
|
|
|
62
75
|
cancelled: number;
|
|
63
76
|
};
|
|
64
77
|
};
|
|
78
|
+
/** A request of `work` ended with one transaction at a time. */
|
|
79
|
+
heldOne(work: string): void;
|
|
80
|
+
private holdsOne;
|
|
81
|
+
private get claimed();
|
|
82
|
+
private get room();
|
|
83
|
+
private admits;
|
|
84
|
+
private widens;
|
|
85
|
+
private widen;
|
|
86
|
+
private widened;
|
|
65
87
|
private nestedLease;
|
|
88
|
+
private get nestedFree();
|
|
66
89
|
private acquireNested;
|
|
90
|
+
private waits;
|
|
67
91
|
private rejection;
|
|
68
92
|
private take;
|
|
69
93
|
private drain;
|
|
@@ -71,11 +95,14 @@ export declare class DatabaseAdmission {
|
|
|
71
95
|
* A transaction's turn; `nested` for a further transaction of a request
|
|
72
96
|
* already admitted, `returning` for the next one of a request that gave its
|
|
73
97
|
* connection back meanwhile — at the head of its user's line, not refused
|
|
74
|
-
* as full.
|
|
98
|
+
* as full. `work` names what the request runs (RequestOptions.work); a
|
|
99
|
+
* further one comes with its request's `turn`.
|
|
75
100
|
*/
|
|
76
101
|
acquire(claims: Record<string, unknown>, signal?: AbortSignal, options?: {
|
|
77
102
|
nested?: boolean;
|
|
78
103
|
returning?: boolean;
|
|
104
|
+
work?: string;
|
|
105
|
+
turn?: AdmissionLease;
|
|
79
106
|
}): Promise<AdmissionLease>;
|
|
80
107
|
}
|
|
81
108
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { Binding } from '../connect.js';
|
|
2
2
|
import type { Roles } from '../plan.js';
|
|
3
|
-
import type
|
|
3
|
+
import { type DatabaseAdmission } from './admission.js';
|
|
4
4
|
import type { Catalog } from './catalog.js';
|
|
5
5
|
import type { DBClient } from './client.js';
|
|
6
6
|
import { type DatabaseDiagnosticsOptions } from './diagnostics.js';
|
|
@@ -21,6 +21,12 @@ export interface Identity {
|
|
|
21
21
|
export interface RequestOptions {
|
|
22
22
|
/** Statement events, totals and a budget — allocated only when given. */
|
|
23
23
|
diagnostics?: DatabaseDiagnosticsOptions;
|
|
24
|
+
/**
|
|
25
|
+
* What the request runs — its route, cron or event, not who calls it — by a
|
|
26
|
+
* name its every request gives: one whose requests open no transaction
|
|
27
|
+
* beside another is admitted on one connection (admission.ts).
|
|
28
|
+
*/
|
|
29
|
+
work?: string;
|
|
24
30
|
/**
|
|
25
31
|
* Told once, with how long it has waited, when a transaction of the
|
|
26
32
|
* request that cannot be given back — it wrote, locked or took a
|