palgres 0.54.0 → 0.55.0

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.
@@ -1,309 +0,0 @@
1
- /*! palgres 0.54.0 — Palbase SDK License (see LICENSE) */
2
- import{createHash as rn}from"node:crypto";function Yn(t){return`${t}_lookup`}function zn(t,e){let n=s=>s==="cascade"||s==="set null"||s==="set default";return n(t)||n(e)}var Nt=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
- - ${e.join(`
4
- - `)}`),this.name="SchemaError",this.problems=e}},Jn=()=>({tables:[],enums:[],extensions:[],raw:[]}),te=t=>`${t.schema}.${t.name}`,an={int:"integer",int4:"integer",int2:"smallint",int8:"bigint",float4:"real",float8:"double precision",bool:"boolean",timestamptz:"timestamp with time zone",timestamp:"timestamp without time zone","timestamp without time zone":"timestamp without time zone",timetz:"time with time zone",time:"time without time zone",varchar:"character varying",char:"character",decimal:"numeric"};function Ye(t){let e=t.trim().replace(/\s+/g," "),n="";for(;e.endsWith("[]");)n+="[]",e=e.slice(0,-2).trim();let s=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!s)return t.trim()+n;let r=s[2]?s[2].replace(/\s+/g,""):"",o=cn(s[1]);return o===void 0?t.trim()+n:o.length===1&&o[0].quoted?`"${o[0].name.replace(/"/g,'""')}"${r}${n}`:o.length===1?`${an[o[0].name]??o[0].name}${r}${n}`:`${o.map(l=>Xe(l.name)).join(".")}${r}${n}`}var Xe=t=>/^[a-z_][a-z0-9_$]*$/.test(t)?t:`"${t.replace(/"/g,'""')}"`,Qn=(t,e)=>`${Xe(t)}.${Xe(e)}`;function cn(t){let e=[],n=0;for(;n<t.length;){if(t[n]==='"'){let s=n+1,r="";for(;;){if(s>=t.length)return;if(t[s]==='"'){if(t[s+1]==='"'){r+='"',s+=2;continue}break}r+=t[s++]}e.push({name:r,quoted:!0}),n=s+1}else{let s=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(t.slice(n));if(!s)return;e.push({name:s[0].trim().toLowerCase(),quoted:!1}),n+=s[0].length}if(n<t.length){if(t[n]!==".")return;n++}}return e}var ln=/^[A-Za-z_][A-Za-z0-9_$]*$/,un=63;function Z(t,e,n=!1){if(typeof e!="string"||e==="")return`${t} has no name`;if(n?e.includes("\0"):!ln.test(e))return`${t} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>un)return`${t} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${t} "${e}": names starting with palgres_ are Palgres' own`}var pn="vector",wt=["cosine","euclidean","inner_product"],ze=1536,mn=2e3,Be=4e3,dn=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function Je(t,e,n){let s=[];e.primaryKey.length!==1&&s.push(`${t} declares search and has ${e.primaryKey.length===0?"no primary key":`a primary key of ${e.primaryKey.length} columns`}: a row's vector is kept by its key \u2014 give the table a single-column primary key (uuid().primaryKey())`),(!Array.isArray(n.from)||n.from.length===0)&&s.push(`${t}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let r=new Set;for(let o of Array.isArray(n.from)?n.from:[]){r.has(o)&&s.push(`${t}: search.from names "${o}" twice \u2014 name each column once`),r.add(o);let l=e.columns.find(a=>a.name===o);l?l.ignored?s.push(`${t}: search.from names "${o}", which is ignored \u2014 take it out of search.from, or keep the column`):dn.test(Ye(l.type))?l.generated&&s.push(`${t}: search.from names "${o}", a generated column \u2014 no write names it, so nothing would say when to embed the row again: name the columns it is computed from`):s.push(`${t}: search.from names "${o}", which is ${l.type} \u2014 search reads text (text, varchar, citext): name a text column, or keep the text in one`):s.push(`${t}: search.from names "${o}", which the table does not have \u2014 name its text columns`)}return(typeof n.model!="string"||n.model.trim()==="")&&s.push(`${t}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),wt.includes(n.metric)||s.push(`${t}: search.metric is ${JSON.stringify(n.metric)} \u2014 it is ${wt.map(o=>`'${o}'`).join(", ")}`),(!Number.isInteger(n.dimensions)||n.dimensions<1||n.dimensions>Be)&&s.push(`${t}: search.dimensions is ${String(n.dimensions)} \u2014 it is 1 to ${Be}: pgvector indexes a vector of at most ${mn} dimensions and a half-precision one of at most ${Be}; ask the model for fewer (search: { dimensions: ${ze} })`),n.staleness!=="null"&&n.staleness!=="keep"&&s.push(`${t}: search.staleness is ${JSON.stringify(n.staleness)} \u2014 it is 'null' (a changed row is not found by its old meaning) or 'keep' (it is, until embedded again)`),e.columns.some(o=>o.name==="_score"&&!o.ignored)&&s.push(`${t} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),s}function Zn(t){let e=[],n=a=>a&&e.push(a),s=new Map,r=new Map,o=(a,c,h)=>{let C=`${a}.${c}`,M=r.get(C);M?e.push(`${h} "${c}" has the name of ${M} in schema ${a}`):r.set(C,h)};for(let a of t.enums)n(Z("an enum",a.name)),a.values.length===0&&e.push(`enum ${a.schema}.${a.name} has no values`),new Set(a.values).size!==a.values.length&&e.push(`enum ${a.schema}.${a.name} names a value twice`);for(let a of t.tables){let c=te(a);n(Z("a schema",a.schema)),n(Z("a table",a.name)),s.has(c)&&e.push(`table ${c} is declared twice`),s.set(c,a),o(a.schema,a.name,`table ${c}`);let h=new Map,C=(m,j)=>{let G=h.get(m);G?e.push(`${j} "${m}" has the name of a ${G} of table ${c}`):h.set(m,j)},M=new Map;for(let m of a.columns)n(Z(`column ${c}.${m.name}`,m.name)),M.has(m.name)&&e.push(`column ${c}.${m.name} is declared twice`),M.set(m.name,m),m.identity&&m.default!==void 0&&e.push(`column ${c}.${m.name}: an identity column has no default`),m.generated&&(m.default!==void 0||m.identity||m.fill!==void 0)&&e.push(`column ${c}.${m.name}: a generated column has no default, identity or fill`),m.generated&&!m.generated.expr.trim()&&e.push(`column ${c}.${m.name}: a generated column's expression is empty`),m.identity&&!["smallint","integer","bigint"].includes(Ye(m.type))&&e.push(`column ${c}.${m.name}: an identity column is smallint, integer or bigint`),m.identity&&m.nullable&&e.push(`column ${c}.${m.name}: an identity column is NOT NULL`);let k=(m,j)=>{let G=M.get(m);G?G.ignored&&e.push(`${j} names column "${m}", which is ignored`):e.push(`${j} names column "${m}", which ${c} does not have`)};for(let m of a.primaryKey)k(m,`the primary key of ${c}`);for(let m of a.primaryKey)M.get(m)?.nullable&&e.push(`column ${c}.${m} is in the primary key, so it is not nullable`);for(let m of a.uniques){n(Z(`a unique constraint of ${c}`,m.name,!0)),o(a.schema,m.name,`unique constraint ${c}.${m.name}`),C(m.name,"unique constraint"),m.columns.length===0&&e.push(`unique constraint ${m.name} names no column`);for(let j of m.columns)k(j,`unique constraint ${m.name}`)}for(let m of a.indexes){n(Z(`an index of ${c}`,m.name,!0)),o(a.schema,m.name,`index ${c}.${m.name}`),m.keys.length===0&&e.push(`index ${m.name} has no key`);for(let j of m.keys)"column"in j&&k(j.column,`index ${m.name}`);for(let j of m.include??[])k(j,`index ${m.name}`)}for(let m of a.checks)n(Z(`a check of ${c}`,m.name,!0)),C(m.name,"check"),m.expr.trim()||e.push(`check ${m.name} has no expression`);for(let m of a.foreignKeys){n(Z(`a foreign key of ${c}`,m.name,!0)),C(m.name,"foreign key"),(m.columns.length===0||m.columns.length!==m.refColumns.length)&&e.push(`foreign key ${m.name} names ${m.columns.length} column(s) and references ${m.refColumns.length}`);for(let j of m.columns)k(j,`foreign key ${m.name}`)}let P=new Set;for(let m of a.policies)n(Z(`a policy of ${c}`,m.name,!0)),P.has(m.name)&&e.push(`policy ${c}.${m.name} is declared twice`),P.add(m.name),m.to.length===0&&e.push(`policy ${c}.${m.name} names no role`),m.for==="insert"&&m.using!==void 0&&e.push(`policy ${c}.${m.name}: an insert policy has only withCheck`),(m.for==="select"||m.for==="delete")&&m.withCheck!==void 0&&e.push(`policy ${c}.${m.name}: a ${m.for} policy has only using`);a.policies.length>0&&!a.rls&&e.push(`table ${c} has policies but row-level security off: they would do nothing`),a.search!==void 0&&e.push(...Je(`table ${c}`,a,a.search))}for(let a of t.tables)for(let c of a.foreignKeys){let h=s.get(`${c.refSchema}.${c.refTable}`);if(!h){e.push(`foreign key ${c.name} of ${te(a)} references ${c.refSchema}.${c.refTable}, which is not declared`);continue}h.ignored&&e.push(`foreign key ${c.name} of ${te(a)} references ${te(h)}, which is ignored`);for(let C of c.refColumns)h.columns.some(M=>M.name===C&&!M.ignored)||e.push(`foreign key ${c.name} references ${te(h)}.${C}, which it does not have`)}let l=new Set;for(let a of t.raw)n(Z("a raw unit",a.name)),l.has(a.name)&&e.push(`raw unit ${a.name} is declared twice`),l.add(a.name),a.sql.trim()||e.push(`raw unit ${a.name} has no SQL`),a.before&&a.table!==void 0&&e.push(`raw unit ${a.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function _t(t){let e=n=>[...n].sort((s,r)=>s.name<r.name?-1:s.name>r.name?1:0);return{tables:[...t.tables].map(n=>({...n,schema:n.schema||"public",columns:n.columns.map(s=>({...s,type:Ye(s.type)})),uniques:e(n.uniques),indexes:e(n.indexes),checks:e(n.checks),foreignKeys:e(n.foreignKeys),policies:e(n.policies).map(s=>({...s,to:[...s.to].sort()}))})).sort((n,s)=>te(n)<te(s)?-1:te(n)>te(s)?1:0),enums:[...t.enums].sort((n,s)=>`${n.schema}.${n.name}`<`${s.schema}.${s.name}`?-1:1),extensions:[...new Set([...t.extensions,...t.tables.some(n=>n.search!==void 0)?[pn]:[]])].sort(),raw:e(t.raw),...t.access!==void 0?{access:t.access}:{}}}function es(t){let e=_t(t),n=new Map(t.raw.map((s,r)=>[s.name,r]));return e.raw.sort((s,r)=>(n.get(s.name)??0)-(n.get(r.name)??0)),e}function Ve(t){return Array.isArray(t)?`[${t.map(Ve).join(",")}]`:t&&typeof t=="object"?`{${Object.entries(t).filter(([,n])=>n!==void 0).sort(([n],[s])=>n<s?-1:1).map(([n,s])=>`${JSON.stringify(n)}:${Ve(s)}`).join(",")}}`:JSON.stringify(t)}function ts(t){return rn("sha256").update(Ve(_t(t))).digest("hex").slice(0,32)}var Qe=Symbol.for("palbase.table.meta"),le=Symbol.for("palbase.ref.target"),je=class{_def;constructor(e){if(e.trim()==="")throw new Error("foreignKey(name): a foreign key's name cannot be empty \u2014 Palbase reconciles constraints by name.");this._def={name:e,columns:[],refTable:"",refColumns:[]}}on(...e){return this._def.columns=e.map(n=>{let s=n.expr;if(s.kind!=="col")throw new Error(`foreignKey(${this._def.name}).on(): takes column references only \u2014 an expression cannot be part of a foreign key.`);return s.name}),this}references(e,...n){if(n.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...n],typeof e=="function"?(Object.defineProperty(this._def,le,{value:()=>e()[Qe],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[Qe].name,Object.defineProperty(this._def,le,{value:e[Qe],enumerable:!1,configurable:!0}),this)}onUpdate(e){return this._def.onUpdate=e,this}onDelete(e){return this._def.onDelete=e,this}match(e){return this._def.match=e,this}index(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).index(): only index(false) \u2014 an index is made unasked`);return this._def.index=!1,this}deferrable(e){if(e!==!1)throw new Error(`foreignKey(${this._def.name}).deferrable(): only deferrable(false) \u2014 a key with an action is deferrable unasked`);return this._def.deferrable=!1,this}};function fn(t){return new je(t)}function xt(t){let e=t instanceof je?t._def:t;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let n=typeof e[le]=="function";if(e.refColumns.length===0||e.refTable===""&&!n)throw new Error(`foreignKey(${e.name}): needs the target table and its columns \u2014 call .references(...).`);if(e.columns.length!==e.refColumns.length)throw new Error(`foreignKey(${e.name}): ${e.columns.length} local column(s) (${e.columns.join(", ")}) but ${e.refColumns.length} target column(s) (${e.refColumns.join(", ")}) \u2014 the two lists must be the same length.`);return e}var T=class extends Error{code;line;constructor(e,n,s=0){super(s>0?`line ${s}: ${n}`:n),this.name="AccessError",this.code=e,this.line=s}};var gn=["->","!=","<=",">=","<>",":",",","=","<",">","+","&","-","(",")",".","|"],At=256*1024,Ot=256,St=32;function En(t){if(t.length>At)throw new T("too_large",`the schema is ${t.length} characters; at most ${At}`);let e=[],n=0,s=1,r=o=>{throw new T("syntax",o,s)};for(;n<t.length;){let o=t[n];if(o===`
5
- `){e.push({k:"nl",v:`
6
- `,line:s,at:n,end:n+1}),s++,n++;continue}if(o===" "||o===" "||o==="\r"){n++;continue}if(o==="#"||o==="/"&&t[n+1]==="/"){for(;n<t.length&&t[n]!==`
7
- `;)n++;continue}if(/[A-Za-z_]/.test(o)){let a=n+1;for(;a<t.length&&/[A-Za-z0-9_]/.test(t[a]);)a++;e.push({k:"word",v:t.slice(n,a),line:s,at:n,end:a}),n=a;continue}if(/[0-9]/.test(o)){let a=n+1;for(;a<t.length&&/[0-9]/.test(t[a]);)a++;if(t[a]==="."&&/[0-9]/.test(t[a+1]??""))for(a++;a<t.length&&/[0-9]/.test(t[a]);)a++;/[A-Za-z_]/.test(t[a]??"")&&r(`"${t.slice(n,a+1)}" is not a number`),e.push({k:"number",v:t.slice(n,a),line:s,at:n,end:a}),n=a;continue}if(o==='"'||o==="'"){let a=n+1,c="";for(;;){if((a>=t.length||t[a]===`
8
- `)&&r(o==='"'?"a quoted name is not closed":"a text value is not closed"),t[a]===o){if(t[a+1]===o){c+=o,a+=2;continue}break}c+=t[a],a++}c.includes("\0")&&r("a NUL character cannot be in a name or a value"),o==='"'&&c===""&&r("a quoted name is empty"),e.push({k:o==='"'?"quoted":"string",v:c,line:s,at:n,end:a+1}),n=a+1;continue}let l=gn.find(a=>t.startsWith(a,n));l||r(`unexpected character ${JSON.stringify(o)}`),e.push({k:"sym",v:l,line:s,at:n,end:n+l.length}),n+=l.length}return e.push({k:"nl",v:`
9
- `,line:s,at:n,end:n}),e.push({k:"end",v:"",line:s,at:n,end:n}),e}var hn=["select","insert","update","delete"];function de(t){let e=En(t),n=0,s=(p=0)=>e[Math.min(n+p,e.length-1)],r=()=>e[Math.min(n++,e.length-1)],o=(p,E=s())=>{throw new T("syntax",p,E.line)},l=p=>p.k==="nl"?"the end of the line":p.k==="end"?"the end of the schema":`"${p.v}"`,a=(p,E=0)=>s(E).k==="sym"&&s(E).v===p,c=(p,E=0)=>s(E).k==="word"&&s(E).v===p,h=(p,E)=>(a(p)||o(`expected "${p}" ${E}, found ${l(s())}`),r()),C=()=>{for(;s().k==="nl";)r()},M=p=>{s().k!=="nl"&&s().k!=="end"&&o(`unexpected ${l(s())} after ${p}`)},k=p=>{let E=r();E.k!=="word"&&o(`expected ${p}, found ${l(E)}`,E);let d=E.v,b=s(),A=s(1);return b.k==="sym"&&b.v==="."&&b.at===E.end&&A.k==="word"&&A.at===b.end&&(r(),r(),d+=`.${A.v}`),d},P=p=>{let E=r();return E.k!=="word"&&E.k!=="quoted"&&o(`expected ${p}, found ${l(E)}`,E),E.v},m=()=>{let p=r();return p.k==="string"?(p.v.length>Ot&&o(`a value is at most ${Ot} characters; this one has ${p.v.length}`,p),{t:"string",v:p.v}):p.k==="number"?{t:"number",v:p.v}:p.k==="sym"&&p.v==="-"&&s().k==="number"&&s().at===p.end?{t:"number",v:`-${r().v}`}:p.k==="word"&&(p.v==="true"||p.v==="false")?{t:"boolean",v:p.v==="true"}:o(`expected a value ('text', a number, true or false), found ${l(p)}`,p)},j=0,G=p=>{if(++j>St)throw new T("too_deep",`parentheses and "not" nested more than ${St} deep`,s().line);try{return p()}finally{j--}},V=()=>{let p=v();if(!c("and")&&!c("or"))return p;let E=s().v,d=[p];for(;c("and")||c("or");)s().v!==E&&o(`"${E}" and "${s().v}" in one condition: put parentheses around one of them`),r(),d.push(v());return{op:E,parts:d}},v=()=>{if(c("not"))return r(),{op:"not",part:G(v)};if(a("(")){r();let d=G(V);return h(")","to close the condition"),d}let p=P("a column");if(c("is")){r();let d=!1;return c("not")&&(r(),d=!0),c("null")||o(`expected "null" after "is", found ${l(s())}`),r(),{op:"null",column:p,negated:d}}if(c("in")){r(),h("(",'after "in"');let d=[m()];for(;a(",");)r(),d.push(m());return h(")","to close the list"),{op:"in",column:p,values:d}}let E=r();return(E.k!=="sym"||!["=","!=","<>","<","<=",">",">="].includes(E.v))&&o(`expected a comparison after "${p}", found ${l(E)}`,E),{op:"cmp",column:p,cmp:E.v==="<>"?"!=":E.v,value:m()}},f=()=>{let p=g(),E=()=>{let I=0;for(;s(I).k==="nl";)I++;let x=s(I),U=x.k!=="sym"?null:x.v==="+"?"union":x.v==="&"?"intersect":x.v==="-"?"exclude":null;return U!==null&&(n+=I),U},d=E();if(d===null)return p;let b=p,A=[p];for(;;){let I=E();if(I===null)break;I!==d&&o(`"${s().v}" beside another operator: put parentheses around one of them`),r(),C();let x=g();d==="exclude"?b={op:"exclude",base:b,minus:x}:A.push(x)}return d==="exclude"?b:{op:d,parts:A}},g=()=>{if(a("(")){r(),C();let E=G(f);return C(),h(")","to close the expression"),E}let p=k("a relation or a permission");return a("->")?(r(),{op:"arrow",relation:p,name:k('a relation or a permission after "->"')}):{op:"ref",name:p}},N=[];for(C();s().k!=="end";){c("type")||o(`expected "type", found ${l(s())}`);let p=r(),E={name:k("the type's name"),table:null,relations:[],permissions:[],rows:[],line:p.line};for(M("the type's name"),C();s().k!=="end"&&!c("type");){let d=r();if(d.k!=="word"&&o(`expected "table", "relation", "permission" or "rows", found ${l(d)}`,d),d.v==="table"){E.table&&o(`type ${E.name} names its table twice`,d);let b=null,A=P("a table");a(".")&&(r(),b=A,A=P("a table"));let I=null;c("key")&&(r(),I=P("the key column")),E.table={schema:b,name:A,key:I,line:d.line},M("the table")}else if(d.v==="relation"){let b=[k("the relation's name")];for(;a(",");)r(),b.push(k("a relation's name"));h(":","after the relation's name");let A=[k('"user" or a type')];for(;a("|");)r(),A.push(k('"user" or a type'));if(c("from")){r(),b.length>1&&o("a relation read from a column is declared alone, one per line",d),A.length>1&&o("a relation read from a column has one kind of subject",d);let I=P("a column"),x=null;c("where")&&(r(),x=V()),E.relations.push({kind:"column",name:b[0],subject:A[0],column:I,where:x,line:d.line})}else for(let I of b)E.relations.push({kind:"stored",name:I,subjects:[...A],line:d.line});M("the relation")}else if(d.v==="permission"){let b=k("the permission's name");h("=","after the permission's name"),C(),E.permissions.push({name:b,expr:f(),line:d.line}),M("the permission")}else if(d.v==="rows"){let b=[];for(;;){let A=r();if((A.k!=="word"||!hn.includes(A.v))&&o(`expected select, insert, update or delete, found ${l(A)}`,A),b.push(A.v),!a(","))break;r()}h(":","after the commands"),E.rows.push({commands:b,name:k("a permission"),line:d.line}),M("the rows rule")}else o(`expected "table", "relation", "permission" or "rows", found "${d.v}"`,d);C()}N.push(E)}return{types:N}}var z="user",Ze=16,Ct=200,It=100,Lt=200,kt=200,jt=50,Dt=25e3,Ft=300,tt=150,$n=2,yn=4,Mt=63,bn=/^[a-z][a-z0-9_]{0,39}$/,Rn=/^[a-z][a-z0-9_]{0,39}(\.[a-z][a-z0-9_]{0,39})?$/,Fe=t=>t.replace(".","__"),Te=t=>t.kind==="stored"?t.subjects.includes(z):t.subject===z,se=t=>t.kind==="stored"?t.subjects.filter(e=>e!==z):t.subject===z?[]:[t.subject];function De(t){return t.op==="ref"||t.op==="arrow"?1:t.op==="exclude"?1+De(t.base)+De(t.minus):1+t.parts.reduce((e,n)=>e+De(n),0)}function Re(t){return"parts"in t?t.parts.reduce((e,n)=>e+Re(n),0):t.op==="not"?Re(t.part):t.op==="in"?t.values.length:1}function et(t,e){if("parts"in t)for(let n of t.parts)et(n,e);else t.op==="not"?et(t.part,e):e.add(t.column)}function nt(t){let e=new Set;return t&&et(t,e),[...e]}function fe(t){if(t.types.length>Ct)throw new T("too_large",`${t.types.length} types; at most ${Ct}`);let e=new Map;for(let f of t.types){if(f.name===z)throw new T("invalid_name",'"user" is whoever asks: a type cannot be called that',f.line);if(!bn.test(f.name)||f.name.includes("__"))throw new T("invalid_name",`type "${f.name}" is not a name: lowercase letters, digits and single underscores, starting with a letter, at most 40`,f.line);if(e.has(f.name))throw new T("duplicate",`type "${f.name}" is declared twice`,f.line);let g=new Map,N=new Map,p=new Map,E=(d,b,A)=>{if(!Rn.test(d)||d.includes("__"))throw new T("invalid_name",`${A} "${d}" is not a name: lowercase letters, digits and single underscores, with at most one dot (code.write), at most 40 each side`,b);if(g.has(d)||N.has(d))throw new T("duplicate",`"${d}" is declared twice in type ${f.name}`,b);let I=Fe(d),x=`${f.name}__${I}`;if(x.length>Mt)throw new T("invalid_name",`${A} "${d}" of type ${f.name}: together they are asked as access.${x} \u2014 ${x.length} characters, and a name in the database holds ${Mt}. Shorten the type's name or this one`,b);let U=p.get(I);if(U!==void 0)throw new T("duplicate",`"${d}" and "${U}" of type ${f.name} would have one name in the database`,b);p.set(I,d)};for(let d of f.relations)E(d.name,d.line,"relation"),g.set(d.name,d);for(let d of f.permissions){if(E(d.name,d.line,"permission"),De(d.expr)>Lt)throw new T("too_large",`permission ${f.name}.${d.name} has more than ${Lt} terms`,d.line);N.set(d.name,d)}if(g.size+N.size>It)throw new T("too_large",`type ${f.name} declares more than ${It} names`,f.line);e.set(f.name,{name:f.name,table:f.table?{schema:f.table.schema??"public",name:f.table.name,key:f.table.key}:null,relations:g,permissions:N,rows:[]})}let n=new Map;for(let f of e.values()){if(!f.table)continue;let g=`${f.table.schema}\0${f.table.name}`,N=n.get(g);if(N!==void 0)throw new T("duplicate",`types ${N} and ${f.name} name the same table`,t.types.find(p=>p.name===f.name)?.line??0);n.set(g,f.name)}for(let f of t.types){let g=e.get(f.name);for(let N of f.relations)if(N.kind==="stored"){let p=new Set;for(let E of N.subjects){if(p.has(E))throw new T("duplicate",`relation ${g.name}.${N.name} names "${E}" twice`,N.line);if(p.add(E),E!==z&&!e.has(E))throw new T("unknown_type",`relation ${g.name}.${N.name}: there is no type "${E}"`,N.line)}}else{if(!g.table)throw new T("needs_table",`relation ${g.name}.${N.name} reads a column, and type ${g.name} names no table`,N.line);if(N.where&&Re(N.where)>jt)throw new T("too_large",`relation ${g.name}.${N.name}: its condition holds more than ${jt} comparisons`,N.line);if(N.subject!==z&&!e.has(N.subject))throw new T("unknown_type",`relation ${g.name}.${N.name}: there is no type "${N.subject}"`,N.line)}}let s=(f,g)=>{let N=e.get(f);return N.relations.get(g)??N.permissions.get(g)},r=(f,g)=>e.get(f).permissions.has(g),o=(f,g)=>{let N=e.get(f);if(N.permissions.has(g))return"yes";let p=N.relations.get(g);return p?Te(p)?"yes":"objects":"missing"},l=new Map,a=(f,g)=>`${f}\0${g}`;for(let f of t.types){let g=e.get(f.name);for(let p of f.permissions){let E=[],d=b=>{if(b.op==="ref"){let A=o(g.name,b.name);if(A==="missing")throw new T("unknown_name",`permission ${g.name}.${p.name}: type ${g.name} has no relation or permission "${b.name}"`,p.line);if(A==="objects")throw new T("not_a_holder",`permission ${g.name}.${p.name}: relation "${b.name}" leads to objects, no subject holds it \u2014 follow it with "->", as in ${b.name}->view`,p.line);E.push({type:g.name,name:b.name})}else if(b.op==="arrow"){let A=g.relations.get(b.relation);if(!A){let x=g.permissions.has(b.relation)?`"${b.relation}" is a permission; an arrow follows a relation`:`type ${g.name} has no relation "${b.relation}"`;throw new T("unknown_name",`permission ${g.name}.${p.name}: ${x}`,p.line)}let I=se(A);if(I.length===0)throw new T("not_an_object_relation",`permission ${g.name}.${p.name}: relation "${b.relation}" leads to no object (its subjects are users), so "->" has nothing to follow`,p.line);for(let x of I){let U=o(x,b.name);if(U==="missing")throw new T("unknown_name",`permission ${g.name}.${p.name}: ${b.relation}->${b.name} \u2014 type ${x} has no relation or permission "${b.name}"`,p.line);if(U==="objects")throw new T("not_a_holder",`permission ${g.name}.${p.name}: ${b.relation}->${b.name} \u2014 "${b.name}" of type ${x} leads to objects, no subject holds it`,p.line);E.push({type:x,name:b.name})}}else if(b.op==="exclude")d(b.base),d(b.minus);else for(let A of b.parts)d(A)};d(p.expr),l.set(a(g.name,p.name),E)}let N=new Set;for(let p of f.rows){if(!g.table)throw new T("needs_table",`type ${g.name} has a rows rule and names no table`,p.line);let E=o(g.name,p.name);if(E==="missing")throw new T("unknown_name",`rows rule of type ${g.name}: there is no relation or permission "${p.name}"`,p.line);if(E==="objects")throw new T("not_a_holder",`rows rule of type ${g.name}: relation "${p.name}" leads to objects, no subject holds it`,p.line);for(let d of p.commands){if(N.has(d))throw new T("duplicate",`type ${g.name} has two rows rules for ${d}`,p.line);N.add(d),g.rows.push({command:d,name:p.name})}}}let c=[],h=new Map,C=(f,g)=>s(f,g)?.line??0,M=(f,g,N)=>{let p=a(f,g),E=h.get(p);if(typeof E=="number")return E;let d=`${f}.${g}`;if(E==="open"){let A=N.indexOf(d),I=[...N.slice(A),d].join(" \u2192 ");throw new T("cycle",`${I}: a permission derived from itself. A type that contains itself (a folder in a folder) is not supported; fixed levels are (company, product, session), however many`,C(f,g))}h.set(p,"open");let b=0;if(r(f,g))for(let A of l.get(p)??[])b=Math.max(b,1+M(A.type,A.name,[...N,d]));if(b>Ze)throw new T("too_deep",`${d} is derived through more than ${Ze} levels`,C(f,g));return h.set(p,b),c.push({type:f,name:g}),b};for(let f of e.values()){for(let g of f.relations.values())M(f.name,g.name,[]);for(let g of f.permissions.values())M(f.name,g.name,[])}let k=new Map,P=(f,g)=>{let N=a(f,g),p=k.get(N);if(p!==void 0)return p;let E=e.get(f),d=E.permissions.get(g),b=I=>I.op==="ref"?P(f,I.name):I.op==="arrow"?1+se(E.relations.get(I.relation)).reduce((x,U)=>x+P(U,I.name),0):I.op==="exclude"?b(I.base)+b(I.minus):I.parts.reduce((x,U)=>x+b(U),0),A=d?b(d.expr):1;return k.set(N,A),A};for(let f of e.values())for(let g of f.permissions.values()){let N=P(f.name,g.name);if(N>kt)throw new T("too_large",`permission ${f.name}.${g.name} comes to ${N} relations once everything it is derived from is written out; at most ${kt}. It names the same permissions through several paths \u2014 derive it from fewer, or from relations directly`,g.line)}let m=new Map,j=(f,g)=>{let N=a(f,g),p=m.get(N);if(p!==void 0)return p;let E=e.get(f),d=E.permissions.get(g),b=x=>x&&x.kind==="column"&&x.where?1+Re(x.where):1,A=x=>x.op==="ref"?j(f,x.name):x.op==="arrow"?b(E.relations.get(x.relation)):x.op==="exclude"?A(x.base)+A(x.minus):x.parts.reduce((U,ee)=>U+A(ee),0),I=d?A(d.expr):b(E.relations.get(g));return m.set(N,I),I},G=new Map,V=(f,g)=>{let N=a(f,g),p=G.get(N);if(p!==void 0)return p;let E=e.get(f),d=E.permissions.get(g),b=x=>x&&x.kind==="column"&&x.where?1+Re(x.where):1,A=x=>{if(x.op==="ref")return V(f,x.name);if(x.op==="arrow"){let U=E.relations.get(x.relation),ee=U.kind==="column"?$n:yn;return b(U)+ee*se(U).reduce((Se,Ce)=>Se+V(Ce,x.name),0)}return x.op==="exclude"?A(x.base)+A(x.minus):x.parts.reduce((U,ee)=>U+A(ee),0)},I=d?A(d.expr):b(E.relations.get(g));return G.set(N,I),I};for(let f of e.values())for(let g of f.permissions.values()){let N=V(f.name,g.name);if(N>Ft)throw new T("too_large",`permission ${f.name}.${g.name} would be planned as ${N} lookups \u2014 what it reads through another type is planned inside it, two or four times over; at most ${Ft} (about 140 KB of the database's memory each, on every statement it guards). Read fewer levels deep through other types' permissions, or through relations read from columns`,g.line)}let v=0;for(let f of e.values())for(let g of[...f.relations.keys(),...f.permissions.keys()])v+=j(f.name,g);if(v>Dt)throw new T("too_large",`the schema comes to ${v} terms once each of its names is written out in full (a permission with what it names, a relation with its condition); at most ${Dt}. Derive permissions from one another's names through fewer copies, or shorten the conditions they repeat`);return{types:e,order:c,planned:V}}var Ne=63,_=t=>{if(t.includes("\0"))throw new TypeError("a NUL character cannot be in a name");if(new TextEncoder().encode(t).length>Ne)throw new T("invalid_name",`"${t}" is longer than the ${Ne} bytes a name in the database holds`);return`"${t.replace(/"/g,'""')}"`},st=(t,e)=>`${_(t)}.${_(e)}`;function $(t){if(t.includes("\0"))throw new TypeError("a NUL character cannot be sent to Postgres");return`E'${t.replace(/\\/g,"\\\\").replace(/'/g,"''")}'`}function L(t){let e="access";for(let n=0;t.includes(`$${e}$`);n++)e=`access${n}`;return`$${e}$${t}$${e}$`}var Tn={text:"text",varchar:"text",uuid:"uuid",int2:"int",int4:"int",int8:"int",bool:"bool",numeric:"numeric",float4:"numeric",float8:"numeric"};function ot(t){let e=typeof t=="string"?JSON.parse(t):t;if(!Array.isArray(e))throw new T("syntax","the catalog could not be read: its answer is not a list of tables");let n=new Map;for(let s of e){let r=new Map;for(let o of s.columns)r.set(o.name,{type:o.type,family:o.array?null:o.enum?"enum":Tn[o.type]??null});n.set(`${s.schema}\0${s.name}`,{schema:s.schema,name:s.name,kind:s.kind,primaryKey:s.pk,identifying:s.identifying??(s.pk.length===1?[...s.pk]:[]),columns:r,forcesRowSecurity:s.force,hasChildren:s.children===!0,hasParent:s.parent===!0,indexes:Number(s.indexes??(s.pk.length>0?1:0))})}return{table:(s,r)=>n.get(`${s}\0${r}`)}}function rt(t){return ot(t.map(e=>({schema:e.schema??"public",name:e.name,kind:"r",force:e.forcesRowSecurity??!1,pk:e.primaryKey,...e.identifying===void 0?{}:{identifying:e.identifying},...e.indexes===void 0?{}:{indexes:e.indexes},columns:Object.entries(e.columns).map(([n,s])=>({name:n,type:s,enum:e.enums?.includes(n)??!1,array:!1}))})))}var B="access",ge="palbase access",Me="2",oe=["!access_fresh","!access_forget","!access_move","!access_empty"],it=[...oe].sort((t,e)=>Buffer.from(t)<Buffer.from(e)?-1:1).at(-1),at=t=>`(${t}.tgtype & 66) = 0 AND ${t}.tgname COLLATE "C" < ${$(it)}`,we={authenticated:"authenticated",service:"service_role"},ct="^-?[0-9]{1,18}$",Ue="^[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}$",_e=256,q={unknown:"PA001",noObject:"PA002",badId:"PA003",tooMany:"PA004",notTaken:"PA005",notAllowed:"PA006"},K="SET search_path = pg_catalog, pg_temp";function ve(t=we){let e=_(B),n=`${_(t.authenticated)}, ${_(t.service)}`,s=_(t.service);return[`CREATE SCHEMA IF NOT EXISTS ${e}`,`COMMENT ON SCHEMA ${e} IS ${$(ge)}`,`CREATE TABLE IF NOT EXISTS ${e}.relationships (
10
- object_type text NOT NULL, object_id text NOT NULL, relation text NOT NULL,
11
- subject_type text NOT NULL, subject_id text NOT NULL,
12
- created_at timestamptz NOT NULL DEFAULT now(),
13
- given_in xid8 NOT NULL DEFAULT pg_current_xact_id(),
14
- PRIMARY KEY (object_type, object_id, relation, subject_type, subject_id))`,`ALTER TABLE ${e}.relationships ADD COLUMN IF NOT EXISTS given_in xid8 NOT NULL DEFAULT pg_current_xact_id()`,`CREATE INDEX IF NOT EXISTS relationships_by_subject ON ${e}.relationships (subject_type, subject_id, object_type, relation, object_id)`,`CREATE TABLE IF NOT EXISTS ${e}.history (
15
- id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
16
- at timestamptz NOT NULL DEFAULT now(),
17
- action text NOT NULL CHECK (action IN ('grant', 'revoke')),
18
- object_type text NOT NULL, object_id text NOT NULL, relation text NOT NULL,
19
- subject_type text NOT NULL, subject_id text NOT NULL,
20
- actor text)`,`CREATE INDEX IF NOT EXISTS history_by_object ON ${e}.history (object_type, object_id, id DESC)`,`CREATE INDEX IF NOT EXISTS history_by_subject ON ${e}.history (subject_type, subject_id, id DESC)`,`CREATE TABLE IF NOT EXISTS ${e}.objects_touched (
21
- object_type text NOT NULL, object_id text NOT NULL, touched xid8 NOT NULL DEFAULT pg_current_xact_id(),
22
- PRIMARY KEY (object_type, object_id))`,`DROP FUNCTION IF EXISTS ${e}.moved_objects() CASCADE`,`DROP TABLE IF EXISTS ${e}.moves`,`CREATE TABLE IF NOT EXISTS ${e}.schemas (
23
- digest text PRIMARY KEY, text text NOT NULL, engine text NOT NULL,
24
- applied_at timestamptz NOT NULL DEFAULT now(), applied_by text NOT NULL DEFAULT session_user,
25
- active boolean NOT NULL DEFAULT false)`,`CREATE OR REPLACE FUNCTION ${e}.may_name_a_subject() RETURNS boolean LANGUAGE sql STABLE ${K} AS ${L(`
26
- SELECT pg_has_role(o.role, ${$(t.service)}, 'MEMBER')
27
- OR EXISTS (SELECT 1 FROM pg_namespace n WHERE n.nspname = ${$(B)} AND pg_has_role(o.role, n.nspowner, 'MEMBER'))
28
- FROM (SELECT CASE WHEN current_setting('role') IN ('none', '') THEN session_user ELSE current_setting('role')::name END AS role) o`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject() RETURNS text LANGUAGE sql STABLE ${K} AS ${L(`
29
- SELECT CASE WHEN ${e}.may_name_a_subject()
30
- THEN coalesce(nullif(current_setting('access.subject', true), ''), c.sub)
31
- ELSE c.sub END
32
- FROM (SELECT nullif((nullif(current_setting('request.jwt.claims', true), ''))::jsonb ->> 'sub', '') AS sub) c`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject_uuid() RETURNS uuid LANGUAGE sql STABLE ${K} AS ${L(`
33
- SELECT CASE WHEN s ~ ${$(Ue)} THEN s::uuid END FROM (SELECT ${e}.subject() AS s) q`)}`,`CREATE OR REPLACE FUNCTION ${e}.subject_int() RETURNS bigint LANGUAGE sql STABLE ${K} AS ${L(`
34
- SELECT CASE WHEN s ~ ${$(ct)} THEN s::bigint END FROM (SELECT ${e}.subject() AS s) q`)}`,`CREATE OR REPLACE FUNCTION ${e}.act_as(subject text) RETURNS void LANGUAGE plpgsql VOLATILE ${K} AS ${L(`
35
- BEGIN
36
- IF NOT ${e}.may_name_a_subject() THEN
37
- RAISE EXCEPTION USING ERRCODE = ${$(q.notAllowed)}, MESSAGE = 'this role asks for itself alone: it cannot ask as another subject';
38
- END IF;
39
- PERFORM set_config('access.subject', coalesce(subject, ''), true);
40
- END`)}`,`CREATE OR REPLACE FUNCTION ${e}.touch(object_type text, object_ids text[]) RETURNS void LANGUAGE sql VOLATILE SECURITY DEFINER ${K} AS ${L(`
41
- INSERT INTO ${e}.objects_touched (object_type, object_id, touched)
42
- SELECT $1, i, pg_current_xact_id() FROM unnest($2) AS i WHERE i IS NOT NULL ORDER BY 2
43
- ON CONFLICT (object_type, object_id) DO UPDATE SET touched = excluded.touched`)}`,`CREATE OR REPLACE FUNCTION ${e}.older_snapshot() RETURNS boolean LANGUAGE sql STABLE ${K} AS ${L(`
44
- SELECT current_setting('transaction_isolation') NOT IN ('read committed', 'read uncommitted')`)}`,`CREATE OR REPLACE FUNCTION ${e}.refuse(state text, message text) RETURNS boolean LANGUAGE plpgsql STABLE ${K} AS ${L(`
45
- BEGIN RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; END`)}`,`CREATE OR REPLACE FUNCTION ${e}.refuse_text(state text, message text) RETURNS text LANGUAGE plpgsql STABLE ${K} AS ${L(`
46
- BEGIN RAISE EXCEPTION USING ERRCODE = state, MESSAGE = message; END`)}`,`CREATE OR REPLACE FUNCTION ${e}.record() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${K} AS ${L(`
47
- DECLARE who text := coalesce(nullif(current_setting('access.actor', true), ''), ${e}.subject(), session_user::text);
48
- BEGIN
49
- IF TG_OP <> 'INSERT' THEN
50
- INSERT INTO ${e}.history (action, object_type, object_id, relation, subject_type, subject_id, actor)
51
- VALUES ('revoke', OLD.object_type, OLD.object_id, OLD.relation, OLD.subject_type, OLD.subject_id, who);
52
- END IF;
53
- IF TG_OP <> 'DELETE' THEN
54
- INSERT INTO ${e}.history (action, object_type, object_id, relation, subject_type, subject_id, actor)
55
- VALUES ('grant', NEW.object_type, NEW.object_id, NEW.relation, NEW.subject_type, NEW.subject_id, who);
56
- END IF;
57
- RETURN NULL;
58
- END`)}`,`CREATE OR REPLACE TRIGGER record AFTER INSERT OR UPDATE OR DELETE ON ${e}.relationships FOR EACH ROW EXECUTE FUNCTION ${e}.record()`,`CREATE OR REPLACE FUNCTION ${e}.forget_object() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${K} AS ${L(`
59
- DECLARE gone text := to_jsonb(OLD) ->> TG_ARGV[1]; was text := current_setting('access.actor', true);
60
- BEGIN
61
- IF gone IS NULL THEN RETURN NULL; END IF;
62
- IF ${e}.older_snapshot() THEN PERFORM ${e}.touch(TG_ARGV[0], ARRAY[gone]); END IF;
63
- PERFORM set_config('access.actor', 'access: row deleted', true);
64
- DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = gone;
65
- DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = gone;
66
- DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0] AND object_id = gone;
67
- PERFORM set_config('access.actor', coalesce(was, ''), true);
68
- RETURN NULL;
69
- END`)}`,`CREATE OR REPLACE FUNCTION ${e}.move_object() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${K} AS ${L(`
70
- DECLARE old_id text := to_jsonb(OLD) ->> TG_ARGV[1]; new_id text := to_jsonb(NEW) ->> TG_ARGV[1]; was text := current_setting('access.actor', true);
71
- BEGIN
72
- IF old_id IS NULL OR new_id IS NULL OR old_id = new_id THEN RETURN NULL; END IF;
73
- IF ${e}.older_snapshot() THEN PERFORM ${e}.touch(TG_ARGV[0], ARRAY[old_id, new_id]); END IF;
74
- PERFORM set_config('access.actor', 'access: id used again', true);
75
- DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = new_id;
76
- DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = new_id;
77
- PERFORM set_config('access.actor', 'access: key changed', true);
78
- UPDATE ${e}.relationships SET object_id = new_id WHERE object_type = TG_ARGV[0] AND object_id = old_id;
79
- UPDATE ${e}.relationships SET subject_id = new_id WHERE subject_type = TG_ARGV[0] AND subject_id = old_id;
80
- DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0] AND object_id = new_id;
81
- UPDATE ${e}.objects_touched SET object_id = new_id WHERE object_type = TG_ARGV[0] AND object_id = old_id;
82
- PERFORM set_config('access.actor', coalesce(was, ''), true);
83
- RETURN NULL;
84
- END`)}`,`CREATE OR REPLACE FUNCTION ${e}.fresh_objects() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${K} AS ${L(`
85
- DECLARE made text := to_jsonb(NEW) ->> TG_ARGV[1]; cur xid8 := pg_current_xact_id(); was text := current_setting('access.actor', true);
86
- BEGIN
87
- IF made IS NULL THEN RETURN NULL; END IF;
88
- IF NOT EXISTS (SELECT 1 FROM ${e}.relationships r WHERE r.object_type = TG_ARGV[0] AND r.object_id = made AND r.given_in <> cur)
89
- AND NOT EXISTS (SELECT 1 FROM ${e}.relationships r WHERE r.subject_type = TG_ARGV[0] AND r.subject_id = made AND r.given_in <> cur) THEN
90
- RETURN NULL;
91
- END IF;
92
- PERFORM set_config('access.actor', 'access: id used again', true);
93
- DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0] AND object_id = made AND given_in <> cur;
94
- DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0] AND subject_id = made AND given_in <> cur;
95
- PERFORM set_config('access.actor', coalesce(was, ''), true);
96
- RETURN NULL;
97
- END`)}`,`CREATE OR REPLACE FUNCTION ${e}.forget_all() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER ${K} AS ${L(`
98
- DECLARE was text := current_setting('access.actor', true);
99
- BEGIN
100
- IF ${e}.older_snapshot() THEN
101
- RAISE EXCEPTION USING ERRCODE = '55000', MESSAGE = format('TRUNCATE of the table of type %s: in a READ COMMITTED transaction \u2014 by an older snapshot, relationships given since could not be taken with its rows', TG_ARGV[0]);
102
- END IF;
103
- PERFORM set_config('access.actor', 'access: table emptied', true);
104
- DELETE FROM ${e}.relationships WHERE object_type = TG_ARGV[0];
105
- DELETE FROM ${e}.relationships WHERE subject_type = TG_ARGV[0];
106
- DELETE FROM ${e}.objects_touched WHERE object_type = TG_ARGV[0];
107
- PERFORM set_config('access.actor', coalesce(was, ''), true);
108
- RETURN NULL;
109
- END`)}`,`CREATE OR REPLACE FUNCTION ${e}.binding_guard() RETURNS trigger LANGUAGE plpgsql ${K} AS ${L(`
110
- DECLARE i int;
111
- BEGIN
112
- FOR i IN 1 .. TG_NARGS - 1 LOOP
113
- IF NEW.object_type = TG_ARGV[i] OR NEW.subject_type = TG_ARGV[i] THEN
114
- RAISE EXCEPTION USING ERRCODE = '55000', MESSAGE = format('type %s is being given a table by the deploy of version %s: its relationships can be given once that deploy completes', TG_ARGV[i], TG_ARGV[0]);
115
- END IF;
116
- END LOOP;
117
- RETURN NEW;
118
- END`)}`,`CREATE OR REPLACE FUNCTION ${e}.forget_subject(subject text) RETURNS bigint LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${K} AS ${L(`
119
- DECLARE n bigint; was text := current_setting('access.actor', true);
120
- BEGIN
121
- PERFORM set_config('access.actor', 'access: subject deleted', true);
122
- DELETE FROM ${e}.relationships WHERE subject_type = 'user' AND subject_id = $1;
123
- GET DIAGNOSTICS n = ROW_COUNT;
124
- PERFORM set_config('access.actor', coalesce(was, ''), true);
125
- RETURN n;
126
- END`)}`,`CREATE OR REPLACE VIEW ${e}.mine WITH (security_barrier = true) AS
127
- SELECT object_type, object_id, relation FROM ${e}.relationships
128
- WHERE subject_type = 'user' AND subject_id = (SELECT ${e}.subject())`,`DROP FUNCTION IF EXISTS ${e}.speaks(text)`,`REVOKE ALL ON SCHEMA ${e} FROM PUBLIC`,`GRANT USAGE ON SCHEMA ${e} TO ${n}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${e} FROM PUBLIC`,`REVOKE ALL ON ${e}.relationships, ${e}.history, ${e}.schemas, ${e}.objects_touched, ${e}.mine FROM ${n}`,`GRANT SELECT ON ${e}.mine TO ${n}`,`GRANT SELECT ON ${e}.relationships, ${e}.history, ${e}.schemas TO ${s}`,`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${e} FROM PUBLIC`,`REVOKE ALL ON FUNCTION ${e}.subject(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text), ${e}.act_as(text), ${e}.forget_subject(text), ${e}.record(), ${e}.forget_object(), ${e}.move_object(), ${e}.fresh_objects(), ${e}.forget_all(), ${e}.binding_guard(), ${e}.touch(text, text[]), ${e}.older_snapshot() FROM ${n}`,`GRANT EXECUTE ON FUNCTION ${e}.subject(), ${e}.subject_uuid(), ${e}.subject_int(), ${e}.may_name_a_subject(), ${e}.refuse(text, text), ${e}.refuse_text(text, text) TO ${n}`,`GRANT EXECUTE ON FUNCTION ${e}.act_as(text), ${e}.forget_subject(text) TO ${s}`]}import{createHash as Ut,randomUUID as Nn}from"node:crypto";var lt=1e4,vt=1e5,Pt=1e4,Gt=1e6,ue=96*1024,xe=100,J="SET search_path = pg_catalog, pg_temp",O=_(B),Ht=["text","uuid","int"],Ee=(t,e)=>t==="int"?`(CASE WHEN ${e} ~ ${$(ct)} THEN (${e})::bigint END)`:t==="uuid"?`(CASE WHEN ${e} ~ ${$(Ue)} THEN (${e})::uuid END)`:e,wn=t=>t==="int"?`(SELECT ${O}.subject_int())`:t==="uuid"?`(SELECT ${O}.subject_uuid())`:`(SELECT ${O}.subject())`;function _n(t,e){let n=new Map;for(let s of t.types.values()){if(!s.table){n.set(s.name,{name:s.name,model:s,table:null,family:"text",idType:"text"});continue}let r=`${s.table.schema}.${s.table.name}`,o=e.table(s.table.schema,s.table.name);if(!o)throw new T("unknown_table",`type ${s.name}: there is no table ${r}`);if(o.kind==="p"||o.hasChildren||o.hasParent)throw new T("not_supported",`type ${s.name}: ${r} is partitioned, a partition, or tied to another table by inheritance; a type's table is one plain table (its rows could be read past its rules through the other)`);if(o.kind!=="r")throw new T("not_supported",`type ${s.name}: ${r} is not a table (a view or a foreign table cannot carry a type)`);if(o.indexes>tt)throw new T("too_large",`type ${s.name}: ${r} has ${o.indexes} indexes; a type's table has at most ${tt} \u2014 the database reads every one of them for each lookup through the table, on every statement a rule guards`);if(o.forcesRowSecurity)throw new T("forced_row_security",`type ${s.name}: ${r} forces row-level security on its owner (FORCE ROW LEVEL SECURITY); access reads a type's table as its owner, so it would read nothing`);let l=s.table.key;if(l===null){if(o.primaryKey.length!==1){let h=o.primaryKey.length===0?"has no primary key":`has a primary key of ${o.primaryKey.length} columns`;throw new T("key_not_supported",`type ${s.name}: ${r} ${h}; name one column that identifies a row \u2014 table ${s.table.name} key <column>`)}l=o.primaryKey[0]}let a=o.columns.get(l);if(!a)throw new T("unknown_column",`type ${s.name}: ${r} has no column "${l}"`);if(!o.identifying.includes(l))throw new T("key_not_supported",`type ${s.name}: ${r}.${l} does not identify a row by itself at every moment; an object's key is NOT NULL and unique alone \u2014 the primary key, or a unique constraint or index of that column and no other \u2014 and not DEFERRABLE`);if(!a.family||!Ht.includes(a.family))throw new T("key_not_supported",`type ${s.name}: the key ${r}.${l} is ${a.type}; an object's id is text, a uuid or an integer`);let c=a.family;n.set(s.name,{name:s.name,model:s,table:{sql:st(o.schema,o.name),schema:o.schema,name:o.name,key:l,info:o},family:c,idType:c==="int"?"bigint":c})}for(let s of n.values())for(let r of s.model.relations.values()){if(r.kind!=="column")continue;let o=s.table.info,l=`${o.schema}.${o.name}`,a=`relation ${s.name}.${r.name}`,c=o.columns.get(r.column);if(!c)throw new T("unknown_column",`${a}: ${l} has no column "${r.column}"`,r.line);if(!c.family||!Ht.includes(c.family))throw new T("type_mismatch",`${a}: ${l}.${r.column} is ${c.type}; an id is text, a uuid or an integer`,r.line);if(r.subject!==z){let h=n.get(r.subject);if(h.table&&h.family!==c.family)throw new T("type_mismatch",`${a}: ${l}.${r.column} is ${c.type}, and the key of type ${h.name} is ${h.table.info.columns.get(h.table.key)?.type}`,r.line)}r.where&&ut(r.where,o,a,r.line)}return n}function ut(t,e,n,s){if("parts"in t){for(let h of t.parts)ut(h,e,n,s);return}if(t.op==="not")return ut(t.part,e,n,s);let r=`${e.schema}.${e.name}`,o=e.columns.get(t.column);if(!o)throw new T("unknown_column",`${n}: its condition reads "${t.column}", which ${r} does not have`,s);if(t.op==="null")return;let l=o.family;if(!l)throw new T("not_supported",`${n}: its condition compares ${r}.${t.column}, which is ${o.type}; a condition compares text, an enum, a uuid, a number or a boolean`,s);let a=t.op==="in"?t.values:[t.value];if(t.op==="cmp"&&t.cmp!=="="&&t.cmp!=="!="&&l!=="int"&&l!=="numeric")throw new T("not_supported",`${n}: "${t.column} ${t.op==="cmp"?t.cmp:""}" \u2014 only a number is compared by order; ${r}.${t.column} is ${o.type}`,s);for(let h of a){let C=l==="bool"?"boolean":l==="int"||l==="numeric"?"number":"string";if(h.t!==C)throw new T("type_mismatch",`${n}: ${r}.${t.column} is ${o.type}; its condition compares it with ${h.t==="string"?"a text":h.t==="number"?"a number":"true or false"}`,s);if(l==="int"&&h.t==="number"&&!/^-?[0-9]{1,18}$/.test(h.v))throw new T("type_mismatch",`${n}: ${r}.${t.column} is ${o.type}; ${h.v} is not a whole number it can hold`,s);if(l==="uuid"&&h.t==="string"&&!new RegExp(Ue).test(h.v))throw new T("type_mismatch",`${n}: ${r}.${t.column} is a uuid; '${h.v}' is not one`,s)}}var Kt=t=>t.t==="string"?$(t.v):t.t==="number"?t.v:t.v?"true":"false";function he(t,e){return"parts"in t?`(${t.parts.map(n=>he(n,e)).join(t.op==="and"?" AND ":" OR ")})`:t.op==="not"?`(NOT ${he(t.part,e)})`:t.op==="null"?`(${e(t.column)} IS ${t.negated?"NOT ":""}NULL)`:t.op==="in"?`(${e(t.column)} IN (${t.values.map(Kt).join(", ")}))`:`(${e(t.column)} ${t.cmp==="!="?"<>":t.cmp} ${Kt(t.value)})`}function qt(t,e){return`SELECT g.tgname INTO early FROM pg_catalog.pg_trigger g JOIN pg_catalog.pg_proc p ON p.oid = g.tgfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
129
- WHERE g.tgrelid = ${$(t)}::pg_catalog.regclass AND NOT g.tgisinternal AND n.nspname <> ${$(B)} AND ${at("g")}
130
- ORDER BY g.tgname COLLATE "C" LIMIT 1;
131
- IF early IS NOT NULL THEN
132
- RAISE EXCEPTION '% has a trigger of its own, "%", that fires after a change and is named to come before access'' (${it}): rename it to come after, or make it fire before the change', ${$(e)}, early;
133
- END IF;`}function Pe(t,e,n,s={}){let r={...we,...s.roles},o=s.rows!==!1,l=_n(t,e),a=`${B}_${Nn().replaceAll("-","")}`,c=_(a),h=`${_(r.authenticated)}, ${_(r.service)}`,C=_(r.service),M=new Map,k=(i,u)=>{let y=M.get(i);if(y!==void 0&&y!==u)throw new T("invalid_name",`${u} and ${y} would have one name in the database (${i})`);return M.set(i,u),i},P=i=>i.length<=Ne?i:`${i.slice(0,Ne-17)}~${Ut("sha256").update(i).digest("hex").slice(0,16)}`,m=(i,u)=>k(`${i}__${Fe(u)}`,`${i}.${u}`),j=(i,u)=>`${c}.${_(m(i,u))}`,G=(i,u,y)=>k(P(`${i}:${u}->${y}`),`the arrow ${i}.${u}->${y}`),V=(i,u)=>`${c}.${_(k(P(`${i}:${u}?`),`who holds ${i}.${u}`))}`,v=i=>l.get(i),f=(i,u)=>i.table?`(${u.key})::text`:u.key,g=(i,u,y)=>{if("parts"in u)return`(${u.parts.map(S=>g(i,S,y)).join(u.op==="union"?" OR ":" AND ")})`;if(u.op==="exclude")return`(${g(i,u.base,y)} AND (${g(i,u.minus,y)}) IS NOT TRUE)`;if(u.op==="ref"){let S=i.model.permissions.get(u.name);return S?g(i,S.expr,y):N(i,i.model.relations.get(u.name),y)}let w=i.model.relations.get(u.relation);if(w.kind==="column"){let S=v(w.subject),R=`EXISTS (SELECT 1 FROM ${j(S.name,u.name)} x WHERE x.id = ${S.table?y.col(w.column):`(${y.col(w.column)})::text`})`;return w.where?`(${R} AND ${he(w.where,y.col)})`:R}return`EXISTS (SELECT 1 FROM ${c}.${_(G(i.name,w.name,u.name))} h WHERE h.object_id = ${f(i,y)})`},N=(i,u,y)=>{if(u.kind==="stored")return`EXISTS (SELECT 1 FROM ${O}.mine m WHERE m.object_type = ${$(i.name)} AND m.relation = ${$(u.name)} AND m.object_id = ${f(i,y)})`;let w=i.table.info.columns.get(u.column)?.family,S=`${y.col(u.column)} = ${wn(w)}`;return u.where?`(${S} AND ${he(u.where,y.col)})`:`(${S})`},p=(i,u)=>{if("parts"in u)return u.parts.flatMap(S=>p(i,S));if(u.op==="exclude")return[...p(i,u.base),...p(i,u.minus)];let y=i.table?"($1)::text":"$1";if(u.op==="ref"){let S=i.model.permissions.get(u.name);if(S)return p(i,S.expr);let R=i.model.relations.get(u.name);if(R.kind==="stored")return[`SELECT m.subject_id FROM ${O}.relationships m WHERE m.object_type = ${$(i.name)} AND m.object_id = ${y} AND m.relation = ${$(R.name)} AND m.subject_type = 'user'`];let D=i.table,H=R.where?` AND ${he(R.where,Y=>`t.${_(Y)}`)}`:"";return[`SELECT (t.${_(R.column)})::text FROM ${D.sql} AS t WHERE t.${_(D.key)} = $1 AND t.${_(R.column)} IS NOT NULL${H}`]}let w=i.model.relations.get(u.relation);if(w.kind==="column"){let S=i.table,R=v(w.subject),D=R.table?`t.${_(w.column)}`:`(t.${_(w.column)})::text`,H=w.where?` AND ${he(w.where,Y=>`t.${_(Y)}`)}`:"";return[`SELECT w FROM ${S.sql} AS t CROSS JOIN LATERAL ${V(R.name,u.name)}(${D}) AS w WHERE t.${_(S.key)} = $1${H}`]}return se(w).map(S=>{let R=v(S);return`SELECT w FROM ${O}.relationships e CROSS JOIN LATERAL ${V(R.name,u.name)}(${Ee(R.family,"e.subject_id")}) AS w WHERE e.object_type = ${$(i.name)} AND e.object_id = ${y} AND e.relation = ${$(w.name)} AND e.subject_type = ${$(R.name)} AND ${c}.walked(e.subject_id)`})},E=[`CREATE SCHEMA IF NOT EXISTS ${c}`];E.push(`CREATE OR REPLACE FUNCTION ${c}.walked(text) RETURNS boolean LANGUAGE plpgsql VOLATILE ${J} AS ${L(`
134
- DECLARE n bigint := coalesce(nullif(pg_catalog.current_setting('access.walked', true), ''), '0')::bigint + 1;
135
- BEGIN
136
- IF n > ${Pt} THEN
137
- PERFORM ${O}.refuse(${$(q.tooMany)}, 'more than ${Pt} objects related to this one would be walked to say who holds it: ask whether one subject holds it (check) instead of who does');
138
- END IF;
139
- PERFORM pg_catalog.set_config('access.walked', n::text, true);
140
- RETURN true;
141
- END`)}`);let d=[],b=new Set,A=new Set,I=i=>i.op==="arrow"?[i]:i.op==="ref"?[]:i.op==="exclude"?[...I(i.base),...I(i.minus)]:i.parts.flatMap(I);for(let{type:i,name:u}of t.order){let y=v(i),w=y.model.relations.get(u);if(w&&!Te(w))continue;let S=y.model.permissions.get(u)?.expr??{op:"ref",name:u};for(let H of I(S)){let Y=y.model.relations.get(H.relation),F=G(y.name,Y.name,H.name);if(Y.kind!=="stored"||b.has(F))continue;b.add(F);let We=se(Y).map(ae=>{let ne=v(ae);return`(e.subject_type = ${$(ne.name)} AND EXISTS (SELECT 1 FROM ${j(ne.name,H.name)} x WHERE x.id = ${Ee(ne.family,"e.subject_id")}))`});E.push(`CREATE OR REPLACE VIEW ${c}.${_(F)} WITH (security_barrier = true) AS
142
- SELECT e.object_id FROM ${O}.relationships e
143
- WHERE e.object_type = ${$(y.name)} AND e.relation = ${$(Y.name)} AND (${We.join(" OR ")}) IS TRUE`)}let R=y.table?{col:H=>`t.${_(H)}`,key:`t.${_(y.table.key)}`}:{col:()=>"",key:"t.k"},D=y.table?`${y.table.sql} AS t`:`(SELECT DISTINCT r.object_id AS k FROM ${O}.relationships r WHERE r.object_type = ${$(y.name)}) AS t`;E.push(`CREATE OR REPLACE VIEW ${j(i,u)} WITH (security_barrier = true) AS SELECT ${R.key} AS id FROM ${D} WHERE (${g(y,S,R)}) IS TRUE`),E.push(`CREATE OR REPLACE FUNCTION ${V(i,u)}(${y.idType}) RETURNS SETOF text LANGUAGE sql STABLE SECURITY DEFINER ${J} AS ${L(`
144
- SELECT c.w FROM (
145
- ${p(y,S).join(`
146
- UNION ALL
147
- `)}
148
- ) AS c(w) LIMIT ${vt+1}`)}`),d.push({type:i,name:u,view:m(i,u),idType:y.table?y.table.info.columns.get(y.table.key)?.type:"text"})}let x=(i,u,y)=>`${y} = ${$(i.type)} AND ${u} = ${$(i.name)}`,U=(i,u)=>`'type ' || coalesce(${u}, '(null)') || ' has no relation or permission ' || coalesce(${i}, '(null)')`,ee=(i,u)=>d.length===0?u:`${d.map((y,w)=>`${w===0?"IF":"ELSIF"} ${x(y,"$1","$2")} THEN
149
- ${i(y)}`).join(`
150
- `)}
151
- ELSE
152
- ${u}
153
- END IF;`;E.push(`CREATE OR REPLACE FUNCTION ${c}.can(permission text, object_type text, object_id text) RETURNS boolean LANGUAGE plpgsql STABLE ${J} AS ${L(`
154
- BEGIN
155
- ${ee(i=>`RETURN EXISTS (SELECT 1 FROM ${j(i.type,i.name)} v WHERE v.id = ${Ee(v(i.type).family,"$3")});`,`RETURN ${O}.refuse(${$(q.unknown)}, ${U("$1","$2")});`)}
156
- END`)}`,`CREATE OR REPLACE FUNCTION ${c}.my_objects(permission text, object_type text) RETURNS SETOF text LANGUAGE plpgsql STABLE ${J} AS ${L(`
157
- BEGIN
158
- ${ee(i=>`RETURN QUERY SELECT (v.id)::text FROM ${j(i.type,i.name)} v;`,`PERFORM ${O}.refuse(${$(q.unknown)}, ${U("$1","$2")});`)}
159
- RETURN;
160
- END`)}`,`CREATE OR REPLACE FUNCTION ${c}.check(subject text, permission text, object_type text, object_id text) RETURNS boolean LANGUAGE plpgsql VOLATILE ${J} AS ${L(`
161
- DECLARE was text := current_setting('access.subject', true); answer boolean;
162
- BEGIN
163
- IF $1 IS NULL OR $1 = '' THEN RETURN false; END IF;
164
- PERFORM ${O}.act_as($1);
165
- answer := ${c}.can($2, $3, $4);
166
- PERFORM set_config('access.subject', coalesce(was, ''), true);
167
- RETURN answer;
168
- END`)}`,`CREATE OR REPLACE FUNCTION ${c}.objects(subject text, permission text, object_type text) RETURNS SETOF text LANGUAGE plpgsql VOLATILE ${J} AS ${L(`
169
- DECLARE was text := current_setting('access.subject', true);
170
- BEGIN
171
- IF $1 IS NULL OR $1 = '' THEN RETURN; END IF;
172
- PERFORM ${O}.act_as($1);
173
- RETURN QUERY SELECT o FROM ${c}.my_objects($2, $3) AS o;
174
- PERFORM set_config('access.subject', coalesce(was, ''), true);
175
- RETURN;
176
- END`)}`,`CREATE OR REPLACE FUNCTION ${c}.subjects(permission text, object_type text, object_id text) RETURNS SETOF text LANGUAGE plpgsql VOLATILE ${J} AS ${L(`
177
- DECLARE named text[]; seen bigint := 0; walked bigint; c text;
178
- BEGIN
179
- PERFORM pg_catalog.set_config('access.walked', '0', true);
180
- ${ee(i=>`SELECT array_agg(DISTINCT w) FILTER (WHERE w IS NOT NULL AND w <> ''), count(*) INTO named, seen FROM ${V(i.type,i.name)}(${Ee(v(i.type).family,"$3")}) AS w;`,`PERFORM ${O}.refuse(${$(q.unknown)}, ${U("$1","$2")});`)}
181
- IF seen > ${vt} OR coalesce(array_length(named, 1), 0) > ${lt} THEN
182
- PERFORM ${O}.refuse(${$(q.tooMany)}, 'more than ${lt} subjects are related to this object: ask whether one subject holds it (check) instead of who does');
183
- END IF;
184
- -- Each one is checked in turn, and a check reads the related objects again.
185
- walked := coalesce(nullif(pg_catalog.current_setting('access.walked', true), ''), '0')::bigint;
186
- IF coalesce(array_length(named, 1), 0) * (walked + 1) > ${Gt} THEN
187
- PERFORM ${O}.refuse(${$(q.tooMany)}, pg_catalog.format('saying who holds it would check %s subjects, each through %s related objects: more than ${Gt} together; ask whether one subject holds it (check) instead of who does', array_length(named, 1), walked));
188
- END IF;
189
- FOREACH c IN ARRAY coalesce(named, '{}'::text[]) LOOP
190
- IF ${c}.check(c, $1, $2, $3) THEN RETURN NEXT c; END IF;
191
- END LOOP;
192
- RETURN;
193
- END`)}`);let Se=[...l.values()].flatMap(i=>[...i.model.relations.values()].flatMap(u=>u.kind==="stored"?u.subjects.map(y=>`(${$(i.name)}, ${$(u.name)}, ${$(y)})`):[])),Ce=(i,u,y)=>Se.length===0?"false":`(${i}, ${u}, ${y}) IN (${Se.join(", ")})`,ft="'type ' || coalesce($1, '(null)') || ' keeps no relation ' || coalesce($3, '(null)') || ' that takes ' || coalesce($4, '(null)')",gt=i=>`${O}.refuse(${$(q.badId)}, ${$(`${i} is empty or longer than ${_e} characters`)})`,Et=[...l.values()].filter(i=>i.table).map(i=>$(i.name)),Ke=i=>Et.length===0?"false":`${i} IN (${Et.join(", ")})`,Jt=`IF ${Ke("$4")} AND ($4, s) < ($1, o) THEN PERFORM ${O}.touch($4, ARRAY[s]); END IF;
194
- IF ${Ke("$1")} THEN PERFORM ${O}.touch($1, ARRAY[o]); END IF;
195
- IF ${Ke("$4")} AND ($4, s) > ($1, o) THEN PERFORM ${O}.touch($4, ARRAY[s]); END IF;`;E.push(`CREATE OR REPLACE FUNCTION ${c}.object(object_type text, object_id text) RETURNS text LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${J} AS ${L(`
196
- DECLARE canon text;
197
- BEGIN
198
- ${[...l.values()].map(i=>i.table?`IF $1 = ${$(i.name)} THEN
199
- SELECT (t.${_(i.table.key)})::text INTO canon FROM ${i.table.sql} AS t WHERE t.${_(i.table.key)} = ${Ee(i.family,"$2")} FOR KEY SHARE;
200
- IF canon IS NULL THEN PERFORM ${O}.refuse(${$(q.noObject)}, 'there is no ' || $1 || ' ' || coalesce($2, '(null)')); END IF;
201
- RETURN canon;
202
- END IF;`:`IF $1 = ${$(i.name)} THEN
203
- IF $2 IS NULL OR $2 = '' OR length($2) > ${_e} THEN PERFORM ${gt(`the id of a ${i.name}`)}; END IF;
204
- RETURN $2;
205
- END IF;`).join(`
206
- `)}
207
- PERFORM ${O}.refuse(${$(q.unknown)}, 'there is no type ' || coalesce($1, '(null)'));
208
- RETURN NULL;
209
- END`)}`,`CREATE OR REPLACE FUNCTION ${c}.grant(object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL) RETURNS boolean LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${J} AS ${L(`
210
- DECLARE o text; s text; n bigint; was text := current_setting('access.actor', true);
211
- BEGIN
212
- IF (${Ce("$1","$3","$4")}) IS NOT TRUE THEN PERFORM ${O}.refuse(${$(q.notTaken)}, ${ft}); END IF;
213
- o := ${c}.object($1, $2);
214
- IF $4 = 'user' THEN
215
- IF $5 IS NULL OR $5 = '' OR length($5) > ${_e} THEN PERFORM ${gt("a subject's id")}; END IF;
216
- s := $5;
217
- ELSE
218
- s := ${c}.object($4, $5);
219
- END IF;
220
- -- The rows it is given on, met by whatever takes their relationships away by a snapshot that cannot see it.
221
- ${Jt}
222
- IF $6 IS NOT NULL AND $6 <> '' THEN PERFORM set_config('access.actor', $6, true); END IF;
223
- INSERT INTO ${O}.relationships (object_type, object_id, relation, subject_type, subject_id) VALUES ($1, o, $3, $4, s) ON CONFLICT DO NOTHING;
224
- GET DIAGNOSTICS n = ROW_COUNT;
225
- PERFORM set_config('access.actor', coalesce(was, ''), true);
226
- RETURN n > 0;
227
- END`)}`,`CREATE OR REPLACE FUNCTION ${c}.canon(object_type text, object_id text) RETURNS text LANGUAGE sql STABLE ${J} AS ${L(`
228
- SELECT CASE
229
- ${[...l.values()].map(i=>`WHEN $1 = ${$(i.name)} THEN ${i.table&&i.family!=="text"?`(${Ee(i.family,"$2")})::text`:"$2"}`).join(`
230
- `)}
231
- ELSE $2 END`)}`,`CREATE OR REPLACE FUNCTION ${c}.revoke(object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL) RETURNS boolean LANGUAGE plpgsql VOLATILE SECURITY DEFINER ${J} AS ${L(`
232
- DECLARE n bigint; was text := current_setting('access.actor', true);
233
- BEGIN
234
- IF (${Ce("$1","$3","$4")}) IS NOT TRUE THEN PERFORM ${O}.refuse(${$(q.notTaken)}, ${ft}); END IF;
235
- IF $6 IS NOT NULL AND $6 <> '' THEN PERFORM set_config('access.actor', $6, true); END IF;
236
- DELETE FROM ${O}.relationships r
237
- WHERE r.object_type = $1 AND r.object_id = ${c}.canon($1, $2) AND r.relation = $3 AND r.subject_type = $4
238
- AND r.subject_id = CASE WHEN $4 = 'user' THEN $5 ELSE ${c}.canon($4, $5) END;
239
- GET DIAGNOSTICS n = ROW_COUNT;
240
- PERFORM set_config('access.actor', coalesce(was, ''), true);
241
- RETURN n > 0;
242
- END`)}`),E.push(`REVOKE ALL ON SCHEMA ${c} FROM PUBLIC, ${h}`,`GRANT USAGE ON SCHEMA ${c} TO ${h}`,`REVOKE ALL ON ALL TABLES IN SCHEMA ${c} FROM PUBLIC, ${h}`,...d.map(i=>`GRANT SELECT ON ${j(i.type,i.name)} TO ${h}`),`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${c} FROM PUBLIC, ${h}`,`GRANT EXECUTE ON FUNCTION ${c}.can(text, text, text), ${c}.my_objects(text, text) TO ${h}`,`GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA ${c} TO ${C}`);let me=[],qe=[],Ie=[],Le=[],re=(i,u,y,w,S)=>me.push(`CREATE OR REPLACE FUNCTION ${O}.${_(i)}(${u}) RETURNS ${y} LANGUAGE sql ${w} AS ${L(` SELECT ${c}.${_(i)}(${S}) `)}`);re("can","permission text, object_type text, object_id text","boolean","STABLE","$1, $2, $3"),re("my_objects","permission text, object_type text","SETOF text","STABLE","$1, $2"),re("check","subject text, permission text, object_type text, object_id text","boolean","VOLATILE","$1, $2, $3, $4"),re("objects","subject text, permission text, object_type text","SETOF text","VOLATILE","$1, $2, $3"),re("subjects","permission text, object_type text, object_id text","SETOF text","VOLATILE","$1, $2, $3"),re("grant","object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL","boolean","VOLATILE","$1, $2, $3, $4, $5, $6"),re("revoke","object_type text, object_id text, relation text, subject_type text, subject_id text, actor text DEFAULT NULL","boolean","VOLATILE","$1, $2, $3, $4, $5, $6");let Qt=`${O}.can(text, text, text), ${O}.my_objects(text, text), ${O}.check(text, text, text, text), ${O}.objects(text, text, text), ${O}.subjects(text, text, text), ${O}.grant(text, text, text, text, text, text), ${O}.revoke(text, text, text, text, text, text)`;me.push(`REVOKE ALL ON ALL FUNCTIONS IN SCHEMA ${O} FROM PUBLIC`,`REVOKE ALL ON FUNCTION ${Qt} FROM ${h}`,`GRANT EXECUTE ON FUNCTION ${O}.can(text, text, text), ${O}.my_objects(text, text) TO ${h}`,`GRANT EXECUTE ON FUNCTION ${O}.check(text, text, text, text), ${O}.objects(text, text, text), ${O}.subjects(text, text, text), ${O}.grant(text, text, text, text, text, text), ${O}.revoke(text, text, text, text, text, text) TO ${C}`);for(let i of d)s.aliases?.some(u=>u.name===i.view&&u.type!==i.idType)&&me.push(`DROP VIEW ${O}.${_(i.view)}`),me.push(`CREATE OR REPLACE VIEW ${O}.${_(i.view)} WITH (security_barrier = true) AS SELECT id FROM ${c}.${_(i.view)}`,`REVOKE ALL ON ${O}.${_(i.view)} FROM PUBLIC, ${h}`,`GRANT SELECT ON ${O}.${_(i.view)} TO ${h}`);let ht=[],$t=[];for(let i of l.values()){if(!i.table)continue;let u=i.table;ht.push({type:i.name,schema:u.schema,name:u.name,key:u.key});let y=`${u.schema}.${u.name}`;if(qe.push(`DO $guard$
243
- DECLARE early text;
244
- BEGIN
245
- IF EXISTS (SELECT 1 FROM pg_catalog.pg_trigger g JOIN pg_catalog.pg_proc p ON p.oid = g.tgfoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
246
- WHERE g.tgrelid = ${$(u.sql)}::pg_catalog.regclass AND NOT g.tgisinternal AND g.tgname IN (${oe.map(w=>$(w)).join(", ")}) AND n.nspname <> ${$(B)}) THEN
247
- RAISE EXCEPTION '% has a trigger of its own under a name access'' takes (${oe.join(", ")}): rename it', ${$(y)};
248
- END IF;
249
- ${qt(u.sql,y)}
250
- END $guard$`,...oe.map(w=>`DROP TRIGGER IF EXISTS ${_(w)} ON ${u.sql}`),`CREATE TRIGGER ${_("!access_fresh")} AFTER INSERT ON ${u.sql} FOR EACH ROW EXECUTE FUNCTION ${O}.fresh_objects(${$(i.name)}, ${$(u.key)})`,`CREATE TRIGGER ${_("!access_forget")} AFTER DELETE ON ${u.sql} FOR EACH ROW EXECUTE FUNCTION ${O}.forget_object(${$(i.name)}, ${$(u.key)})`,`CREATE TRIGGER ${_("!access_move")} AFTER UPDATE ON ${u.sql} FOR EACH ROW WHEN (OLD.${_(u.key)} IS DISTINCT FROM NEW.${_(u.key)}) EXECUTE FUNCTION ${O}.move_object(${$(i.name)}, ${$(u.key)})`,`CREATE TRIGGER ${_("!access_empty")} AFTER TRUNCATE ON ${u.sql} FOR EACH STATEMENT EXECUTE FUNCTION ${O}.forget_all(${$(i.name)})`,...oe.map(w=>`ALTER TABLE ${u.sql} ENABLE TRIGGER ${_(w)}`)),!(!o||i.model.rows.length===0)){Ie.push(`ALTER TABLE ${u.sql} ENABLE ROW LEVEL SECURITY`);for(let w of i.model.rows){let S=`access_${w.command}`,R=Rt(i.name,w.name),D=w.command==="insert"?"":` USING (${R})`,H=w.command==="insert"||w.command==="update"?` WITH CHECK (${R})`:"";Ie.push(`DO $guard$
251
- BEGIN
252
- IF EXISTS (SELECT 1 FROM pg_catalog.pg_policy p WHERE p.polrelid = ${$(u.sql)}::pg_catalog.regclass AND p.polname = ${$(S)}
253
- AND pg_catalog.obj_description(p.oid, 'pg_policy') IS DISTINCT FROM ${$(ge)}) THEN
254
- RAISE EXCEPTION '% has a policy of its own named % \u2014 the name a rows rule of the access schema takes: rename it', ${$(y)}, ${$(S)};
255
- END IF;
256
- END $guard$`,`DROP POLICY IF EXISTS ${_(S)} ON ${u.sql}`,`CREATE POLICY ${_(S)} ON ${u.sql} FOR ${w.command.toUpperCase()} TO ${_(r.authenticated)}${D}${H}`,`COMMENT ON POLICY ${_(S)} ON ${u.sql} IS ${$(ge)}`),$t.push({schema:u.schema,table:u.name,name:S,command:w.command});for(let Y of Tt(i.name,w.name))A.add(Y)}}}Le.push(`REVOKE ALL ON ALL TABLES IN SCHEMA ${c} FROM ${h}`,...d.map(i=>`GRANT SELECT ON ${j(i.type,i.name)} TO ${h}`));for(let i of new Set([...A,...(s.policies??[]).flatMap(u=>Tt(u.type,u.name))]))Le.push(`GRANT SELECT ON ${c}.${_(i)} TO ${_(r.authenticated)}`);let ke=Ut("sha256").update(JSON.stringify({engine:Me,roles:r,sql:[...ve(r),...E,...me.filter(i=>!i.startsWith("DROP VIEW ")),...qe,...Ie,...Le].map(i=>i.replaceAll(a,`${B}_`))})).digest("hex").slice(0,12),yt=`${B}_${ke}`,bt=[`UPDATE ${O}.schemas SET active = false WHERE active AND digest <> ${$(ke)}`,`INSERT INTO ${O}.schemas (digest, text, engine, active) VALUES (${$(ke)}, ${$(n)}, ${$(Me)}, true)
257
- ON CONFLICT (digest) DO UPDATE SET active = true, text = excluded.text, engine = excluded.engine, applied_at = now(), applied_by = session_user`],ie=i=>i.replaceAll(a,yt),Zt=d.filter(i=>v(i.type).table).map(i=>({type:i.type,name:i.name,sql:ie(Rt(i.type,i.name))})),be={watch:qe.map(ie),open:Le.map(ie),rows:Ie.map(ie),point:me.map(ie),record:bt};return{digest:ke,schema:yt,build:E.map(ie),...be,activate:[...be.point,...be.watch,...be.rows,...be.open,...bt],recheck:[...tn(),...nn()],tables:ht,names:d,policies:$t,predicates:Zt};function en(i){let u=[...[...l.values()].flatMap(R=>(o&&R.table?R.model.rows:[]).map(D=>({type:R.name,command:D.command,using:D.command==="insert"?null:[D.name],check:D.command==="insert"||D.command==="update"?[D.name]:null}))),...s.guards??[]],y=(R,D)=>R.command===D||R.command==="all",w=R=>R.check??(R.command==="insert"?[]:R.using??[]),S=[];for(let R of l.values()){if(!R.table)continue;let D=u.filter(F=>F.type===R.name);if(D.length===0)continue;let H=D.filter(F=>y(F,"select")).flatMap(F=>F.using??[]),Y=[["a SELECT",H],["an INSERT",[...D.filter(F=>y(F,"insert")).flatMap(w),...H]],["an UPDATE",[...D.filter(F=>y(F,"update")).flatMap(F=>[...F.using??[],...w(F)]),...H]],["a DELETE",[...D.filter(F=>y(F,"delete")).flatMap(F=>F.using??[]),...H]],["an INSERT \u2026 ON CONFLICT DO UPDATE",[...D.filter(F=>y(F,"insert")).flatMap(w),...D.filter(F=>y(F,"update")).flatMap(F=>[...F.using??[],...w(F)])]]];for(let[F,We]of Y){let ae=new Map;for(let Q of We){let ce=i.get(`${R.name}.${Q}`);ce!==void 0&&ae.set(ce,{what:`${R.name}.${Q}`,n:(ae.get(ce)?.n??0)+1})}if([...ae.values()].reduce((Q,ce)=>Q+ce.n,0)<2)continue;let ne=Q=>[...ae].map(([ce,on])=>`${on.n} * ${Q}[${ce}]`).join(" + "),sn=`${F} of ${R.table.schema}.${R.table.name} plans ${[...ae.values()].map(Q=>`${Q.what} ${Q.n===1?"once":`${Q.n} times`}`).join(" and ")}`;S.push(`
258
- IF (${ne("kbs")}) > ${ue} OR (${ne("mss")}) > ${xe} THEN
259
- RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s \u2014 the rows it reads, its USING and its WITH CHECK: %s MB and %s ms to plan, for every such statement; at most ${ue/1024} MB and ${xe} ms', ${$(sn)}, round((${ne("kbs")}) / 1024), round(${ne("mss")}));
260
- END IF;`)}}return S.join("")}function tn(){let i=[...l.values()].filter(u=>u.table);return i.length===0?[]:[`DO $early$
261
- DECLARE early text;
262
- BEGIN
263
- ${i.map(u=>qt(u.table.sql,`${u.table.schema}.${u.table.name}`)).join(`
264
- `)}
265
- END $early$`]}function nn(){if(d.length===0)return[];let i={int:"1",uuid:"00000000-0000-0000-0000-000000000001",text:"1"},u=d.map(R=>({what:`${R.type}.${R.name}`,view:ie(j(R.type,R.name)),key:v(R.type).table?i[v(R.type).family]:i.text,size:Math.max(1,t.planned(R.type,R.name))})).sort((R,D)=>R.size-D.size),y=R=>`ARRAY[${R.join(", ")}]`,w=new Map(u.map((R,D)=>[R.what,D+1])),S=en(w);return[`DO $measure$
266
- DECLARE
267
- whats text[] := ${y(u.map(R=>$(R.what)))};
268
- views text[] := ${y(u.map(R=>$(R.view)))};
269
- keys text[] := ${y(u.map(R=>$(R.key)))};
270
- sizes int[] := ${y(u.map(R=>String(R.size)))};
271
- memory boolean := pg_catalog.current_setting('server_version_num')::int >= 170000;
272
- per numeric := 0;
273
- p json; kb numeric; ms numeric;
274
- kbs numeric[] := '{}'; mss numeric[] := '{}';
275
- BEGIN
276
- FOR i IN 1 .. pg_catalog.array_length(views, 1) LOOP
277
- IF per * sizes[i] > ${2*ue} THEN
278
- RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s would take the database about %s MB to plan, for every statement it guards (as its other names show); at most ${ue/1024} MB. What its tables carry is planned with it \u2014 their indexes, a partial index''s predicate, an index''s expressions, their statistics \u2014 and the indexes of access.relationships', whats[i], round(per * sizes[i] / 1024));
279
- END IF;
280
- ms := NULL;
281
- -- The time, at its best of three: a database busy with other work is slower, not the schema.
282
- FOR t IN 1 .. 3 LOOP
283
- EXECUTE pg_catalog.format('EXPLAIN (%sSUMMARY, FORMAT JSON) SELECT id FROM %s WHERE id = %L', CASE WHEN memory THEN 'MEMORY, ' ELSE '' END, views[i], keys[i]) INTO p;
284
- kb := coalesce((p -> 0 -> 'Planning' ->> 'Memory Used')::numeric, 0);
285
- ms := least(coalesce(ms, 'Infinity'::numeric), (p -> 0 ->> 'Planning Time')::numeric);
286
- EXIT WHEN ms <= ${xe} OR kb > ${ue};
287
- END LOOP;
288
- IF kb > ${ue} OR ms > ${xe} THEN
289
- RAISE EXCEPTION USING ERRCODE = '54000', MESSAGE = pg_catalog.format('access: %s takes the database %s MB and %s ms to plan, for every statement it guards; at most ${ue/1024} MB and ${xe} ms. What its tables carry is planned with it \u2014 their indexes, a partial index''s predicate, an index''s expressions, their statistics \u2014 and the indexes of access.relationships', whats[i], round(kb / 1024), round(ms));
290
- END IF;
291
- per := greatest(per, kb / sizes[i]);
292
- kbs[i] := kb;
293
- mss[i] := ms;
294
- END LOOP;${S}
295
- END $measure$`]}function Rt(i,u){let y=v(i),w=y.table,S={col:R=>`${_(w.name)}.${_(R)}`,key:`${_(w.name)}.${_(w.key)}`};return g(y,{op:"ref",name:u},S)}function Tt(i,u){let y=v(i),w=S=>{if("parts"in S)return S.parts.flatMap(w);if(S.op==="exclude")return[...w(S.base),...w(S.minus)];if(S.op==="ref"){let R=y.model.permissions.get(S.name);return R?w(R.expr):[]}return y.model.relations.get(S.relation).kind==="stored"?[G(y.name,S.relation,S.name)]:[]};return w({op:"ref",name:u})}}function xn(t){let e=[];for(let n of t.types.values())for(let s of n.relations.values())if(s.kind==="column"){e.push({type:n.name,column:s.column});for(let r of nt(s.where))e.push({type:n.name,column:r})}return e}var Ss=`^${B}_[0-9a-f]{12}$`;function On(t){return[`DO $guard$
296
- DECLARE held text;
297
- BEGIN
298
- SELECT string_agg(DISTINCT pg_catalog.pg_describe_object(d.classid, d.objid, d.objsubid), ', ') INTO held
299
- FROM pg_catalog.pg_depend d
300
- JOIN pg_catalog.pg_class c ON d.refclassid = 'pg_catalog.pg_class'::regclass AND d.refobjid = c.oid
301
- JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace AND n.nspname = ${$(t)}
302
- WHERE d.deptype = 'n'
303
- AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_rewrite w JOIN pg_catalog.pg_class v ON v.oid = w.ev_class JOIN pg_catalog.pg_namespace vn ON vn.oid = v.relnamespace
304
- WHERE d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = w.oid AND vn.nspname = ${$(t)});
305
- IF held IS NOT NULL THEN
306
- RAISE EXCEPTION 'the compiled schema % is still read by: % \u2014 these must read access.* instead', ${$(t)}, held;
307
- END IF;
308
- END $guard$`,`DROP SCHEMA IF EXISTS ${_(t)} CASCADE`]}function Sn(){let t=_(B);return[`DROP FUNCTION IF EXISTS ${t}.can(text, text, text), ${t}.my_objects(text, text), ${t}.check(text, text, text, text), ${t}.objects(text, text, text), ${t}.subjects(text, text, text), ${t}.grant(text, text, text, text, text, text), ${t}.revoke(text, text, text, text, text, text)`,`UPDATE ${t}.schemas SET active = false WHERE active`]}var pt=/\{\{access:([a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*)?)\}\}/g,Xt=t=>`{{access:${t}}}`,In=t=>t!==void 0&&t.includes("{{access:"),Vt=/^[a-z][a-z0-9_]{0,39}(\.[a-z][a-z0-9_]{0,39})?$/,Ln={text:"text",uuid:"uuid",bigint:"int8",integer:"int4",smallint:"int2",boolean:"bool",numeric:"numeric",real:"float4","double precision":"float8","character varying":"varchar"};function kn(t){let e=new Set(t.enums.flatMap(n=>[`${n.schema}.${n.name}`,n.name]));return rt(t.tables.filter(n=>!n.ignored).map(n=>{let s={},r=[];for(let c of n.columns){if(c.ignored)continue;let h=c.type.replace(/\(.*\)$/,"");e.has(h.replaceAll('"',""))&&r.push(c.name),s[c.name]=Ln[h]??h}let o=c=>n.columns.some(h=>h.name===c&&!h.nullable&&!h.ignored),l=[...new Set([...n.primaryKey.length===1?n.primaryKey:[],...n.uniques.filter(c=>c.columns.length===1&&o(c.columns[0])).map(c=>c.columns[0])])],a=(n.primaryKey.length>0?1:0)+n.uniques.length+n.indexes.length;return{schema:n.schema,name:n.name,primaryKey:n.primaryKey,identifying:l,indexes:a,columns:s,enums:r}}))}function jn(t,e){let n=[];for(let s of t.tables){let r=e(s);if(r!==void 0)for(let o of s.policies)for(let l of`${o.using??""} ${o.withCheck??""}`.matchAll(pt))n.push({type:r,name:l[1]})}return n}function Dn(t,e){let n=[],s=r=>r===void 0?null:[...r.matchAll(pt)].map(o=>o[1]);for(let r of t.tables){let o=e(r);if(o!==void 0)for(let l of r.policies)n.push({type:o,command:l.for,using:s(l.using),check:s(l.withCheck)})}return n}function Fn(t,e,n){if(t.access===void 0)return null;let s=fe(de(t.access.text));for(let o of s.types.values())if(o.rows.length>0)throw new T("not_supported",`type ${o.name} has a rows rule: in an app whose tables Palgres makes, a table's row policy is written with the table \u2014 policy(...).using((p) => p.can('${o.rows[0]?.name}'))`);let r=o=>[...s.types.values()].find(l=>l.table?.schema===o.schema&&l.table.name===o.name)?.name;return Pe(s,kn(t),t.access.text,{roles:e,rows:!1,policies:jn(t,r),guards:Dn(t,r),...n===void 0?{}:{aliases:n}})}function ao(t,e,n){return Fn({...t,access:{text:e,compiled:""}},n).digest}function co(t,e){let n=fe(de(e)),s=[];for(let r of n.types.values())for(let o of r.relations.values())if(o.kind==="stored")for(let l of o.subjects)s.push([r.name,o.name,l]);return{digest:t.digest,schema:t.schema,names:t.names,tables:t.tables,predicates:t.predicates,stored:s}}function lo(t,e,n){if(!In(t))return{sql:t};if(!n)return{refused:"the schema declares no access schema for it to read"};let s=n.tables.find(l=>l.schema===e.schema&&l.name===e.name)?.type;if(s===void 0)return{refused:`no type of the access schema names the table ${e.schema}.${e.name}`};let r,o=t.replaceAll(pt,(l,a)=>{let c=n.predicates.find(h=>h.type===s&&h.name===a);return c||(r=a),`(${c?.sql??"false"})`});return r!==void 0?{refused:`type ${s} of the access schema has no relation or permission "${r}" a subject can hold`}:{sql:o}}var X=class t{expr;constructor(e){this.expr=e}bin(e,n){return new t({kind:"binop",op:e,left:this.expr,right:Mn(n)})}eq(e){return this.bin("eq",e)}neq(e){return this.bin("neq",e)}gt(e){return this.bin("gt",e)}gte(e){return this.bin("gte",e)}lt(e){return this.bin("lt",e)}lte(e){return this.bin("lte",e)}isNull(e=!1){return new t({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new t({kind:"and",parts:[this.expr,...e.map(n=>n.expr)]})}or(...e){return new t({kind:"or",parts:[this.expr,...e.map(n=>n.expr)]})}not(){return new t({kind:"not",expr:this.expr})}};function Mn(t){return t instanceof X?t.expr:{kind:"lit",value:t}}function ye(t,e=0,n=""){let s=`pb_e${e}`;return{col:r=>new X(e===0?{kind:"col",name:r}:{kind:"col",name:r,alias:s}),auth:{uid:()=>new X({kind:"authUid"})},can:r=>{if(e!==0)throw new Error(`policy expression: can("${r}") is about the policy's own row \u2014 use it outside existsIn`);if(!Vt.test(r))throw new Error(`policy expression: can("${r}") \u2014 a relation or a permission is lowercase letters, digits and underscores, with at most one dot (code.write)`);return new X({kind:"access",name:r})},lit:r=>new X({kind:"lit",value:r}),and:(...r)=>new X({kind:"and",parts:r.map(o=>o.expr)}),or:(...r)=>new X({kind:"or",parts:r.map(o=>o.expr)}),not:r=>new X({kind:"not",expr:r.expr}),existsIn:(r,o)=>{let l=r[Ge],a=ye(Object.keys(l.columns),e+1,n),c={kind:"exists",table:l.name,alias:`pb_e${e+1}`,outer:n,predicate:o(a).expr};return Object.defineProperty(c,le,{value:l,enumerable:!1,configurable:!0}),new X(c)}}}function W(t){return`"${t.replace(/"/g,'""')}"`}var Oe=class{_def;constructor(e){this._def={name:e,command:"all",roles:["authenticated"],using:null,withCheck:null,permissive:!0}}for(e){return this._def.command=e,this}to(...e){return this._def.roles=e,this}using(e){return this._def.using=e instanceof X?e.expr:e,this}memberOf(e,n,s={}){if(this._def.using!==null)throw new Error(`policy(${this._def.name}).memberOf(): this policy already has a using() expression. Write one or the other \u2014 memberOf IS the using expression.`);let r=s.column??"id",o=s.userColumn??"user_id";return this._def.using=`${W(r)} IN (SELECT ${W(n)} FROM ${W(e)} WHERE ${W(o)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof X?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function go(t){return new Oe(t)}function Ae(t,e){switch(t.kind){case"exists":throw new Error(`check(${e}): \`existsIn(...)\` is a subquery and PostgreSQL forbids subqueries in a CHECK constraint \u2014 express a cross-table rule as a composite FOREIGN KEY (foreignKeys), or as a guard.`);case"access":throw new Error(`check(${e}): \`can("${t.name}")\` asks who the caller is, and a CHECK constraint is true of the row whoever writes it \u2014 say it in a policy (\`withCheck\`)`);case"authUid":throw new Error(`check(${e}): \`auth.uid()\` renders as a subquery \`(SELECT auth.uid())\` and PostgreSQL forbids subqueries in a CHECK constraint \u2014 a caller-dependent rule belongs in an RLS policy, not a CHECK.`);case"binop":Ae(t.left,e),Ae(t.right,e);return;case"and":case"or":for(let n of t.parts)Ae(n,e);return;case"not":case"isNull":Ae(t.expr,e);return;default:return}}var Un={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function zt(t){if(t===null)return"NULL";if(typeof t=="boolean")return t?"true":"false";if(typeof t=="number"){if(!Number.isFinite(t))throw new Error(`check(): ${t} is not an SQL number literal.`);return String(t)}return`'${t.replace(/'/g,"''")}'`}function $e(t,e){switch(t.kind){case"col":return W(t.name);case"lit":return zt(t.value);case"binop":{let n=Un[t.op];if(n===void 0)throw new Error(`check(${e}): \`${t.op}\` is not supported in a CHECK expression.`);return`(${$e(t.left,e)} ${n} ${$e(t.right,e)})`}case"and":case"or":{if(t.parts.length===0)return t.kind==="and"?"(true)":"(false)";let n=t.kind==="and"?" AND ":" OR ";return`(${t.parts.map(s=>$e(s,e)).join(n)})`}case"not":return`(NOT ${$e(t.expr,e)})`;case"isNull":return`(${$e(t.expr,e)} IS ${t.negated?"NOT NULL":"NULL"})`;default:{let n=t.kind;throw new Error(`check(${e}): a \`${n}\` node is not one a CHECK expression takes.`)}}}function vn(t,e){if(t.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return Ae(e.expr,t),{name:t,expr:$e(e.expr,t)}}function Eo(t){if(t!==null)return typeof t=="string"?t:pe(t,"")}var Pn={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function Yt(t){let e=t.indexOf(".");return e<0?`${W("public")}.${W(t)}`:`${W(t.slice(0,e))}.${W(t.slice(e+1))}`}function pe(t,e){switch(t.kind){case"col":return t.alias!==void 0?`${W(t.alias)}.${W(t.name)}`:e===""?W(t.name):`${Yt(e)}.${W(t.name)}`;case"authUid":return"(SELECT auth.uid())";case"access":return Xt(t.name);case"lit":return zt(t.value);case"binop":{let n=Pn[t.op];if(n===void 0)throw new Error(`policy expression: \`${t.op}\` is not an operator a policy can use`);return`(${pe(t.left,e)} ${n} ${pe(t.right,e)})`}case"and":case"or":return t.parts.length===0?t.kind==="and"?"(true)":"(false)":`(${t.parts.map(n=>pe(n,e)).join(t.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${pe(t.expr,e)})`;case"isNull":return`(${pe(t.expr,e)} IS ${t.negated?"NOT NULL":"NULL"})`;case"exists":if(t.outer==="")throw new Error("policy expression: an existsIn carries no outer table \u2014 its correlation would collapse to x = x and filter nothing");return`EXISTS (SELECT 1 FROM ${Yt(t.table)} ${W(t.alias)} WHERE (${pe(t.predicate,t.outer)}))`}}function mt(t,e){return t===""||t==="public"?e:`${t}.${e}`}var He=class{_def;constructor(e){if(e.trim()==="")throw new Error("index(name): an index's name cannot be empty \u2014 Palbase reconciles indexes by name.");this._def={name:e}}unique(){return this._def.unique=!0,this}on(...e){return this._def.columns=e.map(n=>{let s=n.expr;if(s.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return s.name}),this}onExpression(e){return this._def.expression=e,this}where(e){return this._def.where=e.expr,this}desc(){return this._def.sort="desc",this}asc(){return this._def.sort="asc",this}nulls(e){return this._def.nulls=e,this}include(e){return this._def.include=e,this}};function To(t){return new He(t)}function Gn(t){return t instanceof Oe?t._def:t}var Ge=Symbol.for("palbase.table.meta");function No(t,e){if(t.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let n=(e.policies?.(ye(Object.keys(e.columns),0,t))??[]).map(Gn),s=n.length>0||e.rls!==!1,r={};for(let[C,M]of Object.entries(e.columns)){let k=M;Bn(t,C,k._def),qn(t,C,k._def,e.columns);let P=Object.create(Object.getPrototypeOf(k));Object.defineProperty(P,"_def",{value:{...k._def},enumerable:!0,writable:!0}),r[C]=P}let o={name:t,columns:r,rls:s,policies:n};if(e.primaryKey!==void 0&&(o.primaryKey=[...e.primaryKey]),e.search!==void 0&&(o.search=Hn(t,e.search,r,o.primaryKey)),e.unique!==void 0&&(o.unique=e.unique.map(C=>({name:C.name,columns:[...C.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let C of e.raw)if(C.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(t)}): raw ${JSON.stringify(C.name)} carries a drop, but a table-level raw() has no teardown \u2014 a drop is run only for a schema-level unit: defineSchema(name, { tables, raw: [raw(name, up, { drop })] })`);o.raw=e.raw.slice()}let l=typeof e.checks=="function"?e.checks(ye(Object.keys(e.columns),0,t)):e.checks?.slice()??[];l.length>0&&(o.checks=l);let a=(e.indexes?.(ye(Object.keys(e.columns),0,t))??[]).map(C=>C instanceof He?C._def:C);a.length>0&&(o.indexes=a);let c=(e.foreignKeys?.(ye(Object.keys(e.columns),0,t))??[]).map(xt);c.length>0&&(o.foreignKeys=c),e.ignored===!0&&(o.ignored=!0),Wn(t,o);for(let C of Object.values(r))C._def.ownerTable=o;let h={...r};return Object.defineProperty(h,Ge,{value:o,enumerable:!1}),h}function Hn(t,e,n,s){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(t)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let r={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??ze,metric:e.metric??"cosine",staleness:e.staleness??"null"},o=Object.entries(n).map(([a,c])=>({name:a,def:c._def})),l=Je(`defineTable(${JSON.stringify(t)})`,{columns:o.map(({name:a,def:c})=>({name:a,type:c.type==="sql"?c.sqlType??"sql":c.type,...c.ignored?{ignored:!0}:{},...c.generated?{generated:c.generated}:{}})),primaryKey:s??o.filter(({def:a})=>a.primaryKey===!0).map(({name:a})=>a)},r);if(l.length>0)throw new Error(l.join(`
309
- `));return r}var dt=new WeakMap;function Kn(t,e){for(let n of Object.values(t))Xn(n,`table "${n.name}"`,e);for(let n of Object.values(t))for(let[s,r]of Object.entries(n.columns)){let o=r._def;if(o.selfRefColumn!==void 0){if(!(o.selfRefColumn in n.columns))throw new Error(`table "${n.name}" column "${s}": selfReferences("${o.selfRefColumn}") \u2014 no such column on this table`);o.references={table:mt(e,n.name),column:o.selfRefColumn};continue}if(o.referencesThunk===void 0)continue;let l=o.referencesThunk(),a=l?._def?.ownerTable;if(a===void 0)throw new Error(`table "${n.name}" column "${s}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let c=Object.entries(a.columns).find(([,C])=>C._def===l._def)?.[0];if(c===void 0)throw new Error(`table "${n.name}" column "${s}": the referenced column was not found on table "${a.name}"`);let h=dt.get(a);if(h===void 0)throw new Error(`table "${n.name}" column "${s}": references(() => \u2026) points at table "${a.name}", which no defineSchema(...) has claimed yet \u2014 a foreign key cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);o.references={table:mt(h,a.name),column:c}}}function qn(t,e,n,s){if(n.encrypted===void 0)return;let r=`${e}_lookup`,o=n.defaultValue!==void 0||n.defaultSql!==void 0||n.defaultRandom===!0||n.defaultNow===!0?"it has a default \u2014 the database would write it in plain text; give the value in the write":n.fill!==void 0?".fillWith() is SQL over the row in plain text; give the value in the write":n.primaryKey===!0?"it is the primary key \u2014 a key the database matches rows by cannot be ciphertext; keep an id, and the encrypted value beside it":n.references!==void 0||n.referencesThunk!==void 0?"it references another table \u2014 a foreign key compares values the database cannot read":n.identity!==void 0||n.generated!==void 0?"the database makes its value":n.user!==void 0?"it holds a user's id, which the platform matches rows by":n.codec!==void 0||n.transform!==void 0?"it has a codec or a transform \u2014 encryption is its transform":n.unique===!0&&!n.encrypted.lookup?".unique() needs { lookup: true } \u2014 what equality is kept by is the lookup":r in s?`the table has a column "${r}" of its own, where the lookup is kept`:null;if(o!==null)throw new Error(`defineTable(${JSON.stringify(t)}): column "${e}" \u2014 .encrypted(): ${o}`)}function Wn(t,e){let n=r=>e.columns[r]?._def.encrypted,s=r=>{throw new Error(`defineTable(${JSON.stringify(t)}): ${r}`)};for(let r of e.primaryKey??[])n(r)&&s(`the primary key names "${r}", which is .encrypted() \u2014 keep an id, and the encrypted value beside it`);for(let r of e.unique??[])for(let o of r.columns){let l=n(o);l&&!l.lookup&&s(`unique ${JSON.stringify(r.name)} names "${o}", which is .encrypted() without { lookup: true } \u2014 what equality is kept by is the lookup`)}for(let r of e.indexes??[]){let o=JSON.stringify([r.keys??[],r.columns??[]]);for(let l of Object.keys(e.columns))n(l)&&o.includes(JSON.stringify(l))&&s(`index ${JSON.stringify(r.name)} names "${l}", which is .encrypted() \u2014 an index of ciphertext orders nothing; equality is found by { lookup: true }, which is indexed`)}for(let r of e.search?.from??[])n(r)&&s(`search reads "${r}", which is .encrypted() \u2014 its text is not in the database to embed`)}function Bn(t,e,n){if(n.fill===void 0)return;let s=n.defaultValue!==void 0||n.defaultRandom===!0||n.defaultNow===!0||n.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(s!==null)throw new Error(`defineTable(${JSON.stringify(t)}): column "${e}" \u2014 .fillWith(): ${s}`)}function wo(t,e){if(typeof t!="string")throw new Error(`defineSchema(...) takes the schema NAME first: defineSchema("public", { tables: [todos, lists] }). The one-argument form defineSchema({ tables: { \u2026 } }) is gone \u2014 a schema that does not say its own name cannot be told apart from another schema's table of the same name, which is what a cross-schema foreign key has to do. Migrate db/public.ts (one file per schema: db/public.ts, db/billing.ts \u2026): name the schema, and lift each table key onto the table itself with defineTable("todos", { columns: { \u2026 } }), then list the tables in the array.`);if(t.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let n={};for(let l of e.tables){let a=l[Ge];if(n[a.name]!==void 0)throw new Error(`defineSchema("${t}"): two tables declare the name "${a.name}" \u2014 table names must be unique within a schema`);n[a.name]=a,dt.set(a,t)}Kn(n,t);let s=[...new Set(e.extensions??[])],r=(e.raw??[]).slice(),o=new Set;for(let l of r){if(typeof l.name!="string"||l.name.trim()==="")throw new Error(`defineSchema("${t}"): a raw unit needs a name`);if(o.has(l.name))throw new Error(`defineSchema("${t}"): two raw units are named "${l.name}" \u2014 a unit's name identifies it`);o.add(l.name)}return{name:t,tables:n,extensions:s,raw:r}}function Xn(t,e,n){let s=(l,a)=>{let c=l[le];if(c===void 0)return;let h;try{h=typeof c=="function"?c():c}catch(k){throw new Error(`${e}: ${a} names its target through a callback that failed: ${k.message}`)}if(h==null||typeof h.name!="string")throw new Error(`${e}: ${a}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let C=dt.get(h);if(C===void 0)throw new Error(`${e}: ${a} points at table "${h.name}", which no defineSchema(...) has claimed yet \u2014 a cross-table reference cannot be written without its target's schema. Declare that table's schema first (one file per schema: db/public.ts, db/billing.ts \u2026, imported by this one).`);let M=mt(C,h.name);l.refTable!==void 0&&(l.refTable=M),l.table!==void 0&&(l.table=M)};for(let l of t.foreignKeys??[])s(l,`foreignKey("${l.name}")`);let r=`${n}.${t.name}`,o=(l,a)=>{if(!(l==null||typeof l=="string"))switch(l.kind){case"exists":s(l,a),l.table.includes(".")||(l.table=`public.${l.table}`),l.outer=r,o(l.predicate,a);return;case"binop":o(l.left,a),o(l.right,a);return;case"and":case"or":for(let c of l.parts)o(c,a);return;case"not":case"isNull":o(l.expr,a);return;default:return}};for(let l of t.policies)o(l.using,`policy("${l.name}")`),o(l.withCheck,`policy("${l.name}")`);for(let l of t.indexes??[])o(l.where,`index("${l.name}")`)}export{Yn as a,zn as b,Nt as c,Jn as d,te as e,Ye as f,Qn as g,mn as h,Je as i,Zn as j,_t as k,es as l,ts as m,T as n,de as o,z as p,Te as q,fe as r,oe as s,_e as t,ve as u,xn as v,On as w,Sn as x,In as y,Fn as z,ao as A,co as B,lo as C,je as D,fn as E,mt as F,He as G,To as H,Ge as I,No as J,wo as K,X as L,ye as M,Oe as N,go as O,vn as P,Eo as Q};
@@ -1,2 +0,0 @@
1
- /*! palgres 0.54.0 — Palbase SDK License (see LICENSE) */
2
- import{A,Q as w,a as g,b as D,f as K,g as _,k as N,n as P,o as k,r as S,y as x}from"./DMGBXJWT.js";var q={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function ne(e,n={}){let t=Array.isArray(e)?e:[e],i={tables:[],enums:[],extensions:[],raw:[]},a=new Map;for(let o of t){for(let l of Object.values(o.tables))i.tables.push(V(o.name,l,a));i.extensions.push(...o.extensions);for(let l of o.raw??[])i.raw.push({name:l.name,schema:o.name,sql:l.up,...l.drop!==void 0?{drop:l.drop}:{},...l.before===!0?{before:!0}:{}})}i.enums=[...a.values()];for(let o of t)for(let l of Object.values(o.tables))for(let r of l.raw??[])i.raw.push({name:r.name,table:`${o.name}.${l.name}`,sql:r.up});return n.access!==void 0&&(O(i,n.access),i.access={text:n.access,compiled:A(N(i),n.access,n.roles??{authenticated:"authenticated",service:"service_role"})}),i}function O(e,n){let t;try{t=S(k(n))}catch(i){if(i instanceof P)return;throw i}for(let i of t.types.values()){let a=i.table;if(!a)continue;let o=e.tables.find(r=>r.schema===a.schema&&r.name===a.name);if(!o||o.ignored)continue;let l=$.get(o);if(o.policies.some(r=>!l?.unindexedPolicies.has(r.name)&&(x(r.using)||x(r.withCheck))))for(let r of i.relations.values())r.kind==="column"&&U(o,r.column,l?.rawNames??new Set)}}var $=new WeakMap;function U(e,n,t){let i=new Set,a=r=>r[0]!==void 0&&i.add(r[0]);a(e.primaryKey);for(let r of e.uniques)a(r.columns);for(let r of e.indexes){let d=r.keys[0];d&&"column"in d&&r.where===void 0&&i.add(d.column)}let o=e.columns.find(r=>r.name===n);if(i.has(n)||!o||o.ignored)return;let l=`${e.name}_${n}_idx`;Buffer.byteLength(l)>63||e.indexes.some(r=>r.name===l)||t.has(l)||e.indexes.push({name:l,keys:[{column:n}],unique:!1})}function B(e,n){return!n&&D(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function Q(e){return e._def}function V(e,n,t){let i=[],a=s=>{let h=n.columns[s];return h!==void 0&&Q(h).encrypted?.lookup?g(s):s},o=(n.unique??[]).map(s=>({name:s.name,columns:s.columns.map(a)})),l=[],r=[],d=new Set,m=[];for(let[s,h]of Object.entries(n.columns)){let u=Q(h),c={name:s,type:j(e,s,n.name,u,t),nullable:u.nullable},E=F(u);E!==void 0&&(c.default=E),u.renamedFrom!==void 0&&(c.renamedFrom=u.renamedFrom),u.ignored&&(c.ignored=!0),u.fill!==void 0&&(c.fill=u.fill),u.identity!==void 0&&(c.identity=u.identity==="always"?"always":"by default"),u.generated!==void 0&&(c.generated={...u.generated}),u.user!==void 0&&(c.user={...u.user}),u.primaryKey&&r.push(s);let y=u.encrypted?.lookup?g(s):void 0;if(u.encrypted!==void 0&&(c.encrypted=y?{lookup:y}:{}),u.unique&&o.push(y?{name:`${n.name}_${y}_key`,columns:[y]}:{name:`${n.name}_${s}_key`,columns:[s]}),u.references!==void 0){let[b,R]=W(u.references.table);l.push(B({name:`${z(e,n.name)}_${s}_fkey`,columns:[s],refSchema:b,refTable:R,refColumns:[u.references.column],onDelete:u.onDeleteAction??"no action",onUpdate:u.onUpdateAction??"no action"},u.deferrable===!1)),u.index===!1&&d.add(s)}if(i.push(c),y){let b={name:y,type:"text",nullable:!0,lookupOf:s};u.renamedFrom!==void 0&&(b.renamedFrom=g(u.renamedFrom)),u.ignored&&(b.ignored=!0),i.push(b),u.unique||m.push({name:`${n.name}_${y}_idx`,keys:[{column:y}],unique:!1})}}for(let s of n.foreignKeys??[]){s.index===!1&&s.columns.length===1&&d.add(s.columns[0]);let[h,u]=W(s.refTable);l.push(B({name:s.name,columns:[...s.columns],refSchema:h,refTable:u,refColumns:[...s.refColumns],onDelete:s.onDelete??"no action",onUpdate:s.onUpdate??"no action",...s.match==="full"?{match:"full"}:{}},s.deferrable===!1))}let p={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:r,uniques:o,indexes:[...(n.indexes??[]).map(I),...m],checks:(n.checks??[]).map(s=>({name:s.name,expr:s.expr})),foreignKeys:l,rls:n.rls,policies:n.policies.map(L)};n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=H(p.uniques);let C=new Set((n.raw??[]).map(s=>s.name)),T=new Set(n.policies.filter(s=>s.indexes===!1).map(s=>s.name));return M(p,d,C,T),$.set(p,{rawNames:C,unindexedPolicies:T}),p}function j(e,n,t,i,a){let o=i.type;if(o==="enum"||o==="enum[]"){let l=i.enumName,r=`${e}.${l}`,d=i.enumValues??[],m=a.get(r);if(m&&m.values.join()!==d.join())throw new Error(`enum ${r} is declared with different values by ${t}.${n}: (${m.values.join(", ")}) and (${d.join(", ")}) \u2014 one type has one list`);return a.set(r,{schema:e,name:l,values:[...d]}),o==="enum[]"?`${_(e,l)}[]`:_(e,l)}return o==="sql"?K(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${q[o.slice(0,-2)]??o.slice(0,-2)}[]`:q[o]??o}function F(e){if(e.defaultSql!==void 0)return e.defaultSql;if(e.defaultRandom)return"gen_random_uuid()";if(e.defaultNow)return e.type==="date"?"CURRENT_DATE":"now()";let n=e.defaultValue;if(n!==void 0){if(Array.isArray(n)&&n.length===0&&e.type.endsWith("[]"))return"'{}'";if(typeof n=="string")return`'${n.replace(/'/g,"''")}'`;if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`default ${n} is not a number Postgres can store`);return String(n)}return n===null?"NULL":`'${JSON.stringify(n).replace(/'/g,"''")}'::jsonb`}}function I(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(a=>({column:a}));for(let a of n)e.sort==="desc"&&(a.desc=!0),e.nulls!==void 0&&(a.nulls=e.nulls);let t={name:e.name,keys:n,unique:e.unique===!0},i=e.where===void 0?void 0:w(e.where);return i!==void 0&&(t.where=i),e.include?.length&&(t.include=[...e.include]),t}function L(e){let n={name:e.name,for:e.command,to:e.roles.length===0?["public"]:[...e.roles]},t=w(e.using),i=w(e.withCheck);return t!==void 0&&(n.using=t),i!==void 0&&(n.withCheck=i),e.permissive||(n.restrictive=!0),n}function M(e,n,t,i){let a=new Set,o=r=>r[0]!==void 0&&a.add(r[0]);o(e.primaryKey);for(let r of e.uniques)o(r.columns);for(let r of e.indexes){let d=r.keys[0];d&&"column"in d&&r.where===void 0&&a.add(d.column)}let l=r=>{if(a.has(r)||e.columns.find(m=>m.name===r)?.ignored)return;let d=`${e.name}_${r}_idx`;Buffer.byteLength(d)>63||e.indexes.some(m=>m.name===d)||t.has(d)||(e.indexes.push({name:d,keys:[{column:r}],unique:!1}),a.add(r))};for(let r of e.foreignKeys)r.columns.length===1&&!n.has(r.columns[0])&&l(r.columns[0]);for(let r of e.policies)if(!i.has(r.name))for(let d of Y(e,r))l(d)}function Y(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let a of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=a[1].replace(/""/g,'"');e.columns.some(l=>l.name===o)&&!t.includes(o)&&t.push(o)}return t}function W(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function z(e,n){return e==="public"?n:`${e}_${n}`}function H(e){let n=new Map;return e.filter(t=>{let i=n.get(t.name);if(i===void 0)return n.set(t.name,t),!0;if(i.columns.join()!==t.columns.join())throw new Error(`palgres: unique ${t.name} is declared over (${i.columns.join(", ")}) and over (${t.columns.join(", ")}): give one of them another name`);return!1})}var v=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),re={number:{fromDb:e=>e==null?e:Number(e),toDb:e=>{if(e==null||typeof e!="number")return e==null?e:String(e);if(!Number.isFinite(e))throw new Error(`asNumber() cannot write ${e}: it is not a finite number, and the column holds one.`);if(Number.isInteger(e)&&!Number.isSafeInteger(e))throw new Error(`asNumber() cannot write ${e}: it is outside the safe integer range and would be stored as a different number. Declare .asDecimal() and hand this column a string.`);return String(e)},tsType:"number"},decimal:{fromDb:e=>e==null?e:String(e),toDb:e=>e==null?e:String(e),tsType:"string"}},f=class e{_def;constructor(n,t){this._def=t??{type:n,nullable:!1,primaryKey:!1}}primaryKey(){return this._def.primaryKey=!0,new e(this._def.type,this._def)}notNull(){return this._def.nullable=!1,new e(this._def.type,this._def)}nullable(){if(this._def.identity!==void 0)throw new Error(".nullable() on an identity column: an identity is always NOT NULL");return this._def.nullable=!0,new e(this._def.type,this._def)}default(n){return this._def.defaultValue=n,new e(this._def.type,this._def)}defaultRandom(){return this._def.defaultRandom=!0,new e(this._def.type,this._def)}defaultNow(){return this._def.defaultNow=!0,new e(this._def.type,this._def)}defaultSql(n){if(typeof n!="string"||n.trim()==="")throw new Error("defaultSql() takes the SQL of the default");return this._def.defaultSql=n,new e(this._def.type,this._def)}dbAssigned(){return this._def.dbAssigned=!0,new e(this._def.type,this._def)}array(){let n=this._def.type;if(!v.has(n))throw new Error(`${n} column: .array() is available on uuid(), text(), integer(), bigint(), numeric(), boolean(), timestamp(), date() and enumType()`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0)throw new Error(`.array() comes before the default \u2014 write ${n}().array().default([])`);if(this._def.codec!==void 0||this._def.transform!==void 0)throw new Error(".array() cannot follow a codec or a transform \u2014 they convert one value, not a list of them");let t=`${n}[]`;return new e(t,{...this._def,type:t})}identity(n){if(this._def.type!=="integer"&&this._def.type!=="bigint"&&!(this._def.type==="sql"&&this._def.sqlType==="smallint"))throw new Error(`${this._def.type} column: .identity() is for integer(), bigint() and sqlType('smallint') columns`);if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0)throw new Error(".identity() is the column's value \u2014 it cannot also have a default or a fill");let t=n?.always===!1?"byDefault":"always";return new e(this._def.type,{...this._def,nullable:!1,identity:t})}generated(n,t={}){if(typeof n!="string"||n.trim()==="")throw new Error(".generated() takes the SQL expression the column is");if(this._def.defaultValue!==void 0||this._def.defaultNow||this._def.defaultRandom||this._def.defaultSql!==void 0||this._def.fill!==void 0||this._def.identity!==void 0)throw new Error(".generated() is the column's value \u2014 it cannot also have a default, a fill or an identity");return new e(this._def.type,{...this._def,generated:{expr:n,stored:t.stored===!0}})}fillWith(n){return new e(this._def.type,{...this._def,fill:n})}renamedFrom(n){return this._def.renamedFrom=n,this}ignored(){return new e(this._def.type,{...this._def,ignored:!0})}encrypted(n={}){if(this._def.type!=="text")throw new Error(`.encrypted() is for a text() column \u2014 a ${this._def.type} column's value is not text to seal; keep it in a text() column (JSON.stringify it)`);return new e("text",{...this._def,encrypted:{lookup:n.lookup===!0}})}references(n,t){if(typeof n!="function")throw new Error('references(...) takes a callback: write references(() => otherTable.column). The two-string form references("table", "column") is gone \u2014 a string cannot be type-checked and cannot point at a table that does not exist yet.');return this._def.referencesThunk=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.reverseAs!==void 0&&(this._def.reverseAs=t.reverseAs),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),t?.onUpdate!==void 0&&(this._def.onUpdateAction=t.onUpdate),t?.index===!1&&(this._def.index=!1),t?.deferrable===!1&&(this._def.deferrable=!1),new e(this._def.type,this._def)}selfReferences(n,t){return this._def.selfRefColumn=n,t?.as!==void 0&&(this._def.refAs=t.as),t?.onDelete!==void 0&&(this._def.onDeleteAction=t.onDelete),new e(this._def.type,this._def)}onDelete(n){return this._def.onDeleteAction=n,new e(this._def.type,this._def)}unique(){return this._def.unique=!0,new e(this._def.type,this._def)}asNumber(){return this.withCodec("number","asNumber")}asDecimal(){return this.withCodec("decimal","asDecimal")}withCodec(n,t){if(this._def.type!=="bigint"&&this._def.type!=="numeric")throw new Error(`${this._def.type} column: .${t}() is only available on bigint()/numeric() \u2014 those are the exact-precision types that surface as string.`);if(this._def.transform!==void 0)throw new Error(`.${t}() and .transform() are two ways to say the same thing on one column \u2014 keep .${t}().`);if(this._def.codec!==void 0)throw new Error(`column already declares .as${this._def.codec==="number"?"Number":"Decimal"}(); a column has ONE codec.`);return new e(this._def.type,{...this._def,codec:n})}transform(n){if(this._def.codec!==void 0)throw new Error("column already declares a named codec; .transform() and .as*() are two ways to say the same thing \u2014 keep the codec.");return new e(this._def.type,{...this._def,transform:n})}};function ie(){return new f("uuid")}function oe(){return new f("text")}function se(){return new f("integer")}function le(){return new f("bigint")}function ue(e){if(e===void 0)return new f("numeric");let{precision:n,scale:t=0}=e;if(!Number.isInteger(n)||n<1||n>1e3)throw new Error(`numeric({ precision: ${n} }): precision is a whole number from 1 to 1000`);if(!Number.isInteger(t)||t<0||t>n)throw new Error(`numeric({ precision: ${n}, scale: ${t} }): scale is a whole number from 0 to the precision`);return new f("numeric",{type:"numeric",nullable:!1,primaryKey:!1,precision:n,scale:t})}function ae(){return new f("date")}var J={uuid:"uuid()",text:"text()",integer:"integer()",int:"integer()",int4:"integer()",bigint:"bigint()",int8:"bigint()",numeric:"numeric()",decimal:"numeric()",boolean:"boolean()",bool:"boolean()",timestamptz:"timestamp()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"};function de(e){let n=typeof e=="string"?e.trim():"";if(n==="")throw new Error('sqlType() takes the Postgres type, e.g. sqlType("inet")');let t=n.toLowerCase().replace(/\[\]$/,""),i=J[t];if(i!==void 0&&!(n.endsWith("[]")&&!v.has(i.slice(0,-2))))throw new Error(`sqlType(${JSON.stringify(n)}): the DSL has this type \u2014 declare it as ${i}${n.endsWith("[]")?".array()":""}`);return new f("sql",{type:"sql",nullable:!1,primaryKey:!1,sqlType:n})}var fe=new Set(["smallint","real","double precision"]),me=new Set(["json"]);function ce(){return new f("boolean")}function ye(){return new f("timestamp")}function pe(){return new f("jsonb")}function he(e,n){let t=new f("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function be(){let e=new f("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function ge(e){let n=new f("text");return n._def.user={onDelete:e.onDelete,owns:!1},e.as!==void 0&&(n._def.refAs=e.as),n}export{ne as a,Y as b,re as c,f as d,ie as e,oe as f,se as g,le as h,ue as i,ae as j,de as k,fe as l,me as m,ce as n,ye as o,pe as p,he as q,be as r,ge as s};