palgres 0.53.0 → 0.54.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,5 +0,0 @@
1
- /*! palgres 0.53.0 — Palbase SDK License (see LICENSE) */
2
- import{createHash as z}from"node:crypto";function de(n){return`${n}_lookup`}function me(n,e){let t=r=>r==="cascade"||r==="set null"||r==="set default";return t(n)||t(e)}var L=class extends Error{problems;constructor(e){super(`the schema is not valid:
3
- - ${e.join(`
4
- - `)}`),this.name="SchemaError",this.problems=e}},pe=()=>({tables:[],enums:[],extensions:[],raw:[]}),b=n=>`${n.schema}.${n.name}`,J={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 D(n){let e=n.trim().replace(/\s+/g," "),t="";for(;e.endsWith("[]");)t+="[]",e=e.slice(0,-2).trim();let r=/^((?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_ ]*?)(?:\.(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_]*))?)\s*(\(.*\))?$/.exec(e);if(!r)return n.trim()+t;let a=r[2]?r[2].replace(/\s+/g,""):"",o=Q(r[1]);return o===void 0?n.trim()+t:o.length===1&&o[0].quoted?`"${o[0].name.replace(/"/g,'""')}"${a}${t}`:o.length===1?`${J[o[0].name]??o[0].name}${a}${t}`:`${o.map(l=>N(l.name)).join(".")}${a}${t}`}var N=n=>/^[a-z_][a-z0-9_$]*$/.test(n)?n:`"${n.replace(/"/g,'""')}"`,he=(n,e)=>`${N(n)}.${N(e)}`;function Q(n){let e=[],t=0;for(;t<n.length;){if(n[t]==='"'){let r=t+1,a="";for(;;){if(r>=n.length)return;if(n[r]==='"'){if(n[r+1]==='"'){a+='"',r+=2;continue}break}a+=n[r++]}e.push({name:a,quoted:!0}),t=r+1}else{let r=/^[A-Za-z_][A-Za-z0-9_ ]*/.exec(n.slice(t));if(!r)return;e.push({name:r[0].trim().toLowerCase(),quoted:!1}),t+=r[0].length}if(t<n.length){if(n[t]!==".")return;t++}}return e}var W=/^[A-Za-z_][A-Za-z0-9_$]*$/,Z=63;function g(n,e,t=!1){if(typeof e!="string"||e==="")return`${n} has no name`;if(t?e.includes("\0"):!W.test(e))return`${n} "${e}": a name is letters, digits and _ (starting with a letter or _)`;if(Buffer.byteLength(e)>Z)return`${n} "${e}": longer than Postgres' 63 bytes, it would be cut`;if(e.startsWith("palgres_")||e.startsWith("_palgres"))return`${n} "${e}": names starting with palgres_ are Palgres' own`}var V="vector",F=["cosine","euclidean","inner_product"],q=1536,G=2e3,R=4e3,X=/^(text|citext|public\.citext|character varying(\(\d+\))?)$/;function A(n,e,t){let r=[];e.primaryKey.length!==1&&r.push(`${n} 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(t.from)||t.from.length===0)&&r.push(`${n}: search.from is empty \u2014 name the text columns a row is found by (search: { from: ['title', 'body'], model })`);let a=new Set;for(let o of Array.isArray(t.from)?t.from:[]){a.has(o)&&r.push(`${n}: search.from names "${o}" twice \u2014 name each column once`),a.add(o);let l=e.columns.find(i=>i.name===o);l?l.ignored?r.push(`${n}: search.from names "${o}", which is ignored \u2014 take it out of search.from, or keep the column`):X.test(D(l.type))?l.generated&&r.push(`${n}: 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`):r.push(`${n}: 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`):r.push(`${n}: search.from names "${o}", which the table does not have \u2014 name its text columns`)}return(typeof t.model!="string"||t.model.trim()==="")&&r.push(`${n}: search.model is empty \u2014 name the embedding model (search: { from, model: 'embedding' })`),F.includes(t.metric)||r.push(`${n}: search.metric is ${JSON.stringify(t.metric)} \u2014 it is ${F.map(o=>`'${o}'`).join(", ")}`),(!Number.isInteger(t.dimensions)||t.dimensions<1||t.dimensions>R)&&r.push(`${n}: search.dimensions is ${String(t.dimensions)} \u2014 it is 1 to ${R}: pgvector indexes a vector of at most ${G} dimensions and a half-precision one of at most ${R}; ask the model for fewer (search: { dimensions: ${q} })`),t.staleness!=="null"&&t.staleness!=="keep"&&r.push(`${n}: search.staleness is ${JSON.stringify(t.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)&&r.push(`${n} declares search and has a column "_score": search() answers each row with its _score \u2014 rename the column`),r}function ye(n){let e=[],t=i=>i&&e.push(i),r=new Map,a=new Map,o=(i,c,f)=>{let u=`${i}.${c}`,d=a.get(u);d?e.push(`${f} "${c}" has the name of ${d} in schema ${i}`):a.set(u,f)};for(let i of n.enums)t(g("an enum",i.name)),i.values.length===0&&e.push(`enum ${i.schema}.${i.name} has no values`),new Set(i.values).size!==i.values.length&&e.push(`enum ${i.schema}.${i.name} names a value twice`);for(let i of n.tables){let c=b(i);t(g("a schema",i.schema)),t(g("a table",i.name)),r.has(c)&&e.push(`table ${c} is declared twice`),r.set(c,i),o(i.schema,i.name,`table ${c}`);let f=new Map,u=(s,m)=>{let C=f.get(s);C?e.push(`${m} "${s}" has the name of a ${C} of table ${c}`):f.set(s,m)},d=new Map;for(let s of i.columns)t(g(`column ${c}.${s.name}`,s.name)),d.has(s.name)&&e.push(`column ${c}.${s.name} is declared twice`),d.set(s.name,s),s.identity&&s.default!==void 0&&e.push(`column ${c}.${s.name}: an identity column has no default`),s.generated&&(s.default!==void 0||s.identity||s.fill!==void 0)&&e.push(`column ${c}.${s.name}: a generated column has no default, identity or fill`),s.generated&&!s.generated.expr.trim()&&e.push(`column ${c}.${s.name}: a generated column's expression is empty`),s.identity&&!["smallint","integer","bigint"].includes(D(s.type))&&e.push(`column ${c}.${s.name}: an identity column is smallint, integer or bigint`),s.identity&&s.nullable&&e.push(`column ${c}.${s.name}: an identity column is NOT NULL`);let h=(s,m)=>{let C=d.get(s);C?C.ignored&&e.push(`${m} names column "${s}", which is ignored`):e.push(`${m} names column "${s}", which ${c} does not have`)};for(let s of i.primaryKey)h(s,`the primary key of ${c}`);for(let s of i.primaryKey)d.get(s)?.nullable&&e.push(`column ${c}.${s} is in the primary key, so it is not nullable`);for(let s of i.uniques){t(g(`a unique constraint of ${c}`,s.name,!0)),o(i.schema,s.name,`unique constraint ${c}.${s.name}`),u(s.name,"unique constraint"),s.columns.length===0&&e.push(`unique constraint ${s.name} names no column`);for(let m of s.columns)h(m,`unique constraint ${s.name}`)}for(let s of i.indexes){t(g(`an index of ${c}`,s.name,!0)),o(i.schema,s.name,`index ${c}.${s.name}`),s.keys.length===0&&e.push(`index ${s.name} has no key`);for(let m of s.keys)"column"in m&&h(m.column,`index ${s.name}`);for(let m of s.include??[])h(m,`index ${s.name}`)}for(let s of i.checks)t(g(`a check of ${c}`,s.name,!0)),u(s.name,"check"),s.expr.trim()||e.push(`check ${s.name} has no expression`);for(let s of i.foreignKeys){t(g(`a foreign key of ${c}`,s.name,!0)),u(s.name,"foreign key"),(s.columns.length===0||s.columns.length!==s.refColumns.length)&&e.push(`foreign key ${s.name} names ${s.columns.length} column(s) and references ${s.refColumns.length}`);for(let m of s.columns)h(m,`foreign key ${s.name}`)}let E=new Set;for(let s of i.policies)t(g(`a policy of ${c}`,s.name,!0)),E.has(s.name)&&e.push(`policy ${c}.${s.name} is declared twice`),E.add(s.name),s.to.length===0&&e.push(`policy ${c}.${s.name} names no role`),s.for==="insert"&&s.using!==void 0&&e.push(`policy ${c}.${s.name}: an insert policy has only withCheck`),(s.for==="select"||s.for==="delete")&&s.withCheck!==void 0&&e.push(`policy ${c}.${s.name}: a ${s.for} policy has only using`);i.policies.length>0&&!i.rls&&e.push(`table ${c} has policies but row-level security off: they would do nothing`),i.search!==void 0&&e.push(...A(`table ${c}`,i,i.search))}for(let i of n.tables)for(let c of i.foreignKeys){let f=r.get(`${c.refSchema}.${c.refTable}`);if(!f){e.push(`foreign key ${c.name} of ${b(i)} references ${c.refSchema}.${c.refTable}, which is not declared`);continue}f.ignored&&e.push(`foreign key ${c.name} of ${b(i)} references ${b(f)}, which is ignored`);for(let u of c.refColumns)f.columns.some(d=>d.name===u&&!d.ignored)||e.push(`foreign key ${c.name} references ${b(f)}.${u}, which it does not have`)}let l=new Set;for(let i of n.raw)t(g("a raw unit",i.name)),l.has(i.name)&&e.push(`raw unit ${i.name} is declared twice`),l.add(i.name),i.sql.trim()||e.push(`raw unit ${i.name} has no SQL`),i.before&&i.table!==void 0&&e.push(`raw unit ${i.name}: before is for a schema's unit, not a table's \u2014 a table's is made after its table`);return e}function j(n){let e=t=>[...t].sort((r,a)=>r.name<a.name?-1:r.name>a.name?1:0);return{tables:[...n.tables].map(t=>({...t,schema:t.schema||"public",columns:t.columns.map(r=>({...r,type:D(r.type)})),uniques:e(t.uniques),indexes:e(t.indexes),checks:e(t.checks),foreignKeys:e(t.foreignKeys),policies:e(t.policies).map(r=>({...r,to:[...r.to].sort()}))})).sort((t,r)=>b(t)<b(r)?-1:b(t)>b(r)?1:0),enums:[...n.enums].sort((t,r)=>`${t.schema}.${t.name}`<`${r.schema}.${r.name}`?-1:1),extensions:[...new Set([...n.extensions,...n.tables.some(t=>t.search!==void 0)?[V]:[]])].sort(),raw:e(n.raw)}}function ge(n){let e=j(n),t=new Map(n.raw.map((r,a)=>[r.name,a]));return e.raw.sort((r,a)=>(t.get(r.name)??0)-(t.get(a.name)??0)),e}function O(n){return Array.isArray(n)?`[${n.map(O).join(",")}]`:n&&typeof n=="object"?`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:1).map(([t,r])=>`${JSON.stringify(t)}:${O(r)}`).join(",")}}`:JSON.stringify(n)}function be(n){return z("sha256").update(O(j(n))).digest("hex").slice(0,32)}var v=Symbol.for("palbase.table.meta"),x=Symbol.for("palbase.ref.target"),P=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(t=>{let r=t.expr;if(r.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 r.name}),this}references(e,...t){if(t.length===0)throw new Error(`foreignKey(${this._def.name}).references(): needs at least one target column.`);return this._def.refColumns=[...t],typeof e=="function"?(Object.defineProperty(this._def,x,{value:()=>e()[v],enumerable:!1,configurable:!0}),this):(this._def.refTable=e[v].name,Object.defineProperty(this._def,x,{value:e[v],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 Y(n){return new P(n)}function B(n){let e=n instanceof P?n._def:n;if(e.columns.length===0)throw new Error(`foreignKey(${e.name}): needs at least one local column \u2014 call .on(...).`);let t=typeof e[x]=="function";if(e.refColumns.length===0||e.refTable===""&&!t)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 y=class n{expr;constructor(e){this.expr=e}bin(e,t){return new n({kind:"binop",op:e,left:this.expr,right:ee(t)})}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 n({kind:"isNull",expr:this.expr,negated:e})}and(...e){return new n({kind:"and",parts:[this.expr,...e.map(t=>t.expr)]})}or(...e){return new n({kind:"or",parts:[this.expr,...e.map(t=>t.expr)]})}not(){return new n({kind:"not",expr:this.expr})}};function ee(n){return n instanceof y?n.expr:{kind:"lit",value:n}}function k(n,e=0,t=""){let r=`pb_e${e}`;return{col:a=>new y(e===0?{kind:"col",name:a}:{kind:"col",name:a,alias:r}),auth:{uid:()=>new y({kind:"authUid"})},lit:a=>new y({kind:"lit",value:a}),and:(...a)=>new y({kind:"and",parts:a.map(o=>o.expr)}),or:(...a)=>new y({kind:"or",parts:a.map(o=>o.expr)}),not:a=>new y({kind:"not",expr:a.expr}),existsIn:(a,o)=>{let l=a[_],i=k(Object.keys(l.columns),e+1,t),c={kind:"exists",table:l.name,alias:`pb_e${e+1}`,outer:t,predicate:o(i).expr};return Object.defineProperty(c,x,{value:l,enumerable:!1,configurable:!0}),new y(c)}}}function p(n){return`"${n.replace(/"/g,'""')}"`}var S=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 y?e.expr:e,this}memberOf(e,t,r={}){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 a=r.column??"id",o=r.userColumn??"user_id";return this._def.using=`${p(a)} IN (SELECT ${p(t)} FROM ${p(e)} WHERE ${p(o)} = (select auth.uid()))`,this}withCheck(e){return this._def.withCheck=e instanceof y?e.expr:e,this}withoutIndexes(){return this._def.indexes=!1,this}as(e){return this._def.permissive=e==="permissive",this}};function Ee(n){return new S(n)}function T(n,e){switch(n.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"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":T(n.left,e),T(n.right,e);return;case"and":case"or":for(let t of n.parts)T(t,e);return;case"not":case"isNull":T(n.expr,e);return;default:return}}var ne={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function U(n){if(n===null)return"NULL";if(typeof n=="boolean")return n?"true":"false";if(typeof n=="number"){if(!Number.isFinite(n))throw new Error(`check(): ${n} is not an SQL number literal.`);return String(n)}return`'${n.replace(/'/g,"''")}'`}function $(n,e){switch(n.kind){case"col":return p(n.name);case"lit":return U(n.value);case"binop":{let t=ne[n.op];if(t===void 0)throw new Error(`check(${e}): \`${n.op}\` is not supported in a CHECK expression.`);return`(${$(n.left,e)} ${t} ${$(n.right,e)})`}case"and":case"or":{if(n.parts.length===0)return n.kind==="and"?"(true)":"(false)";let t=n.kind==="and"?" AND ":" OR ";return`(${n.parts.map(r=>$(r,e)).join(t)})`}case"not":return`(NOT ${$(n.expr,e)})`;case"isNull":return`(${$(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;default:{let t=n.kind;throw new Error(`check(${e}): a \`${t}\` node is not one a CHECK expression takes.`)}}}function te(n,e){if(n.trim()==="")throw new Error("check(): the constraint's name cannot be empty \u2014 Palbase reconciles CHECKs by name.");return T(e.expr,n),{name:n,expr:$(e.expr,n)}}function Ce(n){if(n!==null)return typeof n=="string"?n:w(n,"")}var re={eq:"=",neq:"<>",gt:">",gte:">=",lt:"<",lte:"<="};function H(n){let e=n.indexOf(".");return e<0?`${p("public")}.${p(n)}`:`${p(n.slice(0,e))}.${p(n.slice(e+1))}`}function w(n,e){switch(n.kind){case"col":return n.alias!==void 0?`${p(n.alias)}.${p(n.name)}`:e===""?p(n.name):`${H(e)}.${p(n.name)}`;case"authUid":return"(SELECT auth.uid())";case"lit":return U(n.value);case"binop":{let t=re[n.op];if(t===void 0)throw new Error(`policy expression: \`${n.op}\` is not an operator a policy can use`);return`(${w(n.left,e)} ${t} ${w(n.right,e)})`}case"and":case"or":return n.parts.length===0?n.kind==="and"?"(true)":"(false)":`(${n.parts.map(t=>w(t,e)).join(n.kind==="and"?" AND ":" OR ")})`;case"not":return`(NOT ${w(n.expr,e)})`;case"isNull":return`(${w(n.expr,e)} IS ${n.negated?"NOT NULL":"NULL"})`;case"exists":if(n.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 ${H(n.table)} ${p(n.alias)} WHERE (${w(n.predicate,n.outer)}))`}}function M(n,e){return n===""||n==="public"?e:`${n}.${e}`}var K=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(t=>{let r=t.expr;if(r.kind!=="col")throw new Error(`index(${this._def.name}).on(): takes column references only \u2014 for an expression, use onExpression("\u2026").`);return r.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 Re(n){return new K(n)}function ie(n){return n instanceof S?n._def:n}var _=Symbol.for("palbase.table.meta");function Ne(n,e){if(n.trim()==="")throw new Error("defineTable(name, \u2026): name must not be empty");let t=(e.policies?.(k(Object.keys(e.columns),0,n))??[]).map(ie),r=t.length>0||e.rls!==!1,a={};for(let[u,d]of Object.entries(e.columns)){let h=d;ce(n,u,h._def),ae(n,u,h._def,e.columns);let E=Object.create(Object.getPrototypeOf(h));Object.defineProperty(E,"_def",{value:{...h._def},enumerable:!0,writable:!0}),a[u]=E}let o={name:n,columns:a,rls:r,policies:t};if(e.primaryKey!==void 0&&(o.primaryKey=[...e.primaryKey]),e.search!==void 0&&(o.search=se(n,e.search,a,o.primaryKey)),e.unique!==void 0&&(o.unique=e.unique.map(u=>({name:u.name,columns:[...u.columns]}))),e.raw!==void 0&&e.raw.length>0){for(let u of e.raw)if(u.drop!==void 0)throw new Error(`defineTable(${JSON.stringify(n)}): raw ${JSON.stringify(u.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(k(Object.keys(e.columns),0,n)):e.checks?.slice()??[];l.length>0&&(o.checks=l);let i=(e.indexes?.(k(Object.keys(e.columns),0,n))??[]).map(u=>u instanceof K?u._def:u);i.length>0&&(o.indexes=i);let c=(e.foreignKeys?.(k(Object.keys(e.columns),0,n))??[]).map(B);c.length>0&&(o.foreignKeys=c),e.ignored===!0&&(o.ignored=!0),le(n,o);for(let u of Object.values(a))u._def.ownerTable=o;let f={...a};return Object.defineProperty(f,_,{value:o,enumerable:!1}),f}function se(n,e,t,r){if(e===null||typeof e!="object")throw new Error(`defineTable(${JSON.stringify(n)}): search is { from: [...columns], model } \u2014 got ${e===null?"null":typeof e}`);let a={from:Array.isArray(e.from)?[...e.from]:e.from,model:e.model,dimensions:e.dimensions??q,metric:e.metric??"cosine",staleness:e.staleness??"null"},o=Object.entries(t).map(([i,c])=>({name:i,def:c._def})),l=A(`defineTable(${JSON.stringify(n)})`,{columns:o.map(({name:i,def:c})=>({name:i,type:c.type==="sql"?c.sqlType??"sql":c.type,...c.ignored?{ignored:!0}:{},...c.generated?{generated:c.generated}:{}})),primaryKey:r??o.filter(({def:i})=>i.primaryKey===!0).map(({name:i})=>i)},a);if(l.length>0)throw new Error(l.join(`
5
- `));return a}var I=new WeakMap;function oe(n,e){for(let t of Object.values(n))ue(t,`table "${t.name}"`,e);for(let t of Object.values(n))for(let[r,a]of Object.entries(t.columns)){let o=a._def;if(o.selfRefColumn!==void 0){if(!(o.selfRefColumn in t.columns))throw new Error(`table "${t.name}" column "${r}": selfReferences("${o.selfRefColumn}") \u2014 no such column on this table`);o.references={table:M(e,t.name),column:o.selfRefColumn};continue}if(o.referencesThunk===void 0)continue;let l=o.referencesThunk(),i=l?._def?.ownerTable;if(i===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) must point at a column of a table declared with defineTable(...)`);let c=Object.entries(i.columns).find(([,u])=>u._def===l._def)?.[0];if(c===void 0)throw new Error(`table "${t.name}" column "${r}": the referenced column was not found on table "${i.name}"`);let f=I.get(i);if(f===void 0)throw new Error(`table "${t.name}" column "${r}": references(() => \u2026) points at table "${i.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:M(f,i.name),column:c}}}function ae(n,e,t,r){if(t.encrypted===void 0)return;let a=`${e}_lookup`,o=t.defaultValue!==void 0||t.defaultSql!==void 0||t.defaultRandom===!0||t.defaultNow===!0?"it has a default \u2014 the database would write it in plain text; give the value in the write":t.fill!==void 0?".fillWith() is SQL over the row in plain text; give the value in the write":t.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":t.references!==void 0||t.referencesThunk!==void 0?"it references another table \u2014 a foreign key compares values the database cannot read":t.identity!==void 0||t.generated!==void 0?"the database makes its value":t.user!==void 0?"it holds a user's id, which the platform matches rows by":t.codec!==void 0||t.transform!==void 0?"it has a codec or a transform \u2014 encryption is its transform":t.unique===!0&&!t.encrypted.lookup?".unique() needs { lookup: true } \u2014 what equality is kept by is the lookup":a in r?`the table has a column "${a}" of its own, where the lookup is kept`:null;if(o!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .encrypted(): ${o}`)}function le(n,e){let t=a=>e.columns[a]?._def.encrypted,r=a=>{throw new Error(`defineTable(${JSON.stringify(n)}): ${a}`)};for(let a of e.primaryKey??[])t(a)&&r(`the primary key names "${a}", which is .encrypted() \u2014 keep an id, and the encrypted value beside it`);for(let a of e.unique??[])for(let o of a.columns){let l=t(o);l&&!l.lookup&&r(`unique ${JSON.stringify(a.name)} names "${o}", which is .encrypted() without { lookup: true } \u2014 what equality is kept by is the lookup`)}for(let a of e.indexes??[]){let o=JSON.stringify([a.keys??[],a.columns??[]]);for(let l of Object.keys(e.columns))t(l)&&o.includes(JSON.stringify(l))&&r(`index ${JSON.stringify(a.name)} names "${l}", which is .encrypted() \u2014 an index of ciphertext orders nothing; equality is found by { lookup: true }, which is indexed`)}for(let a of e.search?.from??[])t(a)&&r(`search reads "${a}", which is .encrypted() \u2014 its text is not in the database to embed`)}function ce(n,e,t){if(t.fill===void 0)return;let r=t.defaultValue!==void 0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultSql!==void 0?"the column has a default \u2014 the default already fills every row; keep one of the two":null;if(r!==null)throw new Error(`defineTable(${JSON.stringify(n)}): column "${e}" \u2014 .fillWith(): ${r}`)}function Oe(n,e){if(typeof n!="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(n.trim()==="")throw new Error("defineSchema(name, \u2026): name must not be empty");let t={};for(let l of e.tables){let i=l[_];if(t[i.name]!==void 0)throw new Error(`defineSchema("${n}"): two tables declare the name "${i.name}" \u2014 table names must be unique within a schema`);t[i.name]=i,I.set(i,n)}oe(t,n);let r=[...new Set(e.extensions??[])],a=(e.raw??[]).slice(),o=new Set;for(let l of a){if(typeof l.name!="string"||l.name.trim()==="")throw new Error(`defineSchema("${n}"): a raw unit needs a name`);if(o.has(l.name))throw new Error(`defineSchema("${n}"): two raw units are named "${l.name}" \u2014 a unit's name identifies it`);o.add(l.name)}return{name:n,tables:t,extensions:r,raw:a}}function ue(n,e,t){let r=(l,i)=>{let c=l[x];if(c===void 0)return;let f;try{f=typeof c=="function"?c():c}catch(h){throw new Error(`${e}: ${i} names its target through a callback that failed: ${h.message}`)}if(f==null||typeof f.name!="string")throw new Error(`${e}: ${i}'s callback does not answer a table \u2014 write references(() => otherTable, \u2026)`);let u=I.get(f);if(u===void 0)throw new Error(`${e}: ${i} points at table "${f.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 d=M(u,f.name);l.refTable!==void 0&&(l.refTable=d),l.table!==void 0&&(l.table=d)};for(let l of n.foreignKeys??[])r(l,`foreignKey("${l.name}")`);let a=`${t}.${n.name}`,o=(l,i)=>{if(!(l==null||typeof l=="string"))switch(l.kind){case"exists":r(l,i),l.table.includes(".")||(l.table=`public.${l.table}`),l.outer=a,o(l.predicate,i);return;case"binop":o(l.left,i),o(l.right,i);return;case"and":case"or":for(let c of l.parts)o(c,i);return;case"not":case"isNull":o(l.expr,i);return;default:return}};for(let l of n.policies)o(l.using,`policy("${l.name}")`),o(l.withCheck,`policy("${l.name}")`);for(let l of n.indexes??[])o(l.where,`index("${l.name}")`)}export{de as a,me as b,L as c,pe as d,b as e,D as f,he as g,G as h,A as i,ye as j,j as k,ge as l,be as m,P as n,Y as o,M as p,K as q,Re as r,_ as s,Ne as t,Oe as u,y as v,k as w,S as x,Ee as y,te as z,Ce as A};
@@ -1,2 +0,0 @@
1
- /*! palgres 0.53.0 — Palbase SDK License (see LICENSE) */
2
- import{A as w,a as g,b as C,f as T,g as _}from"./X2B6AJ7P.js";var E={uuid:"uuid",text:"text",integer:"integer",bigint:"bigint",numeric:"numeric",boolean:"boolean",timestamp:"timestamp with time zone",date:"date",jsonb:"jsonb"};function j(e){let n=Array.isArray(e)?e:[e],t={tables:[],enums:[],extensions:[],raw:[]},i=new Map;for(let u of n){for(let o of Object.values(u.tables))t.tables.push(S(u.name,o,i));t.extensions.push(...u.extensions);for(let o of u.raw??[])t.raw.push({name:o.name,schema:u.name,sql:o.up,...o.drop!==void 0?{drop:o.drop}:{},...o.before===!0?{before:!0}:{}})}t.enums=[...i.values()];for(let u of n)for(let o of Object.values(u.tables))for(let d of o.raw??[])t.raw.push({name:d.name,table:`${u.name}.${o.name}`,sql:d.up});return t}function D(e,n){return!n&&C(e.onDelete,e.onUpdate)?{...e,deferrable:!0}:e}function K(e){return e._def}function S(e,n,t){let i=[],u=r=>{let h=n.columns[r];return h!==void 0&&K(h).encrypted?.lookup?g(r):r},o=(n.unique??[]).map(r=>({name:r.name,columns:r.columns.map(u)})),d=[],s=[],a=new Set,m=[];for(let[r,h]of Object.entries(n.columns)){let l=K(h),c={name:r,type:A(e,r,n.name,l,t),nullable:l.nullable},x=q(l);x!==void 0&&(c.default=x),l.renamedFrom!==void 0&&(c.renamedFrom=l.renamedFrom),l.ignored&&(c.ignored=!0),l.fill!==void 0&&(c.fill=l.fill),l.identity!==void 0&&(c.identity=l.identity==="always"?"always":"by default"),l.generated!==void 0&&(c.generated={...l.generated}),l.user!==void 0&&(c.user={...l.user}),l.primaryKey&&s.push(r);let y=l.encrypted?.lookup?g(r):void 0;if(l.encrypted!==void 0&&(c.encrypted=y?{lookup:y}:{}),l.unique&&o.push(y?{name:`${n.name}_${y}_key`,columns:[y]}:{name:`${n.name}_${r}_key`,columns:[r]}),l.references!==void 0){let[b,k]=N(l.references.table);d.push(D({name:`${O(e,n.name)}_${r}_fkey`,columns:[r],refSchema:b,refTable:k,refColumns:[l.references.column],onDelete:l.onDeleteAction??"no action",onUpdate:l.onUpdateAction??"no action"},l.deferrable===!1)),l.index===!1&&a.add(r)}if(i.push(c),y){let b={name:y,type:"text",nullable:!0,lookupOf:r};l.renamedFrom!==void 0&&(b.renamedFrom=g(l.renamedFrom)),l.ignored&&(b.ignored=!0),i.push(b),l.unique||m.push({name:`${n.name}_${y}_idx`,keys:[{column:y}],unique:!1})}}for(let r of n.foreignKeys??[]){r.index===!1&&r.columns.length===1&&a.add(r.columns[0]);let[h,l]=N(r.refTable);d.push(D({name:r.name,columns:[...r.columns],refSchema:h,refTable:l,refColumns:[...r.refColumns],onDelete:r.onDelete??"no action",onUpdate:r.onUpdate??"no action",...r.match==="full"?{match:"full"}:{}},r.deferrable===!1))}let p={schema:e,name:n.name,columns:i,primaryKey:n.primaryKey!==void 0?[...n.primaryKey]:s,uniques:o,indexes:[...(n.indexes??[]).map(B),...m],checks:(n.checks??[]).map(r=>({name:r.name,expr:r.expr})),foreignKeys:d,rls:n.rls,policies:n.policies.map(Q)};return n.ignored&&(p.ignored=!0),n.search!==void 0&&(p.search={...n.search,from:[...n.search.from]}),p.uniques=v(p.uniques),W(p,a,new Set((n.raw??[]).map(r=>r.name)),new Set(n.policies.filter(r=>r.indexes===!1).map(r=>r.name))),p}function A(e,n,t,i,u){let o=i.type;if(o==="enum"||o==="enum[]"){let d=i.enumName,s=`${e}.${d}`,a=i.enumValues??[],m=u.get(s);if(m&&m.values.join()!==a.join())throw new Error(`enum ${s} is declared with different values by ${t}.${n}: (${m.values.join(", ")}) and (${a.join(", ")}) \u2014 one type has one list`);return u.set(s,{schema:e,name:d,values:[...a]}),o==="enum[]"?`${_(e,d)}[]`:_(e,d)}return o==="sql"?T(i.sqlType):o==="numeric"&&i.precision!==void 0?`numeric(${i.precision},${i.scale??0})`:o.endsWith("[]")?`${E[o.slice(0,-2)]??o.slice(0,-2)}[]`:E[o]??o}function q(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 B(e){let n=e.expression!==void 0?[{expr:e.expression}]:(e.columns??[]).map(u=>({column:u}));for(let u of n)e.sort==="desc"&&(u.desc=!0),e.nulls!==void 0&&(u.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 Q(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 W(e,n,t,i){let u=new Set,o=s=>s[0]!==void 0&&u.add(s[0]);o(e.primaryKey);for(let s of e.uniques)o(s.columns);for(let s of e.indexes){let a=s.keys[0];a&&"column"in a&&s.where===void 0&&u.add(a.column)}let d=s=>{if(u.has(s)||e.columns.find(m=>m.name===s)?.ignored)return;let a=`${e.name}_${s}_idx`;Buffer.byteLength(a)>63||e.indexes.some(m=>m.name===a)||t.has(a)||(e.indexes.push({name:a,keys:[{column:s}],unique:!1}),u.add(s))};for(let s of e.foreignKeys)s.columns.length===1&&!n.has(s.columns[0])&&d(s.columns[0]);for(let s of e.policies)if(!i.has(s.name))for(let a of $(e,s))d(a)}function $(e,n){let t=[];for(let i of[n.using,n.withCheck])if(i!==void 0)for(let u of i.matchAll(/(?<![.\w"])"((?:[^"]|"")+)"(?!\s*\.)/g)){let o=u[1].replace(/""/g,'"');e.columns.some(d=>d.name===o)&&!t.includes(o)&&t.push(o)}return t}function N(e){let n=e.indexOf(".");return n<0?["public",e]:[e.slice(0,n),e.slice(n+1)]}function O(e,n){return e==="public"?n:`${e}_${n}`}function v(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 P=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp","date","enum"]),L={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(!P.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 I(){return new f("uuid")}function M(){return new f("text")}function Y(){return new f("integer")}function H(){return new f("bigint")}function J(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 z(){return new f("date")}var R={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 G(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=R[t];if(i!==void 0&&!(n.endsWith("[]")&&!P.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 X=new Set(["smallint","real","double precision"]),Z=new Set(["json"]);function ee(){return new f("boolean")}function ne(){return new f("timestamp")}function te(){return new f("jsonb")}function re(e,n){let t=new f("enum");return t._def.enumName=e,t._def.enumValues=[...n],t}function ie(){let e=new f("text");return e._def.nullable=!1,e._def.user={onDelete:"cascade",owns:!0},e}function oe(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{j as a,$ as b,L as c,f as d,I as e,M as f,Y as g,H as h,J as i,z as j,G as k,X as l,Z as m,ee as n,ne as o,te as p,re as q,ie as r,oe as s};