palgres 0.56.0 → 0.58.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.
- package/dist/chunks/FW3D6LUC.js +584 -0
- package/dist/chunks/NH6VG43U.js +2 -0
- package/dist/chunks/YBTR6MHQ.js +5 -0
- package/dist/dsl.js +2 -2
- package/dist/index.js +122 -122
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/types/access/src/apply.d.ts +7 -0
- package/types/access/src/base.d.ts +40 -2
- package/types/access/src/compile.d.ts +23 -1
- package/types/access/src/errors.d.ts +1 -1
- package/types/access/src/index.d.ts +4 -3
- package/types/access/src/model.d.ts +42 -1
- package/types/access/src/reference.d.ts +7 -3
- package/types/access/src/text.d.ts +19 -2
- package/types/access/src/tree.d.ts +22 -0
- package/types/access/src/world.d.ts +8 -1
- package/types/palgres/src/access.d.ts +22 -0
- package/types/palgres/src/query/access.d.ts +71 -15
- package/types/palgres/src/query/index.d.ts +1 -1
- package/types/palgres/src/testing/access.d.ts +5 -0
- package/dist/chunks/JPYKRUNF.js +0 -5
- package/dist/chunks/LQHZIV3S.js +0 -2
- package/dist/chunks/YTA5WUZJ.js +0 -309
package/dist/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
/*! palgres 0.
|
|
2
|
-
import{a as
|
|
1
|
+
/*! palgres 0.58.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
+
import{a as mr,b as pr,c as rn,l as Xn,m as Vn}from"./chunks/NH6VG43U.js";import{$ as Rn,A as ur,B as dr,C as Ee,D as Gn,E as Tn,F as ki,G as Gt,H as Xt,J as fr,K as Ii,L as Li,M as on,N as Sn,O as Y,P as Vt,Q as Me,R as an,S as Yn,T as hr,U as gr,V as Er,W as Jn,X as zn,Y as Yt,Z as yr,_ as wr,a as N,aa as $r,b as D,ba as Ci,c as v,ca as vi,d as ne,da as xi,e as Re,ea as _i,f as lr,fa as Di,g as Oe,ga as Pi,h as me,ha as bn,i as Kn,ia as Tr,j as bi,ja as Sr,k as Ni,ka as Qn,l as le,la as Zn,m as pe,ma as Rr,n as De,na as br,o as Ai,p as Pe,q as jt,r as Oi,s as nn,t as tn,u as Ht,v as Kt,w as sn,x as Fe,y as ce,z as cr}from"./chunks/YBTR6MHQ.js";import{A as er,C as nr,D as tr,E as Wt,F as sr,L as _e,M as rr,O as or,P as ir,Q as ar,T as be,a as Ks,b as en,c as Ge,d as Mt,e as F,f as ae,g as $n,h as Gs,i as Xs,j as qt,k as ge,l as Vs,m as Xe,n as Ys,q as Js,u as zs,v as Qs,w as Ut,x as Hn,y as Zs,z as Bt}from"./chunks/FW3D6LUC.js";import{createHash as Mr}from"node:crypto";function et(t){return typeof t=="function"?t():Promise.resolve(t)}var Nr="pbe1.";function ln(t,e,n){return t==="public"?`${e}.${n}`:`${t}.${e}.${n}`}var ye="palgres.sealing",nt=5e3,Jt=3*nt,Nn=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let n;try{n=await e(`SELECT address, direction, phase FROM ${ye}`)}catch(s){let r=s.code??s.errno;if(r!=="42P01"&&r!=="3F000")throw s;n=[]}this.going=new Map(n.map(s=>[s.address,{direction:s.direction,phase:s.phase}]))}},An=t=>`"${t.replace(/"/g,'""')}"`;function Ar(t,e){let n=An(t.column);return t.direction==="open"?{sql:`${n} LIKE 'pbe1.%'`,params:[]}:{sql:`(${n} NOT LIKE $1${t.lookup?` OR ${An(t.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function tt(t,e,n,s,r){let o=Ar(e,n),i=An(e.column),a=s===null?"":` AND ctid > $${o.params.length+1}::tid`,l=await t(`SELECT ctid::text AS at, ${i} AS value FROM ${e.table} WHERE ${i} IS NOT NULL AND ${o.sql}${a} ORDER BY ctid LIMIT ${r}`,s===null?o.params:[...o.params,s]);if(l.length===0)return{done:0,last:null};let c=[],d=l.map(m=>{let f=Fi(n,e.address,m.value),g=[m.at,m.value,e.direction==="seal"?n.encrypt(e.address,f):f,...e.lookup?[n.lookup(e.address,f)]:[]],T=c.length+1;return c.push(...g),`(${g.map((h,p)=>`$${T+p}::text`).join(", ")})`}),y=[`${i} = v.next`,...e.lookup?[`${An(e.lookup)} = v.lookup`]:[]],u=await t(`WITH done AS (UPDATE ${e.table} AS t SET ${y.join(", ")} FROM (VALUES ${d.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${i} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,c);return{done:Number(u[0]?.n??0),last:l.length<r?null:l[l.length-1].at}}function Fi(t,e,n){if(!t.isEncrypted(n))return n;try{return t.decrypt(e,n)}catch{return n}}function st(t,e){if(typeof e=="string"&&e.startsWith(Nr))throw new TypeError(`${t} is going over between plain and encrypted: a value beginning ${Nr} would read as an encrypted one \u2014 it is written once the migration completes`)}async function Or(t,e,n){let s=Ar(e,n);return(await t(`SELECT 1 FROM ${e.table} WHERE ${An(e.column)} IS NOT NULL AND ${s.sql} LIMIT 1`,s.params)).length>0}import{createHash as Qt}from"node:crypto";var J="palgres_search",rt=(t,e)=>t.model===e.model&&t.dimensions===e.dimensions&&t.metric===e.metric&&t.from.length===e.from.length&&t.from.every((n,s)=>n===e.from[s]),kr=48;function Be(t,e){let n=t.replaceAll(".","__");return`${n.length<=kr?n:`${n.slice(0,32)}_${Qt("md5").update(n).digest("hex").slice(0,12)}`}__g${e}`}var Ir=t=>({insert:`_palgres_search_g${t}_ins`,update:`_palgres_search_g${t}_upd`});function ot(t,e){let n=Qt("sha256").update(JSON.stringify([t.schema,t.name,e])).digest("hex").slice(0,8),s=`_palgres_search_${t.name}_${n}`;return Buffer.byteLength(s)<=63?s:`_palgres_search_${Qt("sha256").update(`${t.schema}.${t.name}`).digest("hex").slice(0,16)}_${n}`}function it(t,e){let n=e===void 0?"":`${N(e)}.`;return t.map(s=>`coalesce(${n}${N(s)}::text, '')`).join(" || ' ' || ")}var at=(t,e)=>`to_tsvector('simple', ${it(t,e)})`;function On(t,e){let n=t>Gs?"halfvec":"vector",s={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:n,opclass:`${n}_${s[0]}_ops`,operator:s[1]}}function Lr(t){let e=`${t.table.schema}.${t.table.name}`,n=D(t.table.schema,t.table.name),s=Be(e,t.gen),r=D(J,s),o=On(t.search.dimensions,t.search.metric),i=N(t.pk.name),a=[t.roles.anon,t.roles.authenticated].map(N).join(", ");return[`INSERT INTO ${J}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${v(e)}, ${t.gen}, ${v(t.search.model)}, ${t.search.dimensions}, ${v(t.search.metric)}, ARRAY[${t.search.from.map(v).join(", ")}]::text[], ${v(t.status)}, ${t.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${r} (
|
|
3
3
|
id ${t.pk.type} PRIMARY KEY REFERENCES ${n} (${i}) ON DELETE CASCADE,
|
|
4
|
-
embedding ${
|
|
4
|
+
embedding ${N(t.types)}.${o.type}(${t.search.dimensions}) NOT NULL,
|
|
5
5
|
model text NOT NULL,
|
|
6
6
|
embedded_at timestamptz NOT NULL DEFAULT now()
|
|
7
|
-
)`,`CREATE INDEX ON ${r} USING hnsw (embedding ${
|
|
7
|
+
)`,`CREATE INDEX ON ${r} USING hnsw (embedding ${N(t.types)}.${o.opclass})`,`ALTER TABLE ${r} ENABLE ROW LEVEL SECURITY`,`CREATE POLICY ${N("_palgres_search_parent")} ON ${r} FOR SELECT TO ${a} USING (EXISTS (SELECT 1 FROM ${n} p WHERE p.${i} = ${N(s)}.id))`,`GRANT SELECT ON TABLE ${r} TO ${a}`,`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${r} TO ${N(t.roles.service)}`,`CREATE FUNCTION ${r}() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $palgres$
|
|
8
8
|
BEGIN
|
|
9
9
|
-- A generation left behind keeps its triggers until the next migration takes them: they do nothing.
|
|
10
|
-
IF NOT EXISTS (SELECT 1 FROM ${J}.generations g WHERE g.table_key = ${
|
|
10
|
+
IF NOT EXISTS (SELECT 1 FROM ${J}.generations g WHERE g.table_key = ${v(e)} AND g.gen = ${t.gen} AND g.status <> 'retired') THEN
|
|
11
11
|
RETURN NULL;
|
|
12
12
|
END IF;
|
|
13
13
|
-- One pending row per row of the table: written again before it is embedded, it is embedded once, as it is then.
|
|
14
|
-
INSERT INTO ${J}.queue (table_key, gen, row_id) VALUES (${
|
|
14
|
+
INSERT INTO ${J}.queue (table_key, gen, row_id) VALUES (${v(e)}, ${t.gen}, NEW.${i}::text)
|
|
15
15
|
ON CONFLICT ON CONSTRAINT queue_one_pending DO UPDATE SET enqueued_at = clock_timestamp(), attempts = 0, next_attempt_at = now(), last_error = NULL;
|
|
16
16
|
-- After the queue: a worker writing this row's vector holds its queue row until it commits, so what it wrote from the text before this change is what goes here.
|
|
17
17
|
IF TG_OP = 'UPDATE' AND TG_ARGV[0] = 'null' THEN
|
|
18
18
|
DELETE FROM ${r} WHERE id = NEW.${i};
|
|
19
19
|
END IF;
|
|
20
20
|
RETURN NULL;
|
|
21
|
-
END $palgres$`,`REVOKE ALL ON FUNCTION ${r}() FROM PUBLIC`,...
|
|
21
|
+
END $palgres$`,`REVOKE ALL ON FUNCTION ${r}() FROM PUBLIC`,...lt({table:t.table,gen:t.gen,from:t.search.from,staleness:t.search.staleness},!1)]}function lt(t,e){let n=D(t.table.schema,t.table.name),s=`${D(J,Be(`${t.table.schema}.${t.table.name}`,t.gen))}(${v(t.staleness)})`,r=Ir(t.gen),o=e?"CREATE OR REPLACE TRIGGER":"CREATE TRIGGER",i=t.from.map(a=>`OLD.${N(a)} IS DISTINCT FROM NEW.${N(a)}`).join(" OR ");return[`${o} ${N(r.insert)} AFTER INSERT ON ${n} FOR EACH ROW EXECUTE FUNCTION ${s}`,`${o} ${N(r.update)} AFTER UPDATE OF ${t.from.map(N).join(", ")} ON ${n} FOR EACH ROW WHEN (${i}) EXECUTE FUNCTION ${s}`]}function Cr(t,e,n){return`INSERT INTO ${J}.queue (table_key, gen, row_id) SELECT ${v(`${t.schema}.${t.name}`)}, ${e}, ${N(n)}::text FROM ${D(t.schema,t.name)} ON CONFLICT ON CONSTRAINT queue_one_pending DO NOTHING`}function ct(t,e){let n=`${t.schema}.${t.name}`,s=D(t.schema,t.name),r=D(J,Be(n,e)),o=Ir(e);return[`DROP TRIGGER IF EXISTS ${N(o.insert)} ON ${s}`,`DROP TRIGGER IF EXISTS ${N(o.update)} ON ${s}`,`DROP TABLE IF EXISTS ${r}`,`DROP FUNCTION IF EXISTS ${r}()`,`DELETE FROM ${J}.queue WHERE table_key = ${v(n)} AND gen = ${e}`,`DELETE FROM ${J}.generations WHERE table_key = ${v(n)} AND gen = ${e}`]}var ut=t=>`palgres search 1 (${t.anon}, ${t.authenticated}, ${t.service})`;function vr(t){let e=[t.anon,t.authenticated,t.service].map(N).join(", "),n=N(t.service),s=J;return[`CREATE SCHEMA IF NOT EXISTS ${s}`,`CREATE TABLE IF NOT EXISTS ${s}.generations (
|
|
22
22
|
table_key text NOT NULL,
|
|
23
23
|
gen integer NOT NULL,
|
|
24
24
|
model text NOT NULL,
|
|
@@ -41,7 +41,7 @@ END $palgres$`,`REVOKE ALL ON FUNCTION ${r}() FROM PUBLIC`,...at({table:t.table,
|
|
|
41
41
|
CONSTRAINT queue_one_pending UNIQUE (table_key, gen, row_id),
|
|
42
42
|
CONSTRAINT queue_due UNIQUE (next_attempt_at, enqueued_at, id)
|
|
43
43
|
)`,`GRANT USAGE ON SCHEMA ${s} TO ${e}`,`GRANT SELECT ON TABLE ${s}.generations TO ${e}`,`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${s}.queue TO ${n}`,`GRANT USAGE, SELECT ON SEQUENCE ${s}.queue_id_seq TO ${n}`,`CREATE OR REPLACE FUNCTION ${s}.vectors(of_table text, gen integer) RETURNS text LANGUAGE sql IMMUTABLE SET search_path = pg_catalog, pg_temp AS $palgres$
|
|
44
|
-
SELECT CASE WHEN length(b) <= ${
|
|
44
|
+
SELECT CASE WHEN length(b) <= ${kr} THEN b ELSE left(b, 32) || '_' || left(md5(b), 12) END || '__g' || gen FROM (SELECT replace(of_table, '.', '__') AS b) x
|
|
45
45
|
$palgres$`,`CREATE OR REPLACE FUNCTION ${s}.promote(of_table text) RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $palgres$
|
|
46
46
|
DECLARE
|
|
47
47
|
g ${s}.generations%ROWTYPE;
|
|
@@ -67,73 +67,73 @@ BEGIN
|
|
|
67
67
|
UPDATE ${s}.generations SET status = 'retired' WHERE table_key = of_table AND status = 'active';
|
|
68
68
|
UPDATE ${s}.generations SET status = 'active', promoted_at = now() WHERE table_key = of_table AND gen = g.gen;
|
|
69
69
|
RETURN g.gen;
|
|
70
|
-
END $palgres$`,`REVOKE ALL ON FUNCTION ${s}.promote(text) FROM PUBLIC`,`GRANT EXECUTE ON FUNCTION ${s}.promote(text) TO ${n}`,`COMMENT ON SCHEMA ${s} IS ${x(ct(t))}`]}var Yt=new Set,ut={listen(t){return Yt.add(t),()=>{Yt.delete(t)}},committed(){for(let t of Yt)t()}};var xr=new Set(["tx","statement","backfill","seal","settle"]),es=2;function vi(...t){return t.some(e=>e.some(n=>n.kind==="seal"||n.kind==="settle"))?2:1}var Le=(t,e)=>`palgres_${t}_${e}`,ns=t=>vr("sha256").update(t).digest("hex").slice(0,8),dt=(t,e)=>`${t.name}_${e}_${ns(JSON.stringify([t.schema,t.name,e])).slice(0,6)}`,te=(t,e,n)=>{let s=`_palgres_${t}_${e}_${n}`;return Buffer.byteLength(s)<=63?s:`_palgres_${t}_${e}_${ns(n)}`},On={anon:"anon",backend_anon:"anon",authenticated:"authenticated",backend_authenticated:"authenticated",service_role:"service",backend_service_role:"service",public:"public"},ft=t=>!t.nullable&&t.default===void 0&&!t.identity&&!t.generated,Ve=t=>t.ignored===!0&&t.fill!==void 0&&ft(t),xi=t=>{if(t.generated||t.identity)return;let e=b(t.name);return t.default===void 0?`${e} IS NOT NULL`:`${e}::text IS DISTINCT FROM (${t.default})::text`},Or="the version serving now reads that value in the rows the new version writes",_i={smallint:["integer","bigint","numeric"],integer:["bigint","numeric"],bigint:["numeric"],real:["double precision"],"character varying":["text"],text:["character varying"]};function Qt(t,e){let n=ae(t),s=ae(e);if(_i[n]?.includes(s))return!0;let r=a=>/^character varying\((\d+)\)$/.exec(a)?.[1],o=r(n);if(o===void 0)return!1;let i=r(s);return s==="text"||s==="character varying"||i!==void 0&&Number(i)>=Number(o)}var kn=t=>{let e=ae(t);if(["smallint","integer","bigint"].includes(e))return"integer";if(e==="text"||/^character varying(\(\d+\))?$/.test(e))return"text"},Di=(t,e)=>kn(t)!==void 0&&kn(t)===kn(e)&&Qt(t,e),Pi="data_exception OR integrity_constraint_violation",kr="palgres: every value converted";function ts(t){return new Zt(t).run()}var Zt=class{from;to;fromN;n;input;changes=[];refusals=[];matches=new Map;fromMatched=new Set;prelude=[];creates=[];createFks=[];alters=[];backfills=[];online=[];settle=[];lateFks=[];searchStart=[];searchComplete=[];undoSearch=[];viewsAtComplete=null;namesAtComplete=!1;dropsColumnsAtComplete=!1;completeUnitDrops=[];raws=[];sealingStart=[];sealingComplete=[];sealingUndo=[];completeTables=[];completeIndexes=[];completeFks=[];completeAfter=[];completeDrops=[];completeDropsFoundEmpty=[];guarded={tables:[],columns:[]};completeTypes=[];undoTables=[];undoOnline=[];fkDrops=[];undoFksGone=[];undoIndexesGone=[];undoFksBack=[];undoRawsGone=[];undoRawsBack=[];undoCreates=[];undoNewTables=[];layout={tables:[]};toAccess=null;toRecorded=null;fromRecorded=null;accessPolicies=[];accessGuard=[];accessStart=[];accessComplete=[];accessUndo=[];constructor(e){this.input=e,this.from=he(e.from?.schema??Mt());let n=new Map((e.from?.schema.raw??[]).map((r,o)=>[r.name,o]));this.from.raw.sort((r,o)=>(n.get(r.name)??0)-(n.get(o.name)??0)),this.to=he(e.to);let s=new Map(e.to.raw.map((r,o)=>[r.name,o]));this.to.raw.sort((r,o)=>(s.get(r.name)??0)-(s.get(o.name)??0)),this.fromN=e.from?.n??null,this.n=e.next,this.fromRecorded=e.from?.access??null}run(){this.compileAccess(),this.extensions(),this.schemas(),this.enums(),this.rawUnitsBefore(),this.matchTables();for(let o of this.to.tables){let i=this.matches.get(F(o));i?(this.alterTable(i),this.encryption(i)):this.createTable(o),this.search(o,i)}for(let o of this.from.tables)this.fromMatched.has(o)||this.dropTable(o);this.access(),this.rawUnits(),this.enumDrops();let e=[...this.accessGuard,...this.prelude,...this.creates.length+this.createFks.length>0?[{kind:"tx",sql:[...this.creates,...this.createFks],why:"the new tables and types"}]:[],...this.fkDrops,...this.alters,...this.backfills,...this.online,...this.settle,...this.lateFks,...this.searchStart,...this.raws,...this.sealingStart,...this.accessStart,{kind:"tx",sql:this.views(),why:`version ${this.n}'s views`}],n=[...this.sealingComplete,...this.fromN!==null?[{kind:"tx",sql:this.dropViews(this.fromN,this.from),why:`version ${this.fromN}'s views`}]:[],...this.accessComplete,...this.searchComplete,...this.completeFks,...this.viewsAtComplete?[{kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.completeUnitDrops,...this.viewsAtComplete.drops,...this.completeTables.flatMap(o=>o.kind==="tx"?o.sql:[]),...this.viewsAtComplete.creates],why:"the tables, and the views that read them, at once"}]:[...this.completeUnitDrops.length>0?[{kind:"tx",sql:this.completeUnitDrops,why:"the triggers and rules gone"}]:[],...this.completeTables],...this.completeIndexes,...this.completeAfter,...this.completeDrops.length>0?[{kind:"tx",sql:[this.dropTables()],why:"the dropped tables"}]:[],...this.completeTypes.length>0?[{kind:"tx",sql:this.completeTypes,why:"the dropped types, and the functions of the dropped tables"}]:[]],s=[...this.sealingUndo,{kind:"tx",sql:this.dropViews(this.n,this.to),why:`version ${this.n}'s views`},...this.accessUndo,...this.undoSearch,...this.undoFksGone,...this.undoRawsGone.length>0?[{kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.undoRawsGone],why:"the units start made, taken back"}]:[],...[...this.undoTables].reverse(),...this.undoIndexesGone,...this.undoFksBack,...this.undoRawsBack.length>0?[{kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.undoRawsBack],why:"the units start replaced, back"}]:[],...this.undoOnline,...this.undoNewTables.length+this.undoCreates.length>0?[{kind:"tx",sql:[...this.undoNewTables.length>0?[`DROP TABLE IF EXISTS ${this.undoNewTables.join(", ")}`]:[],...[...this.undoCreates].reverse()],why:"the new tables and types"}]:[]],r=this.guarded.tables.length+this.guarded.columns.length+(this.guarded.retyped?.length??0)>0?{guarded:this.guarded}:{};return this.toRecorded&&(this.layout.access=this.toRecorded),{format:vi(e,n,s),from:this.fromN,to:this.n,changes:this.changes,refusals:this.refusals,start:e,complete:n,rollback:s,layout:this.layout,...r}}dropTables(){let e=`DROP TABLE IF EXISTS ${this.completeDrops.join(", ")}`;if(this.completeDropsFoundEmpty.length===0)return e;let n=this.completeDropsFoundEmpty.map(r=>`EXISTS (SELECT 1 FROM ${r})`).join(" OR "),s=x("tables gone from the schema hold rows the version before wrote while this one rolled out: they are kept, outside the schema");return`DO $palgres$ BEGIN IF ${n} THEN RAISE WARNING 'palgres: %', ${s}; ELSE ${e}; END IF; END $palgres$`}refuse(e,n){this.refusals.push(`${e}: ${n}`)}encryption(e){let n=F(e.to),s=this.input.hasRows(F(e.from)),r=new Map(e.from.columns.map(i=>[i.name,i])),o=new Map([...e.renamed].map(([i,a])=>[a,i]));for(let i of e.to.columns){if(i.lookupOf!==void 0)continue;let a=r.get(o.get(i.name)??i.name);if(a===void 0||e.parked.has(i.name))continue;let l=i.encrypted!==void 0,c=a.encrypted!==void 0;if(!l&&!c)continue;if(s&&(a.name!==i.name||e.from.name!==e.to.name)){this.refuse(`column ${n}.${i.name} is encrypted and is renamed (or its table is) while the table holds rows: its values are bound to ${an(e.from.schema,e.from.name,a.name)}`,"keep its name; to move the values, add a new encrypted column, write them into it from the app, and ignore the old one");continue}if(l===c)continue;if(e.retyped.has(i.name)){this.refuse(`column ${n}.${i.name} changes its type and its encryption in one deploy`,"change one, deploy, then the other");continue}if(!s)continue;let d=an(e.to.schema,e.to.name,i.name);if(l&&i.encrypted?.lookup){let f=i.encrypted.lookup,h=e.to.uniques.some(g=>g.columns.includes(f))||e.to.indexes.some(g=>g.unique&&g.keys.some(p=>"column"in p&&p.column===f)),T=e.from.uniques.some(g=>g.columns.length===1&&g.columns[0]===a.name)||e.from.indexes.some(g=>g.unique&&g.keys.length===1&&"column"in g.keys[0]&&g.keys[0].column===a.name);if(h&&!T){this.refuse(`column ${n}.${i.name} becomes encrypted and unique in one deploy while the table holds rows`,"make it .unique() first and deploy \u2014 the rows are checked while they are plain \u2014 then encrypt it");continue}}let w=l?"seal":"open",u=x(d);this.changes.push(`column ${n}.${i.name} ${l?"becomes encrypted: its rows are sealed":"stops being encrypted: its rows are opened"} at complete`),this.sealingStart.push({kind:"tx",sql:[`INSERT INTO ${ye} (address, direction, phase) VALUES (${u}, ${x(w)}, 'mixed') ON CONFLICT (address) DO UPDATE SET direction = EXCLUDED.direction, phase = 'mixed'`],why:`${d} goes over: the old version's form kept while it serves`}),w==="open"&&this.sealingStart.push({kind:"settle",ms:Vt,why:`the version serving reads that ${d} goes over`});let m=l&&i.encrypted?.lookup?e.cols.get(i.encrypted.lookup)??i.encrypted.lookup:null;if(this.sealingComplete.push({kind:"tx",sql:[`UPDATE ${ye} SET phase = 'final' WHERE address = ${u}`],why:`${d}: the old version is gone, the new form is written`},{kind:"seal",table:M(e.from.schema,e.physical),column:a.name,lookup:m,address:d,direction:w,why:`${d}'s rows ${l?"sealed":"opened"}`},{kind:"tx",sql:[`DELETE FROM ${ye} WHERE address = ${u}`],why:`${d} has gone over`}),w==="open"){let f=a.encrypted?.lookup??null;this.sealingUndo.push({kind:"seal",table:M(e.from.schema,e.physical),column:a.name,lookup:f,address:d,direction:"seal",why:`${d}'s rows the abandoned version wrote plain, sealed again`})}this.sealingUndo.push({kind:"tx",sql:[`DELETE FROM ${ye} WHERE address = ${u}`],why:`${d} no longer goes over`})}}extensions(){for(let e of this.to.extensions)this.from.extensions.includes(e)||(this.changes.push(`extension ${e}`),this.prelude.push({kind:"statement",sql:`CREATE EXTENSION IF NOT EXISTS ${b(e)}`,why:`extension ${e}`}))}schemas(){let e=new Set([...this.from.tables.map(i=>i.schema),...this.from.enums.map(i=>i.schema),...this.from.raw.flatMap(i=>i.schema?[i.schema]:[]),"public"]),n=[...new Set([...this.to.tables.map(i=>i.schema),...this.to.enums.map(i=>i.schema),...this.to.raw.flatMap(i=>i.schema?[i.schema]:[])])].filter(i=>!e.has(i)),{anon:s,authenticated:r,service:o}=this.input.roles;for(let i of n)this.changes.push(`schema ${i}`),this.creates.push(`CREATE SCHEMA IF NOT EXISTS ${b(i)}`,`GRANT USAGE ON SCHEMA ${b(i)} TO ${[s,r,o].map(b).join(", ")}`)}enums(){for(let e of this.to.enums){let n=this.from.enums.find(o=>o.schema===e.schema&&o.name===e.name),s=M(e.schema,e.name);if(!n){this.changes.push(`type ${e.schema}.${e.name}`),this.creates.push(`CREATE TYPE ${s} AS ENUM (${e.values.map(x).join(", ")})`),this.undoCreates.push(`DROP TYPE IF EXISTS ${s}`);continue}let r=n.values.filter(o=>!e.values.includes(o));r.length>0&&this.refuse(`type ${e.schema}.${e.name} loses ${r.join(", ")}`,"Postgres cannot take a value out of an enum; add a new type and move the column to it");for(let o of e.values)n.values.includes(o)||(this.changes.push(`type ${e.schema}.${e.name} gains '${o}'`),this.prelude.push({kind:"statement",sql:`ALTER TYPE ${s} ADD VALUE IF NOT EXISTS ${x(o)}`,why:`${e.name} gains ${o}`}))}}enumDrops(){for(let e of this.from.enums)this.to.enums.some(n=>n.schema===e.schema&&n.name===e.name)||(this.changes.push(`type ${e.schema}.${e.name} goes (at complete)`),this.completeTypes.push(`DROP TYPE IF EXISTS ${M(e.schema,e.name)}`))}matchTables(){let e=new Map(this.from.tables.map(n=>[F(n),n]));for(let n of this.to.tables)n.renamedFrom===void 0||n.renamedFrom===n.name||!e.has(`${n.schema}.${n.renamedFrom}`)||this.to.tables.some(s=>s!==n&&s.schema===n.schema&&s.name===n.renamedFrom)&&this.refuse(`table ${n.schema}.${n.renamedFrom} is renamed ${n.name}, and a new table takes the name ${n.renamedFrom} in the same deploy`,`rename it in this deploy, and make the new ${n.renamedFrom} in the next`);for(let n of this.to.tables){let s=e.get(F(n));if(n.renamedFrom!==void 0&&n.renamedFrom!==n.name){let r=e.get(`${n.schema}.${n.renamedFrom}`);s&&r&&this.refuse(`table ${F(n)} is renamed from ${n.renamedFrom}, but ${F(n)} is there already`,"remove renamedFrom, or rename to a free name"),!s&&r&&(s=r)}!s||this.fromMatched.has(s)||(this.fromMatched.add(s),this.matches.set(F(n),this.matchColumns(n,s)))}}matchColumns(e,n){let s=F(e),r=new Map(n.columns.map(l=>[l.name,l])),o={to:e,from:n,physical:n.name,renamed:new Map,cols:new Map,retyped:new Map,parked:new Map},i=new Set,a=new Set(e.columns.filter(l=>l.renamedFrom!==void 0&&l.renamedFrom!==l.name&&r.has(l.renamedFrom)&&!r.has(l.name)).map(l=>l.renamedFrom));for(let l of e.columns){let c=a.has(l.name)?void 0:r.get(l.name);if(l.renamedFrom!==void 0&&l.renamedFrom!==l.name&&r.has(l.renamedFrom)&&(r.has(l.name)?this.refuse(`column ${s}.${l.name} is renamed from ${l.renamedFrom}, but ${l.name} is there already`,"remove renamedFrom, or rename to a free name"):c=r.get(l.renamedFrom)),!c&&a.has(l.name)){let d=te(this.n,"add",l.name);o.parked.set(l.name,d),o.cols.set(l.name,d);continue}if(!c||i.has(c.name)){o.cols.set(l.name,l.name);continue}if(i.add(c.name),c.name!==l.name&&o.renamed.set(c.name,l.name),ae(c.type)!==ae(l.type)){let d=te(this.n,"new",l.name);o.retyped.set(l.name,{shadow:d,from:c,to:l}),o.cols.set(l.name,d)}else o.cols.set(l.name,c.name)}return o}inNewNames(e){let s=[...this.matches.values()].find(i=>i.from===e)?.renamed??new Map,r=i=>s.get(i)??i,o=i=>me(i,s);return{...e,uniques:e.uniques.map(i=>({...i,columns:i.columns.map(r)})),indexes:e.indexes.map(i=>({...i,keys:i.keys.map(a=>"column"in a?{...a,column:r(a.column)}:{...a,expr:o(a.expr)}),include:i.include?.map(r),where:i.where===void 0?void 0:o(i.where)})),checks:e.checks.map(i=>({...i,expr:o(i.expr)})),foreignKeys:e.foreignKeys.map(i=>this.fkInNewNames(i,r)),policies:e.policies.map(i=>({...i,using:i.using===void 0?void 0:o(i.using),withCheck:i.withCheck===void 0?void 0:o(i.withCheck)})),primaryKey:e.primaryKey.map(r)}}fkInNewNames(e,n){let s=this.from.tables.find(o=>o.schema===e.refSchema&&o.name===e.refTable),r=s&&[...this.matches.values()].find(o=>o.from===s);return{...e,columns:e.columns.map(n),refTable:r?r.to.name:e.refTable,refColumns:e.refColumns.map(o=>r?.renamed.get(o)??o)}}where(e){let n=this.matches.get(F(e));return n?{table:n.physical,cols:n.cols}:{table:e.name,cols:new Map(e.columns.map(s=>[s.name,s.name]))}}grants(e){let{anon:n,authenticated:s,service:r}=this.input.roles;return[`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${e} TO ${[n,s,r].map(b).join(", ")}`]}typeSql(e){let n=/^([a-z_][a-z0-9_]*)\.([a-z_][a-z0-9_]*)((?:\[\])*)$/i.exec(e);return n?`${M(n[1],n[2])}${n[3]}`:e}columnSql(e){let n=`${b(e.name)} ${this.typeSql(e.type)}`;return e.identity&&(n+=` GENERATED ${e.identity==="always"?"ALWAYS":"BY DEFAULT"} AS IDENTITY`),e.generated&&(n+=` GENERATED ALWAYS AS (${e.generated.expr}) ${e.generated.stored?"STORED":"VIRTUAL"}`),e.default!==void 0&&(n+=` DEFAULT ${e.default}`),e.nullable||(n+=" NOT NULL"),n}sequences(e,n,s,r){let{anon:o,authenticated:i,service:a}=this.input.roles;for(let l of Ir(n.default)){let c=new RegExp(String.raw`\bCREATE\s+SEQUENCE\s+(?:IF\s+NOT\s+EXISTS\s+)?${l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\w$"])`,"i");if(this.to.raw.some(d=>c.test(d.sql))){r.push(`GRANT USAGE, SELECT ON SEQUENCE ${l} TO ${[o,i,a].map(b).join(", ")}`);continue}s.push(`CREATE SEQUENCE IF NOT EXISTS ${l}`),r.push(`ALTER SEQUENCE ${l} OWNED BY ${M(e.schema,e.name)}.${b(n.name)}`,`GRANT USAGE, SELECT ON SEQUENCE ${l} TO ${[o,i,a].map(b).join(", ")}`)}}createTable(e){let n=M(e.schema,e.name),s=new Map(e.columns.map(l=>[l.name,l.name]));this.changes.push(`table ${F(e)}`);let r=[];for(let l of e.columns)this.sequences(e,l,this.creates,r);let o=e.columns.map(l=>this.columnSql(l)),i=new Set,a=[];e.primaryKey.length>0&&(o.push(`PRIMARY KEY (${Re(e.primaryKey)})`),i.add(e.primaryKey.join("\0")));for(let l of e.uniques){let c=l.columns.join("\0");i.has(c)?a.push(`ALTER TABLE ${n} ADD CONSTRAINT ${b(l.name)} UNIQUE (${Re(l.columns)})`):o.push(`CONSTRAINT ${b(l.name)} UNIQUE (${Re(l.columns)})`),i.add(c)}for(let l of e.checks)o.push(`CONSTRAINT ${b(l.name)} CHECK (${l.expr})`);this.creates.push(`CREATE TABLE ${n} (
|
|
70
|
+
END $palgres$`,`REVOKE ALL ON FUNCTION ${s}.promote(text) FROM PUBLIC`,`GRANT EXECUTE ON FUNCTION ${s}.promote(text) TO ${n}`,`COMMENT ON SCHEMA ${s} IS ${v(ut(t))}`]}var zt=new Set,dt={listen(t){return zt.add(t),()=>{zt.delete(t)}},committed(){for(let t of zt)t()}};var qr=new Set(["tx","statement","backfill","seal","settle"]),ts=2;function Mi(...t){return t.some(e=>e.some(n=>n.kind==="seal"||n.kind==="settle"))?2:1}var Ie=(t,e)=>`palgres_${t}_${e}`,ss=t=>Mr("sha256").update(t).digest("hex").slice(0,8),mt=(t,e)=>`${t.name}_${e}_${ss(JSON.stringify([t.schema,t.name,e])).slice(0,6)}`,te=(t,e,n)=>{let s=`_palgres_${t}_${e}_${n}`;return Buffer.byteLength(s)<=63?s:`_palgres_${t}_${e}_${ss(n)}`},Ve={anon:"anon",backend_anon:"anon",authenticated:"authenticated",backend_authenticated:"authenticated",service_role:"service",backend_service_role:"service",public:"public"},ht=t=>!t.nullable&&t.default===void 0&&!t.identity&&!t.generated,Ye=t=>t.ignored===!0&&t.fill!==void 0&&ht(t),qi=t=>{if(t.generated||t.identity)return;let e=N(t.name);return t.default===void 0?`${e} IS NOT NULL`:`${e}::text IS DISTINCT FROM (${t.default})::text`},xr="the version serving now reads that value in the rows the new version writes",Ui={smallint:["integer","bigint","numeric"],integer:["bigint","numeric"],bigint:["numeric"],real:["double precision"],"character varying":["text"],text:["character varying"]};function es(t,e){let n=ae(t),s=ae(e);if(Ui[n]?.includes(s))return!0;let r=a=>/^character varying\((\d+)\)$/.exec(a)?.[1],o=r(n);if(o===void 0)return!1;let i=r(s);return s==="text"||s==="character varying"||i!==void 0&&Number(i)>=Number(o)}var kn=t=>{let e=ae(t);if(["smallint","integer","bigint"].includes(e))return"integer";if(e==="text"||/^character varying(\(\d+\))?$/.test(e))return"text"},Bi=(t,e)=>kn(t)!==void 0&&kn(t)===kn(e)&&es(t,e),Wi="data_exception OR integrity_constraint_violation",_r="palgres: every value converted";function rs(t){return new ns(t).run()}var ns=class{from;to;fromN;n;input;changes=[];refusals=[];matches=new Map;fromMatched=new Set;prelude=[];creates=[];createFks=[];alters=[];backfills=[];online=[];settle=[];lateFks=[];searchStart=[];searchComplete=[];undoSearch=[];viewsAtComplete=null;namesAtComplete=!1;dropsColumnsAtComplete=!1;completeUnitDrops=[];raws=[];sealingStart=[];sealingComplete=[];sealingUndo=[];completeTables=[];completeIndexes=[];completeFks=[];completeAfter=[];completeDrops=[];completeDropsFoundEmpty=[];guarded={tables:[],columns:[]};completeTypes=[];undoTables=[];undoOnline=[];fkDrops=[];undoFksGone=[];undoIndexesGone=[];undoFksBack=[];undoRawsGone=[];undoRawsBack=[];undoCreates=[];undoNewTables=[];layout={tables:[]};toAccess=null;toRecorded=null;fromRecorded=null;accessPolicies=[];accessGuard=[];accessStart=[];accessComplete=[];accessUndo=[];constructor(e){this.input=e,this.from=ge(e.from?.schema??Mt());let n=new Map((e.from?.schema.raw??[]).map((r,o)=>[r.name,o]));this.from.raw.sort((r,o)=>(n.get(r.name)??0)-(n.get(o.name)??0)),this.to=ge(e.to);let s=new Map(e.to.raw.map((r,o)=>[r.name,o]));this.to.raw.sort((r,o)=>(s.get(r.name)??0)-(s.get(o.name)??0)),this.fromN=e.from?.n??null,this.n=e.next,this.fromRecorded=e.from?.access??null}run(){this.compileAccess(),this.extensions(),this.schemas(),this.enums(),this.rawUnitsBefore(),this.matchTables();for(let o of this.to.tables){let i=this.matches.get(F(o));i?(this.alterTable(i),this.encryption(i)):this.createTable(o),this.search(o,i)}for(let o of this.from.tables)this.fromMatched.has(o)||this.dropTable(o);this.access(),this.rawUnits(),this.enumDrops();let e=[...this.accessGuard,...this.prelude,...this.creates.length+this.createFks.length>0?[{kind:"tx",sql:[...this.creates,...this.createFks],why:"the new tables and types"}]:[],...this.fkDrops,...this.alters,...this.backfills,...this.online,...this.settle,...this.lateFks,...this.searchStart,...this.raws,...this.sealingStart,...this.accessStart,{kind:"tx",sql:this.views(),why:`version ${this.n}'s views`}],n=[...this.sealingComplete,...this.fromN!==null?[{kind:"tx",sql:this.dropViews(this.fromN,this.from),why:`version ${this.fromN}'s views`}]:[],...this.accessComplete,...this.searchComplete,...this.completeFks,...this.viewsAtComplete?[{kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.completeUnitDrops,...this.viewsAtComplete.drops,...this.completeTables.flatMap(o=>o.kind==="tx"?o.sql:[]),...this.viewsAtComplete.creates],why:"the tables, and the views that read them, at once"}]:[...this.completeUnitDrops.length>0?[{kind:"tx",sql:this.completeUnitDrops,why:"the triggers and rules gone"}]:[],...this.completeTables],...this.completeIndexes,...this.completeAfter,...this.completeDrops.length>0?[{kind:"tx",sql:[this.dropTables()],why:"the dropped tables"}]:[],...this.completeTypes.length>0?[{kind:"tx",sql:this.completeTypes,why:"the dropped types, and the functions of the dropped tables"}]:[]],s=[...this.sealingUndo,{kind:"tx",sql:this.dropViews(this.n,this.to),why:`version ${this.n}'s views`},...this.accessUndo,...this.undoSearch,...this.undoFksGone,...this.undoRawsGone.length>0?[{kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.undoRawsGone],why:"the units start made, taken back"}]:[],...[...this.undoTables].reverse(),...this.undoIndexesGone,...this.undoFksBack,...this.undoRawsBack.length>0?[{kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.undoRawsBack],why:"the units start replaced, back"}]:[],...this.undoOnline,...this.undoNewTables.length+this.undoCreates.length>0?[{kind:"tx",sql:[...this.undoNewTables.length>0?[`DROP TABLE IF EXISTS ${this.undoNewTables.join(", ")}`]:[],...[...this.undoCreates].reverse()],why:"the new tables and types"}]:[]],r=this.guarded.tables.length+this.guarded.columns.length+(this.guarded.retyped?.length??0)>0?{guarded:this.guarded}:{};return this.toRecorded&&(this.layout.access=this.toRecorded),{format:Mi(e,n,s),from:this.fromN,to:this.n,changes:this.changes,refusals:this.refusals,start:e,complete:n,rollback:s,layout:this.layout,...r}}dropTables(){let e=`DROP TABLE IF EXISTS ${this.completeDrops.join(", ")}`;if(this.completeDropsFoundEmpty.length===0)return e;let n=this.completeDropsFoundEmpty.map(r=>`EXISTS (SELECT 1 FROM ${r})`).join(" OR "),s=v("tables gone from the schema hold rows the version before wrote while this one rolled out: they are kept, outside the schema");return`DO $palgres$ BEGIN IF ${n} THEN RAISE WARNING 'palgres: %', ${s}; ELSE ${e}; END IF; END $palgres$`}refuse(e,n){this.refusals.push(`${e}: ${n}`)}encryption(e){let n=F(e.to),s=this.input.hasRows(F(e.from)),r=new Map(e.from.columns.map(i=>[i.name,i])),o=new Map([...e.renamed].map(([i,a])=>[a,i]));for(let i of e.to.columns){if(i.lookupOf!==void 0)continue;let a=r.get(o.get(i.name)??i.name);if(a===void 0||e.parked.has(i.name))continue;let l=i.encrypted!==void 0,c=a.encrypted!==void 0;if(!l&&!c)continue;if(s&&(a.name!==i.name||e.from.name!==e.to.name)){this.refuse(`column ${n}.${i.name} is encrypted and is renamed (or its table is) while the table holds rows: its values are bound to ${ln(e.from.schema,e.from.name,a.name)}`,"keep its name; to move the values, add a new encrypted column, write them into it from the app, and ignore the old one");continue}if(l===c)continue;if(e.retyped.has(i.name)){this.refuse(`column ${n}.${i.name} changes its type and its encryption in one deploy`,"change one, deploy, then the other");continue}if(!s)continue;let d=ln(e.to.schema,e.to.name,i.name);if(l&&i.encrypted?.lookup){let f=i.encrypted.lookup,g=e.to.uniques.some(h=>h.columns.includes(f))||e.to.indexes.some(h=>h.unique&&h.keys.some(p=>"column"in p&&p.column===f)),T=e.from.uniques.some(h=>h.columns.length===1&&h.columns[0]===a.name)||e.from.indexes.some(h=>h.unique&&h.keys.length===1&&"column"in h.keys[0]&&h.keys[0].column===a.name);if(g&&!T){this.refuse(`column ${n}.${i.name} becomes encrypted and unique in one deploy while the table holds rows`,"make it .unique() first and deploy \u2014 the rows are checked while they are plain \u2014 then encrypt it");continue}}let y=l?"seal":"open",u=v(d);this.changes.push(`column ${n}.${i.name} ${l?"becomes encrypted: its rows are sealed":"stops being encrypted: its rows are opened"} at complete`),this.sealingStart.push({kind:"tx",sql:[`INSERT INTO ${ye} (address, direction, phase) VALUES (${u}, ${v(y)}, 'mixed') ON CONFLICT (address) DO UPDATE SET direction = EXCLUDED.direction, phase = 'mixed'`],why:`${d} goes over: the old version's form kept while it serves`}),y==="open"&&this.sealingStart.push({kind:"settle",ms:Jt,why:`the version serving reads that ${d} goes over`});let m=l&&i.encrypted?.lookup?e.cols.get(i.encrypted.lookup)??i.encrypted.lookup:null;if(this.sealingComplete.push({kind:"tx",sql:[`UPDATE ${ye} SET phase = 'final' WHERE address = ${u}`],why:`${d}: the old version is gone, the new form is written`},{kind:"seal",table:D(e.from.schema,e.physical),column:a.name,lookup:m,address:d,direction:y,why:`${d}'s rows ${l?"sealed":"opened"}`},{kind:"tx",sql:[`DELETE FROM ${ye} WHERE address = ${u}`],why:`${d} has gone over`}),y==="open"){let f=a.encrypted?.lookup??null;this.sealingUndo.push({kind:"seal",table:D(e.from.schema,e.physical),column:a.name,lookup:f,address:d,direction:"seal",why:`${d}'s rows the abandoned version wrote plain, sealed again`})}this.sealingUndo.push({kind:"tx",sql:[`DELETE FROM ${ye} WHERE address = ${u}`],why:`${d} no longer goes over`})}}extensions(){for(let e of this.to.extensions)this.from.extensions.includes(e)||(this.changes.push(`extension ${e}`),this.prelude.push({kind:"statement",sql:`CREATE EXTENSION IF NOT EXISTS ${N(e)}`,why:`extension ${e}`}))}schemas(){let e=new Set([...this.from.tables.map(i=>i.schema),...this.from.enums.map(i=>i.schema),...this.from.raw.flatMap(i=>i.schema?[i.schema]:[]),"public"]),n=[...new Set([...this.to.tables.map(i=>i.schema),...this.to.enums.map(i=>i.schema),...this.to.raw.flatMap(i=>i.schema?[i.schema]:[])])].filter(i=>!e.has(i)),{anon:s,authenticated:r,service:o}=this.input.roles;for(let i of n)this.changes.push(`schema ${i}`),this.creates.push(`CREATE SCHEMA IF NOT EXISTS ${N(i)}`,`GRANT USAGE ON SCHEMA ${N(i)} TO ${[s,r,o].map(N).join(", ")}`)}enums(){for(let e of this.to.enums){let n=this.from.enums.find(o=>o.schema===e.schema&&o.name===e.name),s=D(e.schema,e.name);if(!n){this.changes.push(`type ${e.schema}.${e.name}`),this.creates.push(`CREATE TYPE ${s} AS ENUM (${e.values.map(v).join(", ")})`),this.undoCreates.push(`DROP TYPE IF EXISTS ${s}`);continue}let r=n.values.filter(o=>!e.values.includes(o));r.length>0&&this.refuse(`type ${e.schema}.${e.name} loses ${r.join(", ")}`,"Postgres cannot take a value out of an enum; add a new type and move the column to it");for(let o of e.values)n.values.includes(o)||(this.changes.push(`type ${e.schema}.${e.name} gains '${o}'`),this.prelude.push({kind:"statement",sql:`ALTER TYPE ${s} ADD VALUE IF NOT EXISTS ${v(o)}`,why:`${e.name} gains ${o}`}))}}enumDrops(){for(let e of this.from.enums)this.to.enums.some(n=>n.schema===e.schema&&n.name===e.name)||(this.changes.push(`type ${e.schema}.${e.name} goes (at complete)`),this.completeTypes.push(`DROP TYPE IF EXISTS ${D(e.schema,e.name)}`))}matchTables(){let e=new Map(this.from.tables.map(n=>[F(n),n]));for(let n of this.to.tables)n.renamedFrom===void 0||n.renamedFrom===n.name||!e.has(`${n.schema}.${n.renamedFrom}`)||this.to.tables.some(s=>s!==n&&s.schema===n.schema&&s.name===n.renamedFrom)&&this.refuse(`table ${n.schema}.${n.renamedFrom} is renamed ${n.name}, and a new table takes the name ${n.renamedFrom} in the same deploy`,`rename it in this deploy, and make the new ${n.renamedFrom} in the next`);for(let n of this.to.tables){let s=e.get(F(n));if(n.renamedFrom!==void 0&&n.renamedFrom!==n.name){let r=e.get(`${n.schema}.${n.renamedFrom}`);s&&r&&this.refuse(`table ${F(n)} is renamed from ${n.renamedFrom}, but ${F(n)} is there already`,"remove renamedFrom, or rename to a free name"),!s&&r&&(s=r)}!s||this.fromMatched.has(s)||(this.fromMatched.add(s),this.matches.set(F(n),this.matchColumns(n,s)))}}matchColumns(e,n){let s=F(e),r=new Map(n.columns.map(l=>[l.name,l])),o={to:e,from:n,physical:n.name,renamed:new Map,cols:new Map,retyped:new Map,parked:new Map},i=new Set,a=new Set(e.columns.filter(l=>l.renamedFrom!==void 0&&l.renamedFrom!==l.name&&r.has(l.renamedFrom)&&!r.has(l.name)).map(l=>l.renamedFrom));for(let l of e.columns){let c=a.has(l.name)?void 0:r.get(l.name);if(l.renamedFrom!==void 0&&l.renamedFrom!==l.name&&r.has(l.renamedFrom)&&(r.has(l.name)?this.refuse(`column ${s}.${l.name} is renamed from ${l.renamedFrom}, but ${l.name} is there already`,"remove renamedFrom, or rename to a free name"):c=r.get(l.renamedFrom)),!c&&a.has(l.name)){let d=te(this.n,"add",l.name);o.parked.set(l.name,d),o.cols.set(l.name,d);continue}if(!c||i.has(c.name)){o.cols.set(l.name,l.name);continue}if(i.add(c.name),c.name!==l.name&&o.renamed.set(c.name,l.name),ae(c.type)!==ae(l.type)){let d=te(this.n,"new",l.name);o.retyped.set(l.name,{shadow:d,from:c,to:l}),o.cols.set(l.name,d)}else o.cols.set(l.name,c.name)}return o}inNewNames(e){let s=[...this.matches.values()].find(i=>i.from===e)?.renamed??new Map,r=i=>s.get(i)??i,o=i=>me(i,s);return{...e,uniques:e.uniques.map(i=>({...i,columns:i.columns.map(r)})),indexes:e.indexes.map(i=>({...i,keys:i.keys.map(a=>"column"in a?{...a,column:r(a.column)}:{...a,expr:o(a.expr)}),include:i.include?.map(r),where:i.where===void 0?void 0:o(i.where)})),checks:e.checks.map(i=>({...i,expr:o(i.expr)})),foreignKeys:e.foreignKeys.map(i=>this.fkInNewNames(i,r)),policies:e.policies.map(i=>({...i,using:i.using===void 0?void 0:o(i.using),withCheck:i.withCheck===void 0?void 0:o(i.withCheck)})),primaryKey:e.primaryKey.map(r)}}fkInNewNames(e,n){let s=this.from.tables.find(o=>o.schema===e.refSchema&&o.name===e.refTable),r=s&&[...this.matches.values()].find(o=>o.from===s);return{...e,columns:e.columns.map(n),refTable:r?r.to.name:e.refTable,refColumns:e.refColumns.map(o=>r?.renamed.get(o)??o)}}where(e){let n=this.matches.get(F(e));return n?{table:n.physical,cols:n.cols}:{table:e.name,cols:new Map(e.columns.map(s=>[s.name,s.name]))}}grants(e){let{anon:n,authenticated:s,service:r}=this.input.roles;return[`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${e} TO ${[n,s,r].map(N).join(", ")}`]}typeSql(e){let n=/^([a-z_][a-z0-9_]*)\.([a-z_][a-z0-9_]*)((?:\[\])*)$/i.exec(e);return n?`${D(n[1],n[2])}${n[3]}`:e}columnSql(e){let n=`${N(e.name)} ${this.typeSql(e.type)}`;return e.identity&&(n+=` GENERATED ${e.identity==="always"?"ALWAYS":"BY DEFAULT"} AS IDENTITY`),e.generated&&(n+=` GENERATED ALWAYS AS (${e.generated.expr}) ${e.generated.stored?"STORED":"VIRTUAL"}`),e.default!==void 0&&(n+=` DEFAULT ${e.default}`),e.nullable||(n+=" NOT NULL"),n}sequences(e,n,s,r){let{anon:o,authenticated:i,service:a}=this.input.roles;for(let l of Pr(n.default)){let c=new RegExp(String.raw`\bCREATE\s+SEQUENCE\s+(?:IF\s+NOT\s+EXISTS\s+)?${l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\w$"])`,"i");if(this.to.raw.some(d=>c.test(d.sql))){r.push(`GRANT USAGE, SELECT ON SEQUENCE ${l} TO ${[o,i,a].map(N).join(", ")}`);continue}s.push(`CREATE SEQUENCE IF NOT EXISTS ${l}`),r.push(`ALTER SEQUENCE ${l} OWNED BY ${D(e.schema,e.name)}.${N(n.name)}`,`GRANT USAGE, SELECT ON SEQUENCE ${l} TO ${[o,i,a].map(N).join(", ")}`)}}createTable(e){let n=D(e.schema,e.name),s=new Map(e.columns.map(l=>[l.name,l.name]));this.changes.push(`table ${F(e)}`);let r=[];for(let l of e.columns)this.sequences(e,l,this.creates,r);let o=e.columns.map(l=>this.columnSql(l)),i=new Set,a=[];e.primaryKey.length>0&&(o.push(`PRIMARY KEY (${Re(e.primaryKey)})`),i.add(e.primaryKey.join("\0")));for(let l of e.uniques){let c=l.columns.join("\0");i.has(c)?a.push(`ALTER TABLE ${n} ADD CONSTRAINT ${N(l.name)} UNIQUE (${Re(l.columns)})`):o.push(`CONSTRAINT ${N(l.name)} UNIQUE (${Re(l.columns)})`),i.add(c)}for(let l of e.checks)o.push(`CONSTRAINT ${N(l.name)} CHECK (${l.expr})`);this.creates.push(`CREATE TABLE ${n} (
|
|
71
71
|
${o.join(`,
|
|
72
72
|
`)}
|
|
73
|
-
)`,...a,...r);for(let l of e.indexes)this.creates.push(this.indexSql(e.schema,e.name,l,s,!1));for(let l of e.foreignKeys){let c=`${l.refSchema}.${l.refTable}`;this.from.tables.some(d=>F(d)===c)&&c!==F(e)?(this.lateFks.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD ${this.fkSql(l,s)} NOT VALID`],why:`foreign key ${l.name}`}),this.lateFks.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${
|
|
73
|
+
)`,...a,...r);for(let l of e.indexes)this.creates.push(this.indexSql(e.schema,e.name,l,s,!1));for(let l of e.foreignKeys){let c=`${l.refSchema}.${l.refTable}`;this.from.tables.some(d=>F(d)===c)&&c!==F(e)?(this.lateFks.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD ${this.fkSql(l,s)} NOT VALID`],why:`foreign key ${l.name}`}),this.lateFks.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${N(l.name)}`,why:`foreign key ${l.name}`}),this.undoFksGone.push({kind:"tx",sql:[`ALTER TABLE IF EXISTS ${n} DROP CONSTRAINT IF EXISTS ${N(l.name)}`],why:`foreign key ${l.name}`})):this.createFks.push(`ALTER TABLE ${n} ADD ${this.fkSql(l,s)}`)}for(let l of e.columns.filter(Ye)){let c=this.ignoredFillNames(e,l.name);this.creates.push(this.ignoredFillFunction(c.fn,l.name,l.fill,e.name),`CREATE TRIGGER ${N(c.trigger)} BEFORE INSERT ON ${n} FOR EACH ROW EXECUTE FUNCTION ${c.fn}()`,`SELECT (
|
|
74
74
|
${l.fill}
|
|
75
|
-
) FROM ${n} AS ${
|
|
75
|
+
) FROM ${n} AS ${N(e.name)} LIMIT 0`),this.undoCreates.push(`DROP FUNCTION IF EXISTS ${c.fn}()`)}this.creates.push(...cn(n,e.rls,!1));for(let l of e.policies)_e(l.using)||_e(l.withCheck)?this.accessPolicies.push({q:n,table:e,to:l}):this.readsOthersRenamed(e,l,F(e))||this.createFks.push(this.policySql(n,l,s));this.creates.push(...this.grants(n)),this.undoNewTables.push(n),this.addLayout(e,e.name,s)}dropTable(e){if(!e.ignored&&this.input.hasRows(F(e))){this.refuse(`table ${F(e)} is gone from the schema and has rows`,"mark it ignored first (defineTable(\u2026, { ignored: true })) and deploy; remove it in the deploy after that, when its data may go");return}this.changes.push(`table ${F(e)} goes (at complete)`),this.searchGone(e,e.name),this.completeDrops.push(D(e.schema,e.name));for(let n of e.foreignKeys){let s=[...this.matches.values()].find(r=>r.from.schema===n.refSchema&&r.from.name===n.refTable);s&&[...s.retyped.values()].some(r=>n.refColumns.includes(r.from.name))&&this.completeFks.push({kind:"tx",sql:[`ALTER TABLE IF EXISTS ${D(e.schema,e.name)} DROP CONSTRAINT IF EXISTS ${N(n.name)}`],why:`foreign key ${n.name}, onto the old column`})}for(let n of e.columns.filter(Ye))this.completeTypes.push(`DO $palgres$ BEGIN IF to_regclass(${v(D(e.schema,e.name))}) IS NULL THEN DROP FUNCTION IF EXISTS ${this.ignoredFillNames(e,n.name).fn}(); END IF; END $palgres$`);e.ignored||(this.completeDropsFoundEmpty.push(D(e.schema,e.name)),this.guarded.tables.push([e.schema,e.name]))}addLayout(e,n,s){e.ignored||this.layout.tables.push({schema:e.schema,name:e.name,physical:n,columns:e.columns.filter(r=>!r.ignored).map(r=>({name:r.name,physical:s.get(r.name)}))})}alterTable(e){let{to:n,from:s}=e,r=D(n.schema,e.physical),o=F(n),i={tx:[],undo:[],undoColumns:[],complete:[]},a=this.input.hasRows(F(s));n.name!==s.name&&this.changes.push(`table ${n.schema}.${s.name} is renamed ${n.name} (at complete)`);let l=new Map(s.columns.map(u=>[u.name,u])),c=new Set,d=[];for(let u of n.columns){let m=e.cols.get(u.name),f=e.retyped.get(u.name),g=f?.from??(e.parked.has(u.name)?void 0:l.get(m));if(u.nullable&&u.fill!==void 0&&u.fill!==g?.fill&&!(f&&!es(f.from.type,u.type))&&this.refuse(`column ${o}.${u.name} is nullable and declares .fillWith(\u2026), and its type does not change by a cast that may fail`,"a nullable column's fill is the value of a type change for a value that does not convert: remove .fillWith, or make the column NOT NULL"),!g){this.addColumn(n,r,m===u.name?u:{...u,name:m},i),Ye(u)&&this.ignoredFill(e,r,void 0,u,i,d);continue}if(c.add(g.name),f){this.retype(e,r,u.name,f,i);continue}g.name!==u.name&&(this.changes.push(`column ${o}.${g.name} is renamed ${u.name} (at complete)`),i.complete.push(`ALTER TABLE ${r} RENAME COLUMN ${N(g.name)} TO ${N(u.name)}`),i.names=!0),u.ignored&&!g.ignored&&this.insertsWithout(o,u),this.alterColumn(n,r,g,u,i),this.ignoredFill(e,r,g,u,i,d)}for(let u of s.columns){if(c.has(u.name))continue;if(Ye(u)&&i.complete.unshift(...this.ignoredFillDrop(e.from,r,u.name)),!u.ignored&&a&&u.lookupOf===void 0){let g=ht(u)?` \u2014 and, being NOT NULL with no default, with one (.default(\u2026)) or the value computed from the row (.fillWith(sql)): ${xr}`:"";this.refuse(`column ${F(s)}.${u.name} is gone from the schema and the table has rows`,`mark it ignored first (.ignored())${g}, and deploy; remove it in the deploy after that, when its data may go`);continue}u.ignored||this.insertsWithout(o,u),this.changes.push(`column ${F(s)}.${u.name} goes (at complete)`);let m=`ALTER TABLE ${r} DROP COLUMN IF EXISTS ${N(u.name)}`,f=u.ignored||u.lookupOf!==void 0?void 0:qi(u);if(f===void 0)i.complete.push(m);else{let g=v(`column ${F(s)}.${u.name} is gone from the schema and holds what the version before wrote while this one rolled out: it is kept, outside the schema`);i.complete.push(`DO $palgres$ BEGIN IF EXISTS (SELECT 1 FROM ${r} WHERE ${f}) THEN RAISE WARNING 'palgres: %', ${g}; ELSE ${m}; END IF; END $palgres$`),this.guarded.columns.push([n.schema,n.name,u.name])}i.names=!0,i.dropsColumns=!0}if(this.constraints(e,r,i),this.policies(e,r,i),s.rls!==n.rls){this.changes.push(`table ${o}: row-level security ${n.rls?"on":"off"}`);let u=m=>_e(m.using)||_e(m.withCheck);if(e.from.policies.some(u)||n.policies.some(u)){let m=`(SELECT coalesce(pg_catalog.current_setting('palgres.version', true), '') = ${v(String(this.input.next))})`,f=N("palgres_was_open");n.rls?(i.tx.push(`DROP POLICY IF EXISTS ${f} ON ${r}`,`CREATE POLICY ${f} ON ${r} AS PERMISSIVE FOR ALL TO PUBLIC USING (NOT ${m}) WITH CHECK (NOT ${m})`,...cn(r,!0,!0)),i.complete.push(`DROP POLICY IF EXISTS ${f} ON ${r}`),i.undo.push(`DROP POLICY IF EXISTS ${f} ON ${r}`,...cn(r,!1,!0))):(i.tx.push(`DROP POLICY IF EXISTS ${f} ON ${r}`,`CREATE POLICY ${f} ON ${r} AS PERMISSIVE FOR ALL TO PUBLIC USING (${m}) WITH CHECK (${m})`),i.complete.push(`DROP POLICY IF EXISTS ${f} ON ${r}`,...cn(r,!1,!0)),i.undo.push(`DROP POLICY IF EXISTS ${f} ON ${r}`))}else i.tx.push(...cn(r,n.rls,!0)),i.undo.push(...cn(r,s.rls,!0))}this.inNewNames(s).primaryKey.join()!==n.primaryKey.join()&&this.refuse(`the primary key of ${o} changes`,"a primary key cannot change while both versions write the table; add a unique constraint instead"),i.tx.length>0&&this.alters.push({kind:"tx",sql:i.tx,why:`table ${o}`});let y=[...i.undo,...i.undoColumns];y.length>0&&this.undoTables.push({kind:"tx",sql:y,why:`table ${o}`});for(let[u,m]of e.parked)this.changes.push(`column ${o}.${u} is made as ${m}, and takes its name at complete`),i.complete.push(`ALTER TABLE ${r} RENAME COLUMN ${N(m)} TO ${N(u)}`),i.names=!0;n.name!==s.name&&(i.complete.push(`ALTER TABLE ${r} RENAME TO ${N(n.name)}`),i.names=!0),i.complete.push(...d),i.names&&(this.namesAtComplete=!0),i.dropsColumns&&(this.dropsColumnsAtComplete=!0),i.complete.length>0&&this.completeTables.push({kind:"tx",sql:i.complete,why:`table ${o}`}),this.addLayout(n,e.physical,e.cols)}sequenceRenamed(e,n){let[s,r]=gt(e.default),[o,i]=gt(n.default);if(s===void 0||o===void 0||r!==void 0||i!==void 0||(s.schema??null)!==(o.schema??null)||s.name===o.name)return;let a=m=>m.replace(Br,"nextval()");if(a(e.default)!==a(n.default))return;let l=m=>f=>f.name===m.name&&(f.schema??null)===(m.schema??null),c=m=>this.from.tables.flatMap(f=>f.columns).filter(f=>gt(f.default).some(l(m))).length;if(c(s)!==1||c(o)!==0)return;let d=m=>m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),y=o.schema===void 0?String.raw`[^".\s]+`:d(o.schema),u=new RegExp(String.raw`\bSEQUENCE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"?${y}"?\.)?"?${d(o.name)}"?(?![\w$"])`,"i");if(!this.from.raw.some(m=>u.test(m.sql)))return{from:s.schema===void 0?N(s.name):D(s.schema,s.name),to:o.name}}insertsWithout(e,n){ht(n)&&!Ye(n)&&this.refuse(`column ${e}.${n.name} is NOT NULL with no default, and the new version inserts rows without it`,`give it a default (.default(\u2026)), or keep it ignored a deploy with the value computed from the row (.ignored().fillWith(sql)): ${xr} \u2014 or make it nullable in this deploy, if that version can read it empty`)}ignoredFillNames(e,n){let s=o=>{let i=`_palgres_keep_${o}`;return Buffer.byteLength(i)<=63?i:`_palgres_keep_${ss(o)}`},r=s(mt(e,n));return{fn:D(e.schema,r),name:r,trigger:s(n)}}ignoredFillFunction(e,n,s,r){let o=N(n);return`CREATE OR REPLACE FUNCTION ${e}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
|
|
76
76
|
BEGIN
|
|
77
77
|
IF NEW.${o} IS NULL THEN
|
|
78
78
|
NEW.${o} := (SELECT (
|
|
79
79
|
${s}
|
|
80
|
-
) FROM (SELECT (NEW).*) AS ${
|
|
80
|
+
) FROM (SELECT (NEW).*) AS ${N(r)});
|
|
81
81
|
END IF;
|
|
82
82
|
RETURN NEW;
|
|
83
|
-
END $palgres$`}ignoredFillDrop(e,n,s){let r=this.ignoredFillNames(e,s);return[`DROP TRIGGER IF EXISTS ${
|
|
84
|
-
${
|
|
85
|
-
) FROM ${n} AS ${
|
|
83
|
+
END $palgres$`}ignoredFillDrop(e,n,s){let r=this.ignoredFillNames(e,s);return[`DROP TRIGGER IF EXISTS ${N(r.trigger)} ON ${n}`,`DROP FUNCTION IF EXISTS ${r.fn}()`]}ignoredFill(e,n,s,r,o,i){let a=s!==void 0&&Ye(s),l=Ye(r);if(!a&&!l)return;let c=F(e.to),d=D(e.to.schema,e.to.name),y=e.cols.get(r.name),u=s===void 0?void 0:this.ignoredFillNames(e.from,s.name),m=this.ignoredFillNames(e.to,r.name);if(!l){if(r.ignored&&ht(r)){this.refuse(`column ${c}.${r.name} is ignored, NOT NULL with no default, and loses its .fillWith`,"the rows the new version inserts without it would have no value: keep .fillWith while it is ignored, or give it a default");return}o.complete.unshift(...this.ignoredFillDrop(e.from,n,s.name));return}let f=e.from.columns.map(h=>h.name).filter(h=>!e.to.columns.some(p=>p.name===h)&&Oe(r.fill,h));if(f.length>0){this.refuse(`column ${c}.${r.name}'s .fillWith reads ${f.join(", ")}, which this deploy renames or drops`,"say it by the names of the new version");return}let g=me(r.fill,ke(e.cols)),T=`SELECT (
|
|
84
|
+
${g}
|
|
85
|
+
) FROM ${n} AS ${N(e.physical)} LIMIT 0`;a?(s.fill!==r.fill&&(this.changes.push(`column ${c}.${r.name}: its .fillWith changes`),o.tx.push(this.ignoredFillFunction(u.fn,y,g,e.physical),T),o.undo.push(this.ignoredFillFunction(u.fn,s.name,s.fill,e.from.name))),u.fn!==m.fn&&i.push(`ALTER FUNCTION ${u.fn}() RENAME TO ${N(m.name)}`),u.trigger!==m.trigger&&i.push(`ALTER TRIGGER ${N(u.trigger)} ON ${d} RENAME TO ${N(m.trigger)}`)):(this.changes.push(`column ${c}.${r.name}: a row inserted without it gets the value of its .fillWith (while it is ignored)`),o.tx.push(this.ignoredFillFunction(m.fn,y,g,e.physical),`CREATE TRIGGER ${N(m.trigger)} BEFORE INSERT ON ${n} FOR EACH ROW EXECUTE FUNCTION ${m.fn}()`,T),o.undo.push(`DROP TRIGGER IF EXISTS ${N(m.trigger)} ON ${n}`,`DROP FUNCTION IF EXISTS ${m.fn}()`)),(g!==r.fill||e.physical!==e.to.name||y!==r.name)&&i.push(this.ignoredFillFunction(m.fn,r.name,r.fill,e.to.name))}addColumn(e,n,s,r){let o=[];this.sequences(e,s,r.tx,o),this.addColumnItself(e,n,s,r),r.tx.push(...o)}addColumnItself(e,n,s,r){let o=F(e),i=N(s.name);if(this.changes.push(`column ${o}.${s.name}`),r.undoColumns.push(`ALTER TABLE ${n} DROP COLUMN IF EXISTS ${i}`),s.identity){this.input.hasRows(F(this.matches.get(o).from))?this.refuse(`column ${o}.${s.name} is an identity column added to a table with rows`,"Postgres would rewrite the table under a lock; add a bigint column with a default and fill it"):r.tx.push(`ALTER TABLE ${n} ADD COLUMN ${this.columnSql(s)}`);return}if(s.generated){s.generated.stored&&this.input.hasRows(F(this.matches.get(o).from))?this.refuse(`column ${o}.${s.name} is a stored generated column added to a table with rows`,"Postgres would rewrite the table under a lock: add it virtual (.generated(expr)), or as a plain column a trigger keeps"):r.tx.push(`ALTER TABLE ${n} ADD COLUMN ${this.columnSql(s)}`);return}if(this.input.hasRows(F(this.matches.get(o).from))&&this.checkedDomain(s.type)){this.refuse(`column ${o}.${s.name} is of ${s.type}, a domain with a CHECK, added to a table with rows`,"Postgres would rewrite the table under a lock to check every row: add it as the domain's base type with a CHECK (added NOT VALID, then validated), or before the table has rows");return}if(!(s.default!==void 0&&lr(s.default))&&(s.nullable||s.default!==void 0)){r.tx.push(`ALTER TABLE ${n} ADD COLUMN ${this.columnSql(s)}`);return}if(!s.nullable&&s.default===void 0&&s.fill===void 0){this.refuse(`column ${o}.${s.name} is NOT NULL with no default`,"the version serving now inserts rows without it: give it a default (.default(\u2026)) or the value for those rows (.fillWith(sql))");return}r.tx.push(`ALTER TABLE ${n} ADD COLUMN ${i} ${this.typeSql(s.type)}`),s.default!==void 0?(r.tx.push(`ALTER TABLE ${n} ALTER COLUMN ${i} SET DEFAULT ${s.default}`),this.backfills.push({kind:"backfill",table:n,key:this.keyOf(e),set:`${i} = ${s.default}`,where:`${i} IS NULL`,why:`${o}.${s.name} takes its default`})):this.fill(e,n,s.name,s.fill,r),s.nullable||this.notNull(e,n,s.name,r)}fill(e,n,s,r,o){let i=F(e),a=D(e.schema,te(this.n,"fill",mt(e,s))),l=N(te(this.n,"fill",s)),c=N(s),d=this.where(e),y=me(r,ke(d.cols));o.tx.push(`CREATE OR REPLACE FUNCTION ${a}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
|
|
86
86
|
BEGIN
|
|
87
87
|
IF NEW.${c} IS NULL THEN
|
|
88
88
|
NEW.${c} := (SELECT (
|
|
89
|
-
${
|
|
90
|
-
) FROM (SELECT (NEW).*) AS ${
|
|
89
|
+
${y}
|
|
90
|
+
) FROM (SELECT (NEW).*) AS ${N(d.table)});
|
|
91
91
|
END IF;
|
|
92
92
|
RETURN NEW;
|
|
93
93
|
END $palgres$`,`CREATE TRIGGER ${l} BEFORE INSERT OR UPDATE ON ${n} FOR EACH ROW EXECUTE FUNCTION ${a}()`);let u=[`DROP TRIGGER IF EXISTS ${l} ON ${n}`,`DROP FUNCTION IF EXISTS ${a}()`];o.undo.push(...u),o.complete.unshift(...u),this.backfills.push({kind:"backfill",table:n,key:this.keyOf(e),set:`${c} = (
|
|
94
|
-
${
|
|
95
|
-
)`,where:`${c} IS NULL`,why:`${i}.${s} is filled`})}relaxNotNull(e,n,s,r){let o=
|
|
94
|
+
${y}
|
|
95
|
+
)`,where:`${c} IS NULL`,why:`${i}.${s} is filled`})}relaxNotNull(e,n,s,r){let o=N(s);r.tx.push(`ALTER TABLE ${n} ALTER COLUMN ${o} DROP NOT NULL`);let i=N(te(this.n,"nn",s)),a=`EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${v(i.slice(1,-1))} AND conrelid = ${v(n)}::regclass`;this.undoOnline.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF NOT ${a}) THEN ALTER TABLE ${n} ADD CONSTRAINT ${i} CHECK (${o} IS NOT NULL) NOT VALID; END IF; END $palgres$`],why:`${e}.${s} NOT NULL again`},{kind:"statement",sql:`DO $palgres$ BEGIN IF ${a}) THEN ALTER TABLE ${n} VALIDATE CONSTRAINT ${i}; END IF; EXCEPTION WHEN check_violation THEN ALTER TABLE ${n} DROP CONSTRAINT ${i}; RAISE WARNING 'palgres: % stays nullable: NULL was written since', ${v(`${e}.${s}`)}; END $palgres$`,why:`${e}.${s} has no NULL`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF ${a} AND convalidated) THEN ALTER TABLE ${n} ALTER COLUMN ${o} SET NOT NULL; END IF; END $palgres$`,`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${i}`],why:`${e}.${s} is NOT NULL`})}notNull(e,n,s,r){let o=N(te(this.n,"nn",s)),i=N(s);this.online.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD CONSTRAINT ${o} CHECK (${i} IS NOT NULL) NOT VALID`],why:`${F(e)}.${s} is held NOT NULL`}),r.undo.push(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${o}`),this.online.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${o}`,why:`${F(e)}.${s} has no NULL`}),this.settle.push({kind:"tx",sql:[`ALTER TABLE ${n} ALTER COLUMN ${i} SET NOT NULL`,`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${o}`],why:`${F(e)}.${s} is NOT NULL`})}alterColumn(e,n,s,r,o){let i=F(e),a=N(s.name);if(s.nullable&&!r.nullable){let l=r.fill??r.default;l===void 0?this.refuse(`column ${i}.${r.name} becomes NOT NULL`,"the version serving now may still write NULL: give the value for those rows and writes (.fillWith(sql))"):(this.changes.push(`column ${i}.${r.name} becomes NOT NULL`),this.fill(e,n,s.name,l,o),this.notNull(e,n,s.name,o),o.undo.push(`ALTER TABLE ${n} ALTER COLUMN ${a} DROP NOT NULL`))}if(!s.nullable&&r.nullable&&(this.changes.push(`column ${i}.${r.name} becomes nullable`),this.relaxNotNull(i,n,s.name,o)),(s.default??null)!==(r.default??null)){let l=this.sequenceRenamed(s,r);l!==void 0?(this.changes.push(`sequence ${l.from} becomes ${l.to} (at complete)`),o.complete.push(`ALTER SEQUENCE ${l.from} RENAME TO ${N(l.to)}`)):r.default!==void 0?(this.changes.push(`column ${i}.${r.name} defaults to ${r.default}`),o.tx.push(`ALTER TABLE ${n} ALTER COLUMN ${a} SET DEFAULT ${r.default}`),o.undo.push(s.default!==void 0?`ALTER TABLE ${n} ALTER COLUMN ${a} SET DEFAULT ${s.default}`:`ALTER TABLE ${n} ALTER COLUMN ${a} DROP DEFAULT`)):(this.changes.push(`column ${i}.${r.name} loses its default (at complete)`),o.complete.push(`ALTER TABLE ${n} ALTER COLUMN ${N(r.name)} DROP DEFAULT`))}(s.identity??null)!==(r.identity??null)&&this.refuse(`column ${i}.${r.name} changes identity`,"an identity cannot change while both versions write; add a new column"),this.regenerate(e,n,s,r,o)}regenerate(e,n,s,r,o){let i=F(e),a=N(s.name),l=s.generated,c=r.generated;if(!(!l&&!c)&&!(l&&c&&l.expr===c.expr&&l.stored===c.stored)){if(!l&&c){this.refuse(`column ${i}.${r.name} becomes a generated column`,"Postgres cannot make a column generated: add a new generated column and ignore the old one");return}if(l&&!c){if(!l.stored){this.refuse(`column ${i}.${r.name} stops being a virtual generated column`,"a virtual column holds no values to keep: add a plain column filled with .fillWith(expr) and ignore this one");return}this.changes.push(`column ${i}.${r.name} is no longer generated (it keeps its values; the old version's writes are computed until complete, and a rollback leaves it plain, computed so)`);let d=D(e.schema,te(this.n,"gen",mt(e,s.name))),y=N(te(this.n,"gen",s.name)),u=this.where(e);o.tx.push(`ALTER TABLE ${n} ALTER COLUMN ${a} DROP EXPRESSION IF EXISTS`,`CREATE OR REPLACE FUNCTION ${d}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
|
|
96
96
|
BEGIN
|
|
97
|
-
IF position(${
|
|
97
|
+
IF position(${v(Ie(this.n,""))} in replace(current_setting('search_path'), '"', '')) <> 1 THEN
|
|
98
98
|
NEW.${a} := (SELECT (
|
|
99
99
|
${me(l.expr,ke(u.cols))}
|
|
100
|
-
) FROM (SELECT (NEW).*) AS ${
|
|
100
|
+
) FROM (SELECT (NEW).*) AS ${N(u.table)});
|
|
101
101
|
END IF;
|
|
102
102
|
RETURN NEW;
|
|
103
|
-
END $palgres$`,`CREATE TRIGGER ${
|
|
103
|
+
END $palgres$`,`CREATE TRIGGER ${y} BEFORE INSERT OR UPDATE ON ${n} FOR EACH ROW EXECUTE FUNCTION ${d}()`),o.complete.unshift(`DROP TRIGGER IF EXISTS ${y} ON ${n}`,`DROP FUNCTION IF EXISTS ${d}()`);return}if(l.stored!==c.stored){this.refuse(`column ${i}.${r.name} changes between stored and virtual`,"Postgres would compute every row again: add a new generated column and ignore the old one");return}if(c.stored&&this.input.hasRows(F(this.matches.get(i).from))){this.refuse(`column ${i}.${r.name} changes its stored expression on a table with rows`,"Postgres would compute every row again under a lock: add a new generated column and ignore the old one");return}this.changes.push(`column ${i}.${r.name} is generated as ${c.expr}`),o.tx.push(`ALTER TABLE ${n} ALTER COLUMN ${a} SET EXPRESSION AS (${c.expr})`),o.undo.push(`ALTER TABLE ${n} ALTER COLUMN ${a} SET EXPRESSION AS (${l.expr})`)}}retype(e,n,s,r,o){let i=e.to,a=F(i),l=Bi(r.from.type,r.to.type),c=this.to.tables.flatMap($=>$.foreignKeys.filter(A=>A.refSchema===i.schema&&A.refTable===i.name&&A.refColumns.includes(s)).map(A=>({o:$,f:A}))),d=[...i.checks.filter($=>Oe($.expr,s)).map($=>`check ${$.name}`),...i.policies.filter($=>Oe(`${$.using??""} ${$.withCheck??""}`,s)).map($=>`policy ${$.name}`),...i.indexes.filter($=>$.keys.some(A=>"expr"in A&&Oe(A.expr,s))||$.where!==void 0&&Oe($.where,s)).map($=>`index ${$.name}`),...i.primaryKey.includes(s)&&!l?["the primary key"]:[],...l?[]:c.map(({o:$,f:A})=>`foreign key ${F($)}.${A.name}`)];if(d.length>0){let $=!l&&(i.primaryKey.includes(s)||c.length>0)?" \u2014 a key changes type in place only by widening: an integer to a wider one, a text to a longer one":"";this.refuse(`column ${a}.${s} changes type from ${r.from.type} to ${r.to.type}, and ${d.join(", ")} use it`,`add a column of the new type with .fillWith("${s}::${r.to.type}"), move them to it, and ignore the old one${$}`);return}let y=c.flatMap(({o:$,f:A})=>A.columns.filter((I,L)=>A.refColumns[L]===s&&kn($.columns.find(k=>k.name===I)?.type??"")!==kn(r.to.type)).map(I=>`${F($)}.${I}`));if(y.length>0){this.refuse(`column ${a}.${s} becomes ${r.to.type}, and ${y.join(", ")}, which reference it, are not of its kind`,`change their type with it in this deploy, to ${r.to.type}`);return}if((r.from.identity??null)!==(r.to.identity??null)){this.refuse(`column ${a}.${s} changes identity`,"an identity cannot change while both versions write; add a new column");return}let u=this.conversion(r.from.type,r.to.type);if("refused"in u){this.refuse(`column ${a}.${s} changes type from ${r.from.type} to ${r.to.type}: ${u.refused}`,"add a column of the new type with .fillWith(\u2026) saying the value, move to it, and ignore the old one");return}if(r.from.nullable&&!r.to.nullable){this.refuse(`column ${a}.${s} changes type and becomes NOT NULL in one deploy`,"change its type in this deploy and make it NOT NULL (with .fillWith) in the next");return}let m=es(r.from.type,r.to.type);this.changes.push(`column ${a}.${s} changes type from ${r.from.type} to ${r.to.type}${m?"":" (a value that does not convert is kept in the old column at complete)"}`);let f=N(r.from.name),g=N(r.shadow),T=D(i.schema,te(this.n,"sync",mt(i,s))),h=N(te(this.n,"sync",s)),p=new Map([...e.cols].map(([$,A])=>[$,e.retyped.get($)?.from.name??A])),S=m||r.to.fill===void 0?void 0:me(r.to.fill,ke(p)),b=$=>{let A=`NEW.${g} := ${u.on(`NEW.${f}`)};`;if(m)return`${$}${A}`;let I=k=>["BEGIN",` ${k}`,`EXCEPTION WHEN ${Wi} THEN`,` NEW.${g} := NULL;`,"END;"];return[...I(A),...S===void 0?[]:[`IF NEW.${g} IS NULL AND NEW.${f} IS NOT NULL THEN`,...I(`NEW.${g} := (SELECT (
|
|
104
104
|
${S}
|
|
105
|
-
) FROM (SELECT (NEW).*) AS ${
|
|
106
|
-
`)};o.tx.push(`ALTER TABLE ${n} ADD COLUMN ${
|
|
105
|
+
) FROM (SELECT (NEW).*) AS ${N(e.physical)});`).map(k=>` ${k}`),"END IF;"]].map(k=>`${$}${k}`).join(`
|
|
106
|
+
`)};o.tx.push(`ALTER TABLE ${n} ADD COLUMN ${g} ${this.typeSql(r.to.type)}`,`CREATE OR REPLACE FUNCTION ${T}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
|
|
107
107
|
DECLARE
|
|
108
|
-
next boolean := position(${
|
|
108
|
+
next boolean := position(${v(Ie(this.n,""))} in replace(current_setting('search_path'), '"', '')) = 1;
|
|
109
109
|
BEGIN
|
|
110
110
|
-- The writer's own column, taken across \u2014 on an update only when it
|
|
111
111
|
-- changed: a value the other version wrote is not cast back over (a cast
|
|
112
112
|
-- may lose: a shorter varchar, an integer).
|
|
113
113
|
IF TG_OP = 'INSERT' THEN
|
|
114
|
-
IF next${r.from.identity?` AND NEW.${
|
|
115
|
-
NEW.${f} := ${u.back(`NEW.${
|
|
114
|
+
IF next${r.from.identity?` AND NEW.${g} IS NOT NULL`:""} THEN
|
|
115
|
+
NEW.${f} := ${u.back(`NEW.${g}`)};${r.from.identity?`
|
|
116
116
|
ELSIF next THEN
|
|
117
117
|
-- An identity, which the new version gave none: the number the old
|
|
118
118
|
-- column was given, from the one sequence both versions number from.
|
|
119
|
-
NEW.${
|
|
119
|
+
NEW.${g} := ${u.on(`NEW.${f}`)};`:""}
|
|
120
120
|
ELSE
|
|
121
|
-
${
|
|
121
|
+
${b(" ")}
|
|
122
122
|
END IF;
|
|
123
123
|
ELSIF next THEN
|
|
124
|
-
IF NEW.${
|
|
125
|
-
NEW.${f} := ${u.back(`NEW.${
|
|
124
|
+
IF NEW.${g} IS DISTINCT FROM OLD.${g} THEN
|
|
125
|
+
NEW.${f} := ${u.back(`NEW.${g}`)};
|
|
126
126
|
END IF;
|
|
127
|
-
ELSIF NEW.${f} IS DISTINCT FROM OLD.${f} OR (NEW.${
|
|
127
|
+
ELSIF NEW.${f} IS DISTINCT FROM OLD.${f} OR (NEW.${g} IS NULL AND NEW.${f} IS NOT NULL) THEN
|
|
128
128
|
-- the old version's write, or the backfill reaching a row
|
|
129
|
-
${
|
|
129
|
+
${b(" ")}
|
|
130
130
|
END IF;
|
|
131
131
|
RETURN NEW;
|
|
132
|
-
END $palgres$`,`CREATE TRIGGER ${
|
|
132
|
+
END $palgres$`,`CREATE TRIGGER ${h} BEFORE INSERT OR UPDATE ON ${n} FOR EACH ROW EXECUTE FUNCTION ${T}()`),S!==void 0&&o.tx.push(`SELECT (
|
|
133
133
|
${S}
|
|
134
|
-
) FROM ${n} AS ${
|
|
134
|
+
) FROM ${n} AS ${N(e.physical)} LIMIT 0`),r.to.default!==void 0&&o.tx.push(`ALTER TABLE ${n} ALTER COLUMN ${g} SET DEFAULT ${r.to.default}`),!r.from.nullable&&r.to.nullable&&this.relaxNotNull(a,n,r.from.name,o),o.undo.push(`DROP TRIGGER IF EXISTS ${h} ON ${n}`,`DROP FUNCTION IF EXISTS ${T}()`),o.undoColumns.push(`ALTER TABLE ${n} DROP COLUMN IF EXISTS ${g}`);let E=r.from.identity==="always"?g:f;this.backfills.push({kind:"backfill",table:n,key:this.keyOf(i),set:`${E} = ${E}`,where:`${g} IS NULL AND ${f} IS NOT NULL`,why:`${a}.${s} in its new type`}),o.complete.push(`DROP TRIGGER IF EXISTS ${h} ON ${n}`,`DROP FUNCTION IF EXISTS ${T}()`);for(let $ of Pr(r.to.default))o.complete.push(`DO $palgres$ BEGIN IF EXISTS (SELECT 1 FROM pg_catalog.pg_depend WHERE classid = 'pg_catalog.pg_class'::regclass AND objid = to_regclass(${v($)}) AND refclassid = 'pg_catalog.pg_class'::regclass AND refobjid = ${v(n)}::regclass AND refobjsubid = (SELECT attnum FROM pg_catalog.pg_attribute WHERE attrelid = ${v(n)}::regclass AND attname = ${v(r.from.name)} AND NOT attisdropped) AND deptype = 'a') THEN ALTER SEQUENCE ${$} OWNED BY ${n}.${g}; END IF; END $palgres$`),ae(r.to.type)==="bigint"&&o.complete.push(`ALTER SEQUENCE IF EXISTS ${$} AS bigint`);if(o.names=!0,o.dropsColumns=!0,!m){this.keepUnconverted(e,n,s,r,o);return}if(r.to.nullable||this.notNull(i,n,r.shadow,o),r.to.identity){let $=r.to.identity==="always"?"ALWAYS":"BY DEFAULT";o.complete.push(`DO $palgres$
|
|
135
135
|
DECLARE
|
|
136
|
-
seq regclass := pg_catalog.pg_get_serial_sequence(${
|
|
136
|
+
seq regclass := pg_catalog.pg_get_serial_sequence(${v(n)}, ${v(r.from.name)})::regclass;
|
|
137
137
|
seq_name text;
|
|
138
138
|
seq_step bigint;
|
|
139
139
|
seq_next bigint;
|
|
@@ -142,63 +142,63 @@ BEGIN
|
|
|
142
142
|
SELECT seqincrement INTO seq_step FROM pg_catalog.pg_sequence WHERE seqrelid = seq;
|
|
143
143
|
seq_next := nextval(seq);
|
|
144
144
|
ALTER TABLE ${n} DROP COLUMN ${f};
|
|
145
|
-
EXECUTE format('ALTER TABLE %s ALTER COLUMN %I ADD GENERATED ${$} AS IDENTITY (SEQUENCE NAME %s START WITH %s INCREMENT BY %s)', ${
|
|
146
|
-
END $palgres$`)}else o.complete.push(`ALTER TABLE ${n} DROP COLUMN ${f}`);o.complete.push(`ALTER TABLE ${n} RENAME COLUMN ${h} TO ${b(s)}`)}keepUnconverted(e,n,s,r,o){let i=e.to,a=F(i),l=b(r.from.name),c=te(this.n,"old",s),d=T=>T.includes(r.from.name);o.complete.push(...e.from.uniques.filter(T=>d(T.columns)).map(T=>`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b(T.name)}`),...e.from.foreignKeys.filter(T=>d(T.columns)).map(T=>`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b(T.name)}`),...e.from.indexes.filter(T=>d([...T.keys.flatMap(g=>"column"in g?[g.column]:[]),...T.include??[]])).map(T=>`DROP INDEX IF EXISTS ${M(i.schema,T.name)}`),`ALTER TABLE ${n} ALTER COLUMN ${l} DROP NOT NULL`,`ALTER TABLE ${n} ALTER COLUMN ${l} DROP DEFAULT`,`ALTER TABLE ${n} RENAME COLUMN ${l} TO ${b(c)}`,`ALTER TABLE ${n} RENAME COLUMN ${b(r.shadow)} TO ${b(s)}`);let w=M(i.schema,i.name),u=b(s),m=b(c),f=`(SELECT attnum FROM pg_catalog.pg_attribute WHERE attrelid = ${x(w)}::regclass AND attname = ${x(c)} AND NOT attisdropped)`,h=x(`column ${a}.${s}: values of it that did not become ${r.to.type} are kept in ${c}, outside the schema, and ${s} is NULL in their rows`);if(this.completeAfter.push({kind:"statement",sql:`DO $palgres$ BEGIN IF ${f} IS NOT NULL THEN IF NOT EXISTS (SELECT 1 FROM ${w} WHERE ${u} IS NULL AND ${m} IS NOT NULL) THEN COMMENT ON COLUMN ${w}.${m} IS ${x(kr)}; END IF; END IF; END $palgres$`,why:`${a}.${s}: whether every value became ${r.to.type}`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF pg_catalog.col_description(${x(w)}::regclass, ${f}) = ${x(kr)} THEN ALTER TABLE ${w} DROP COLUMN ${m}; ELSIF ${f} IS NOT NULL THEN RAISE WARNING 'palgres: %', ${h}; END IF; END $palgres$`],why:`${a}.${s}: its values before, once converted`}),!r.to.nullable){let T=te(this.n,"nn",s),g=`EXISTS (SELECT 1 FROM pg_catalog.pg_constraint WHERE conname = ${x(T)} AND conrelid = ${x(w)}::regclass`;this.completeAfter.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF ${f} IS NULL AND NOT ${g}) THEN ALTER TABLE ${w} ADD CONSTRAINT ${b(T)} CHECK (${u} IS NOT NULL) NOT VALID; END IF; END $palgres$`],why:`${a}.${s} is held NOT NULL`},{kind:"statement",sql:`DO $palgres$ BEGIN IF ${g}) THEN ALTER TABLE ${w} VALIDATE CONSTRAINT ${b(T)}; END IF; END $palgres$`,why:`${a}.${s} has no NULL`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF ${g} AND convalidated) THEN ALTER TABLE ${w} ALTER COLUMN ${u} SET NOT NULL; END IF; END $palgres$`,`ALTER TABLE ${w} DROP CONSTRAINT IF EXISTS ${b(T)}`],why:`${a}.${s} is NOT NULL`})}(this.guarded.retyped??=[]).push({schema:i.schema,table:i.name,column:s,kept:c,type:r.to.type,key:i.primaryKey})}checkedDomain(e){if(this.input.checkedDomain(this.typeSql(e))===!0)return!0;let n=ae(e).replace(/^public\./,""),s=o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(String.raw`\bCREATE\s+DOMAIN\s+(?:"?public"?\.)?"?${s(n.replace(/^"|"$/g,""))}"?\s[\s\S]*\b(?:CHECK|NOT\s+NULL)\b`,"i");return this.to.raw.some(o=>r.test(o.sql))}conversion(e,n){let s=m=>/(\[\])*$/.exec(m)[0],r=m=>m.slice(0,m.length-s(m).length);if(s(e)!==s(n))return{refused:"one is an array and the other is not, or of another depth"};let o=s(e),i=m=>{let f=ae(r(m));return[...this.to.enums,...this.from.enums].find(h=>wn(h.schema,h.name)===f||h.schema==="public"&&wn(h.schema,h.name)===`public.${f}`)},a=m=>/^(text|citext|public\.citext|character varying(\(\d+\))?|character(\(\d+\))?)$/.test(ae(r(m))),l=m=>f=>`${f}::${this.typeSql(m)}`,c=i(e),d=i(n);if(c&&d){let m=(g,p)=>g.filter(S=>!p.includes(S)),f=m(c.values,d.values),h=m(d.values,c.values);if(f.length>0||h.length>0)return{refused:`the enums' labels differ (${[...f.map(g=>`-${g}`),...h.map(g=>`+${g}`)].join(", ")}), and a label one version writes the other's column cannot hold`};let T=g=>p=>`${p}::text${o}::${this.typeSql(g)}`;return{on:T(n),back:T(e)}}if(c||d)return a(c?n:e)?{on:l(n),back:l(e)}:{refused:`Postgres has no cast between an enum and ${c?n:e}`};let w=this.input.castable(this.typeSql(e),this.typeSql(n)),u=this.input.castable(this.typeSql(n),this.typeSql(e));return w===!1||u===!1?{refused:`Postgres has no cast from ${w===!1?e:n} to ${w===!1?n:e}`}:{on:l(n),back:l(e)}}constraints(e,n,s){let{to:r}=e,o=this.inNewNames(e.from),i=e.from,a=F(r),l=E=>E.some($=>e.retyped.has($)),c=E=>E.some($=>e.retyped.has($)),d=(E,$)=>l($)?te(this.n,"c",E):E,w=(E,$,A)=>{E!==$&&s.complete.push(A?`ALTER TABLE ${n} RENAME CONSTRAINT ${b(E)} TO ${b($)}`:`ALTER INDEX ${M(r.schema,E)} RENAME TO ${b($)}`)},u=(E,$,A,O)=>{let L=[],N=[];for(let _ of $){let y=E.find(k=>k.name===_.name);y?(!O(y,_)||l(A(_)))&&(c(A(y))||N.push(y),L.push(_)):L.push(_)}for(let _ of E)!$.some(y=>y.name===_.name)&&!c(A(_))&&N.push(_);return{added:L,gone:N}},m=(E,$)=>E.find(A=>A.name===$),f=E=>i.uniques.some($=>$.name===E)||i.indexes.some($=>$.name===E),h=u(o.uniques,r.uniques,E=>E.columns,(E,$)=>E.columns.join()===$.columns.join());this.renamedTwins(h,(E,$)=>E.columns.join()===$.columns.join()&&!l($.columns),(E,$)=>{this.changes.push(`unique ${a}.${E.name} is renamed ${$.name} (at complete)`),s.complete.push(`ALTER TABLE ${n} RENAME CONSTRAINT ${b(E.name)} TO ${b($.name)}`)});for(let E of h.gone)this.changes.push(`unique ${a}.${E.name} goes (at complete)`),s.complete.push(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b(E.name)}`);for(let E of h.added){let $=f(E.name)?te(this.n,"c",E.name):d(E.name,E.columns),A=M(r.schema,$);this.changes.push(`unique ${a}.${E.name}`),this.online.push({kind:"statement",sql:`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ${b($)} ON ${n} (${Re(E.columns.map(O=>e.cols.get(O)))})`,why:`unique ${E.name}`}),this.settle.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${x($)} AND conrelid = ${x(n)}::regclass) THEN ALTER TABLE ${n} ADD CONSTRAINT ${b($)} UNIQUE USING INDEX ${b($)}; END IF; END $palgres$`],why:`unique ${E.name}`}),s.undo.unshift(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b($)}`,`DROP INDEX IF EXISTS ${A}`),w($,E.name,!0)}let T=u(o.checks,r.checks,E=>r.columns.filter($=>Oe(E.expr,$.name)).map($=>$.name),(E,$)=>E.expr.trim()===$.expr.trim());for(let E of T.gone)this.changes.push(`check ${a}.${E.name} goes`),s.tx.push(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b(E.name)}`),s.undo.push(`ALTER TABLE ${n} ADD CONSTRAINT ${b(E.name)} CHECK (${m(i.checks,E.name).expr}) NOT VALID`);for(let E of T.added)this.changes.push(`check ${a}.${E.name}`),s.tx.push(`ALTER TABLE ${n} ADD CONSTRAINT ${b(E.name)} CHECK (${me(E.expr,ke(e.cols))}) NOT VALID`),this.online.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${b(E.name)}`,why:`check ${E.name}`}),s.undo.unshift(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b(E.name)}`);let g=u(o.foreignKeys,r.foreignKeys,E=>E.columns,(E,$)=>mt(E)===mt($)),p=E=>E.refColumns.some($=>this.matches.get(`${E.refSchema}.${E.refTable}`)?.retyped.has($)??!1);for(let E of r.foreignKeys){if(!p(E))continue;g.added.includes(E)||g.added.push(E);let $=o.foreignKeys.find(A=>A.name===E.name);$&&!g.gone.includes($)&&this.completeFks.push({kind:"tx",sql:[`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b($.name)}`],why:`foreign key ${E.name}, onto the old column`})}for(let E of g.gone)this.changes.push(`foreign key ${a}.${E.name} goes`),this.fkDrops.push({kind:"tx",sql:[`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b(E.name)}`],why:`foreign key ${E.name} goes`}),this.undoFksBack.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD ${this.fkSqlOld(m(i.foreignKeys,E.name))} NOT VALID`],why:`foreign key ${E.name} again`});for(let E of g.added){let $=p(E)?te(this.n,"c",E.name):d(E.name,E.columns);this.changes.push(`foreign key ${a}.${E.name}${p(E)?" references the new column (the old one goes at complete)":""}`),this.lateFks.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD ${this.fkSql({...E,name:$},e.cols)} NOT VALID`],why:`foreign key ${E.name}`}),this.lateFks.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${b($)}`,why:`foreign key ${E.name}`}),this.undoFksGone.push({kind:"tx",sql:[`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${b($)}`],why:`foreign key ${E.name}`}),w($,E.name,!0)}for(let E of r.foreignKeys){let $=o.foreignKeys.find(A=>A.name===E.name);!$||mt($)!==mt(E)||l(E.columns)||p(E)||($.deferrable??!1)===(E.deferrable??!1)||(this.changes.push(`foreign key ${a}.${E.name} is ${E.deferrable?"":"not "}deferrable (in the catalog, no row read again; ${a} locked a moment, the lock given way to while others hold it and tried again)`),s.tx.push(`ALTER TABLE ${n} ALTER CONSTRAINT ${b(E.name)} ${E.deferrable?"DEFERRABLE":"NOT DEFERRABLE"}`),s.undo.push(`ALTER TABLE ${n} ALTER CONSTRAINT ${b(E.name)} ${E.deferrable?"NOT DEFERRABLE":"DEFERRABLE"}`))}if(r.primaryKey.some(E=>e.retyped.has(E))){let E=te(this.n,"pk",r.name),$=`${r.name}_pkey`;this.changes.push(`the primary key of ${a} is made again on the new column (its index built at start, the key at complete)`),this.online.push({kind:"statement",sql:`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ${b(E)} ON ${n} (${Re(r.primaryKey.map(A=>e.cols.get(A)))})`,why:`the primary key of ${a}, on the new column`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${M(r.schema,E)}`,why:`the primary key of ${a}, on the new column`}),s.complete.push(`ALTER TABLE ${n} ADD PRIMARY KEY USING INDEX ${b(E)}`),Buffer.byteLength($)<=63&&s.complete.push(`DO $palgres$ BEGIN IF to_regclass(${x(M(r.schema,$))}) IS NULL THEN ALTER INDEX ${M(r.schema,E)} RENAME TO ${b($)}; END IF; END $palgres$`)}let S=E=>[...E.keys.flatMap($=>"column"in $?[$.column]:[]),...E.include??[]],R=u(o.indexes,r.indexes,S,(E,$)=>pt(E)===pt($));this.renamedTwins(R,(E,$)=>pt(E)===pt($)&&!l(S($)),(E,$)=>{this.changes.push(`index ${a}.${E.name} is renamed ${$.name} (at complete)`),s.complete.push(`ALTER INDEX ${M(r.schema,E.name)} RENAME TO ${b($.name)}`)});for(let E of R.added){if(!E.unique)continue;let $=S(E).slice(0,E.keys.length),A=R.gone.find(L=>L.unique&&S(L).slice(0,L.keys.length).join()===$.join());if(!A)continue;let O=this.to.tables.flatMap(L=>L.foreignKeys.filter(N=>N.refSchema===r.schema&&N.refTable===r.name&&N.refColumns.join()===$.join()).map(N=>`${F(L)}.${N.name}`));O.length>0&&this.refuse(`unique index ${a}.${A.name} is built again as ${E.name}, and foreign key ${O.join(", ")} reference its columns`,"Postgres binds a foreign key to the first unique index over its columns \u2014 the old one, which then cannot go: change the index in one deploy and the foreign keys in another, or give the new index other key columns")}for(let E of R.gone)R.added.some($=>$.name===E.name)?(this.changes.push(`index ${a}.${E.name} is built again (the old one goes at complete)`),s.complete.push(`DROP INDEX IF EXISTS ${M(r.schema,E.name)}`)):(this.changes.push(`index ${a}.${E.name} goes (at complete)`),this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${M(r.schema,E.name)}`,why:`index ${E.name}`}));for(let E of R.added){let $=f(E.name)?te(this.n,"i",E.name):d(E.name,S(E));this.changes.push(`index ${a}.${E.name}`),this.online.push({kind:"statement",sql:this.indexSql(r.schema,e.physical,{...E,name:$},e.cols,!0),why:`index ${E.name}`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${M(r.schema,$)}`,why:`index ${E.name}`}),w($,E.name,!1)}}renamedTwins(e,n,s){for(let r of[...e.gone]){let o=e.added.find(i=>i.name!==r.name&&n(r,i)&&!e.gone.some(a=>a.name===i.name));o&&(e.gone.splice(e.gone.indexOf(r),1),e.added.splice(e.added.indexOf(o),1),s(r,o))}}indexSql(e,n,s,r,o){let i=ke(r),a=s.keys.map(c=>{let d="column"in c?b(r.get(c.column)??c.column):`(${me(c.expr,i)})`;return c.desc&&(d+=" DESC"),c.nulls&&(d+=` NULLS ${c.nulls.toUpperCase()}`),d}),l=`CREATE ${s.unique?"UNIQUE ":""}INDEX ${o?"CONCURRENTLY ":""}IF NOT EXISTS ${b(s.name)} ON ${M(e,n)}`;return s.method&&s.method!=="btree"&&(l+=` USING ${s.method}`),l+=` (${a.join(", ")})`,s.include?.length&&(l+=` INCLUDE (${Re(s.include.map(c=>r.get(c)??c))})`),s.where!==void 0&&(l+=` WHERE ${me(s.where,i)}`),l}fkSql(e,n){let s=this.to.tables.find(o=>o.schema===e.refSchema&&o.name===e.refTable),r=s?this.where(s):{table:e.refTable,cols:new Map};return`CONSTRAINT ${b(e.name)} FOREIGN KEY (${Re(e.columns.map(o=>n.get(o)??o))}) REFERENCES ${M(e.refSchema,r.table)} (${Re(e.refColumns.map(o=>r.cols.get(o)??o))})${e.match==="full"?" MATCH FULL":""} ON DELETE ${e.onDelete.toUpperCase()} ON UPDATE ${e.onUpdate.toUpperCase()}${e.deferrable?" DEFERRABLE":""}`}fkSqlOld(e){return`CONSTRAINT ${b(e.name)} FOREIGN KEY (${Re(e.columns)}) REFERENCES ${M(e.refSchema,e.refTable)} (${Re(e.refColumns)})${e.match==="full"?" MATCH FULL":""} ON DELETE ${e.onDelete.toUpperCase()} ON UPDATE ${e.onUpdate.toUpperCase()}${e.deferrable?" DEFERRABLE":""}`}generations(e){return[...this.input.generations?.(e)??[]].sort((n,s)=>n.gen-s.gen)}search(e,n){let s=F(e),r=e.search,o=n?.from.search;if(r===void 0){n&&this.searchGone(n.from,n.physical);return}let i=Ks(`table ${s}`,e,r);if(i.length>0){this.refusals.push(...i);return}let a=e.columns.find(S=>S.name===e.primaryKey[0]),l=this.generations(n?F(n.from):s),c=l.filter(S=>S.status!=="retired"),d=c.find(S=>S.status==="active"),w=c.at(-1),u=w===void 0?[]:st(w,r)?c:d?[d]:[],m=w===void 0?"active":st(w,r)||d!==void 0&&st(d,r)?void 0:"filling";if(n){let S="take search out of the table and deploy, make the change in the next deploy, and declare search again in the one after \u2014 every row is embedded again then";e.name!==n.from.name&&this.refuse(`table ${e.schema}.${n.from.name} is renamed ${e.name} while it declares search`,S);let R=new Set;for(let E of new Set([a.name,...r.from])){let $=E===a.name?"search keeps each row's vector by it":"search reads it";if(n.retyped.has(E))this.refuse(`column ${s}.${E} changes type, and ${$}`,S);else if((n.cols.get(E)??E)!==E)this.refuse(`column ${s}.${E} ${n.parked.has(E)?"takes a name another column leaves in this deploy":`is renamed from ${n.cols.get(E)}`}, and ${$}`,S);else continue;R.add(n.retyped.get(E)?.from.name??n.cols.get(E)??E)}for(let E of u)for(let $ of E.from){if(R.has($))continue;e.columns.some(O=>O.name===$)&&!n.retyped.has($)&&(n.cols.get($)??$)===$||this.refuse(`column ${s}.${$} goes or changes, and the vectors that serve search of ${s} now (generation ${E.gen}) are made from it`,"they serve until the new ones are complete: leave the column as it is in this deploy, and change it in a deploy after that")}}let f={schema:e.schema,name:n?n.physical:e.name},h=M(f.schema,f.name);if(m!==void 0){let S=(l.at(-1)?.gen??0)+1;this.changes.push(m==="active"?`search of ${s}: its rows are embedded with ${r.model} (${r.dimensions} dimensions) in the background; found by their words until then`:`search of ${s}: every row is embedded again with ${r.model} (${r.dimensions} dimensions) in the background; the vectors there serve until the new ones are complete`),this.searchStart.push({kind:"tx",sql:br({table:f,gen:S,search:r,status:m,pk:{name:a.name,type:this.typeSql(a.type)},roles:this.input.roles,types:this.input.vectorSchema??"public"}),why:`search of ${s}: generation ${S}`}),n&&this.searchStart.push({kind:"statement",sql:Nr(f,S,a.name),why:`search of ${s}: its rows queued`}),this.undoSearch.push({kind:"tx",sql:lt(f,S),why:`search of ${s}: generation ${S}`})}if(o!==void 0&&o.staleness!==r.staleness&&u.length>0){this.changes.push(`search of ${s}: a changed row's old vector ${r.staleness==="null"?"goes":"stays"} until the row is embedded again`);for(let S of u)this.searchStart.push({kind:"tx",sql:at({table:f,gen:S.gen,from:S.from,staleness:r.staleness},!0),why:`search of ${s}: generation ${S.gen}'s triggers`}),this.undoSearch.push({kind:"tx",sql:at({table:f,gen:S.gen,from:S.from,staleness:o.staleness},!0),why:`search of ${s}: generation ${S.gen}'s triggers`})}for(let S of l)u.includes(S)||(this.changes.push(`search of ${s}: generation ${S.gen}'s vectors, ${S.status==="retired"?"left behind":"never full"}, go (at complete)`),this.searchComplete.push({kind:"tx",sql:lt(f,S.gen),why:`search of ${s}: generation ${S.gen}`}));let T=rt(f,r.from),g=o===void 0?void 0:rt(f,o.from);if(T===g)return;let p=S=>`CREATE INDEX ${S?"CONCURRENTLY ":""}IF NOT EXISTS ${b(T)} ON ${h} USING gin (${it(r.from)})`;o!==void 0&&this.changes.push(`search of ${s} reads ${r.from.join(", ")}`),n?(this.online.push({kind:"statement",sql:p(!0),why:`search of ${s}: its words`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${M(f.schema,T)}`,why:`search of ${s}: its words`})):this.creates.push(p(!1)),g!==void 0&&this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${M(f.schema,g)}`,why:`search of ${s}: the words it read`})}searchGone(e,n){let s=this.generations(F(e));if(e.search===void 0&&s.length===0)return;let r={schema:e.schema,name:n},o=F(e);this.changes.push(`search of ${o} goes (at complete)`);for(let i of s)this.searchComplete.push({kind:"tx",sql:lt(r,i.gen),why:`search of ${o}: generation ${i.gen}`});e.search!==void 0&&this.searchComplete.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${M(r.schema,rt(r,e.search.from))}`,why:`search of ${o}: the words it read`})}compileAccess(){if(this.to.access!==void 0)try{let e=Zs(this.to,{authenticated:this.input.roles.authenticated,service:this.input.roles.service},(this.input.from?.access?.names??[]).map(n=>({name:n.view,type:n.idType})));if(e.digest!==this.to.access.compiled){this.refuse(`the access schema compiles to ${e.digest} for this database's roles, and the schema carries ${this.to.access.compiled}`,"the model was made for other roles than the migration runs with: give toModel the same roles");return}this.toAccess=e,this.toRecorded=er(e,this.to.access.text)}catch(e){if(!(e instanceof Xs))throw e;this.refuse(`the access schema: ${e.message}`,"mend it: nothing is compiled from a schema that does not hold together")}}access(){let e=this.toRecorded,n=this.fromRecorded;if(!e&&!n){for(let y of this.accessPolicies){let k=y.to??y.from;y.to&&this.refuse(`policy ${F(y.table)}.${k.name} reads the access schema`,"the schema declares none: give the database one (db.access)")}return}let s=b("access"),r={authenticated:this.input.roles.authenticated,service:this.input.roles.service},o=e?.digest!==n?.digest;if(e&&this.to.access){let y=Ys(Vs(this.to.access.text));for(let k of e.tables){let D=this.to.tables.find(I=>I.schema===k.schema&&I.name===k.name);if(!D)continue;let P=this.from.tables.find(I=>I.schema===D.schema&&I.name===(D.renamedFrom??D.name)),C="rename or retype in this deploy, and have the access schema read it in the next";P&&D.renamedFrom!==void 0&&D.renamedFrom!==D.name&&this.refuse(`the access schema reads ${F(D)}, renamed in this deploy`,C);let v=new Set([k.key,...zs(y).filter(I=>I.type===k.type).map(I=>I.column)]);for(let I of D.columns){if(!v.has(I.name)||!P)continue;let B=P.columns.find(U=>U.name===(I.renamedFrom??I.name));B&&(I.renamedFrom!==void 0&&I.renamedFrom!==I.name?this.refuse(`the access schema reads ${F(D)}.${I.name}, renamed in this deploy`,C):ae(B.type)!==ae(I.type)&&this.refuse(`the access schema reads ${F(D)}.${I.name}, whose type changes in this deploy`,C))}}}let i=`(SELECT coalesce(pg_catalog.current_setting('palgres.version', true), '') = ${x(String(this.input.next))})`,a=(y,k,D,P)=>{let C=`CREATE POLICY ${b(k.name)} ON ${y} AS ${k.restrictive?"RESTRICTIVE":"PERMISSIVE"} FOR ${k.for.toUpperCase()} TO ${this.policyRoles(k,y)}`;return D!==void 0&&(C+=` USING (${D})`),P!==void 0&&(C+=` WITH CHECK (${P})`),C},l=(y,k)=>`DROP POLICY IF EXISTS ${b(k)} ON ${y}`,c=(y,k)=>k===void 0?void 0:y.restrictive?`(NOT ${i} OR (${k}))`:`(${i} AND (${k}))`,d=(y,k)=>k===void 0?void 0:y.restrictive?`(${i} OR (${k}))`:`(NOT ${i} AND (${k}))`,w=y=>`palgres_was_${vr("sha256").update(y).digest("hex").slice(0,24)}`,u=[],m=[],f=[];for(let y of this.accessPolicies){let k=F(y.table);if(y.to&&(_e(y.to.using)||_e(y.to.withCheck))){let v=y.to.to.length===0?["public"]:y.to.to.filter(I=>On[I]!=="authenticated"&&On[I]!=="service");v.length>0&&this.refuse(`policy ${k}.${y.to.name} reads the access schema and is for ${v.join(", ")}`,"the access schema answers for a signed-in user: a policy that reads it is for authenticated")}let D=(v,I,B)=>{if(v===void 0||B===void 0)return;let U=nr(B,y.table,I);if("refused"in U){I===e?this.refuse(`policy ${k}.${v.name} reads the access schema`,U.refused):this.refuse(`policy ${k}.${v.name} of the version in force reads an access schema the database does not record (${U.refused})`,"nothing is changed: what the policy says could not be kept, or put back");return}return U.sql},P={using:D(y.to,e,y.to?.using),check:D(y.to,e,y.to?.withCheck)},C={using:D(y.from,n,y.from?.using),check:D(y.from,n,y.from?.withCheck)};if(y.to&&y.from){let v=I=>JSON.stringify([I.for,[...I.to].sort(),I.restrictive??!1,I.using===void 0,I.withCheck===void 0]);if(v(y.to)===v(y.from)&&P.using===C.using&&P.check===C.check)continue;if(this.changes.push(`policy ${k}.${y.to.name} changes`),m.push(l(y.q,y.to.name),a(y.q,y.to,P.using,P.check)),v(y.to)===v(y.from)){let I=(B,U)=>B===void 0||U===void 0?B:`CASE WHEN ${i} THEN (${B}) ELSE (${U}) END`;u.push(l(y.q,y.to.name),a(y.q,y.to,I(P.using,C.using),I(P.check,C.check))),f.push(l(y.q,y.to.name),a(y.q,y.from,C.using,C.check))}else{let I=w(y.from.name);u.push(l(y.q,y.to.name),l(y.q,I),a(y.q,y.to,c(y.to,P.using),c(y.to,P.check)),a(y.q,{...y.from,name:I},d(y.from,C.using),d(y.from,C.check))),m.unshift(l(y.q,I)),f.push(l(y.q,I),l(y.q,y.to.name),a(y.q,y.from,C.using,C.check))}}else if(y.to)this.changes.push(`policy ${k}.${y.to.name}`),u.push(l(y.q,y.to.name),a(y.q,y.to,c(y.to,P.using),c(y.to,P.check))),m.push(l(y.q,y.to.name),a(y.q,y.to,P.using,P.check)),f.push(l(y.q,y.to.name));else if(y.from){this.changes.push(`policy ${k}.${y.from.name} goes`);let v=[l(y.q,y.from.name),a(y.q,y.from,C.using,C.check)];u.push(l(y.q,y.from.name),a(y.q,y.from,d(y.from,C.using),d(y.from,C.check))),m.push(l(y.q,y.from.name)),f.push(...v)}}if(!o&&u.length===0){this.toAccess&&this.toAccess.recheck.length>0&&this.accessStart.push({kind:"tx",sql:this.toAccess.recheck,why:"the access schema, checked again"});return}o&&this.changes.push(e?`access schema ${e.digest}${n?` in place of ${n.digest}`:""}`:`access schema ${n?.digest} goes`);let h=new Set((e?.stored??[]).map(y=>y.join("\0"))),T=(n?.stored??[]).filter(y=>!h.has(y.join("\0"))),g=T.map(y=>`(${y.map(x).join(", ")})`).join(", ");T.length>0&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
|
|
145
|
+
EXECUTE format('ALTER TABLE %s ALTER COLUMN %I ADD GENERATED ${$} AS IDENTITY (SEQUENCE NAME %s START WITH %s INCREMENT BY %s)', ${v(n)}, ${v(r.shadow)}, seq_name, seq_next, seq_step);
|
|
146
|
+
END $palgres$`)}else o.complete.push(`ALTER TABLE ${n} DROP COLUMN ${f}`);o.complete.push(`ALTER TABLE ${n} RENAME COLUMN ${g} TO ${N(s)}`)}keepUnconverted(e,n,s,r,o){let i=e.to,a=F(i),l=N(r.from.name),c=te(this.n,"old",s),d=T=>T.includes(r.from.name);o.complete.push(...e.from.uniques.filter(T=>d(T.columns)).map(T=>`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N(T.name)}`),...e.from.foreignKeys.filter(T=>d(T.columns)).map(T=>`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N(T.name)}`),...e.from.indexes.filter(T=>d([...T.keys.flatMap(h=>"column"in h?[h.column]:[]),...T.include??[]])).map(T=>`DROP INDEX IF EXISTS ${D(i.schema,T.name)}`),`ALTER TABLE ${n} ALTER COLUMN ${l} DROP NOT NULL`,`ALTER TABLE ${n} ALTER COLUMN ${l} DROP DEFAULT`,`ALTER TABLE ${n} RENAME COLUMN ${l} TO ${N(c)}`,`ALTER TABLE ${n} RENAME COLUMN ${N(r.shadow)} TO ${N(s)}`);let y=D(i.schema,i.name),u=N(s),m=N(c),f=`(SELECT attnum FROM pg_catalog.pg_attribute WHERE attrelid = ${v(y)}::regclass AND attname = ${v(c)} AND NOT attisdropped)`,g=v(`column ${a}.${s}: values of it that did not become ${r.to.type} are kept in ${c}, outside the schema, and ${s} is NULL in their rows`);if(this.completeAfter.push({kind:"statement",sql:`DO $palgres$ BEGIN IF ${f} IS NOT NULL THEN IF NOT EXISTS (SELECT 1 FROM ${y} WHERE ${u} IS NULL AND ${m} IS NOT NULL) THEN COMMENT ON COLUMN ${y}.${m} IS ${v(_r)}; END IF; END IF; END $palgres$`,why:`${a}.${s}: whether every value became ${r.to.type}`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF pg_catalog.col_description(${v(y)}::regclass, ${f}) = ${v(_r)} THEN ALTER TABLE ${y} DROP COLUMN ${m}; ELSIF ${f} IS NOT NULL THEN RAISE WARNING 'palgres: %', ${g}; END IF; END $palgres$`],why:`${a}.${s}: its values before, once converted`}),!r.to.nullable){let T=te(this.n,"nn",s),h=`EXISTS (SELECT 1 FROM pg_catalog.pg_constraint WHERE conname = ${v(T)} AND conrelid = ${v(y)}::regclass`;this.completeAfter.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF ${f} IS NULL AND NOT ${h}) THEN ALTER TABLE ${y} ADD CONSTRAINT ${N(T)} CHECK (${u} IS NOT NULL) NOT VALID; END IF; END $palgres$`],why:`${a}.${s} is held NOT NULL`},{kind:"statement",sql:`DO $palgres$ BEGIN IF ${h}) THEN ALTER TABLE ${y} VALIDATE CONSTRAINT ${N(T)}; END IF; END $palgres$`,why:`${a}.${s} has no NULL`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF ${h} AND convalidated) THEN ALTER TABLE ${y} ALTER COLUMN ${u} SET NOT NULL; END IF; END $palgres$`,`ALTER TABLE ${y} DROP CONSTRAINT IF EXISTS ${N(T)}`],why:`${a}.${s} is NOT NULL`})}(this.guarded.retyped??=[]).push({schema:i.schema,table:i.name,column:s,kept:c,type:r.to.type,key:i.primaryKey})}checkedDomain(e){if(this.input.checkedDomain(this.typeSql(e))===!0)return!0;let n=ae(e).replace(/^public\./,""),s=o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),r=new RegExp(String.raw`\bCREATE\s+DOMAIN\s+(?:"?public"?\.)?"?${s(n.replace(/^"|"$/g,""))}"?\s[\s\S]*\b(?:CHECK|NOT\s+NULL)\b`,"i");return this.to.raw.some(o=>r.test(o.sql))}conversion(e,n){let s=m=>/(\[\])*$/.exec(m)[0],r=m=>m.slice(0,m.length-s(m).length);if(s(e)!==s(n))return{refused:"one is an array and the other is not, or of another depth"};let o=s(e),i=m=>{let f=ae(r(m));return[...this.to.enums,...this.from.enums].find(g=>$n(g.schema,g.name)===f||g.schema==="public"&&$n(g.schema,g.name)===`public.${f}`)},a=m=>/^(text|citext|public\.citext|character varying(\(\d+\))?|character(\(\d+\))?)$/.test(ae(r(m))),l=m=>f=>`${f}::${this.typeSql(m)}`,c=i(e),d=i(n);if(c&&d){let m=(h,p)=>h.filter(S=>!p.includes(S)),f=m(c.values,d.values),g=m(d.values,c.values);if(f.length>0||g.length>0)return{refused:`the enums' labels differ (${[...f.map(h=>`-${h}`),...g.map(h=>`+${h}`)].join(", ")}), and a label one version writes the other's column cannot hold`};let T=h=>p=>`${p}::text${o}::${this.typeSql(h)}`;return{on:T(n),back:T(e)}}if(c||d)return a(c?n:e)?{on:l(n),back:l(e)}:{refused:`Postgres has no cast between an enum and ${c?n:e}`};let y=this.input.castable(this.typeSql(e),this.typeSql(n)),u=this.input.castable(this.typeSql(n),this.typeSql(e));return y===!1||u===!1?{refused:`Postgres has no cast from ${y===!1?e:n} to ${y===!1?n:e}`}:{on:l(n),back:l(e)}}constraints(e,n,s){let{to:r}=e,o=this.inNewNames(e.from),i=e.from,a=F(r),l=E=>E.some($=>e.retyped.has($)),c=E=>E.some($=>e.retyped.has($)),d=(E,$)=>l($)?te(this.n,"c",E):E,y=(E,$,A)=>{E!==$&&s.complete.push(A?`ALTER TABLE ${n} RENAME CONSTRAINT ${N(E)} TO ${N($)}`:`ALTER INDEX ${D(r.schema,E)} RENAME TO ${N($)}`)},u=(E,$,A,I)=>{let L=[],k=[];for(let x of $){let R=E.find(_=>_.name===x.name);R?(!I(R,x)||l(A(x)))&&(c(A(R))||k.push(R),L.push(x)):L.push(x)}for(let x of E)!$.some(R=>R.name===x.name)&&!c(A(x))&&k.push(x);return{added:L,gone:k}},m=(E,$)=>E.find(A=>A.name===$),f=E=>i.uniques.some($=>$.name===E)||i.indexes.some($=>$.name===E),g=u(o.uniques,r.uniques,E=>E.columns,(E,$)=>E.columns.join()===$.columns.join());this.renamedTwins(g,(E,$)=>E.columns.join()===$.columns.join()&&!l($.columns),(E,$)=>{this.changes.push(`unique ${a}.${E.name} is renamed ${$.name} (at complete)`),s.complete.push(`ALTER TABLE ${n} RENAME CONSTRAINT ${N(E.name)} TO ${N($.name)}`)});for(let E of g.gone)this.changes.push(`unique ${a}.${E.name} goes (at complete)`),s.complete.push(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N(E.name)}`);for(let E of g.added){let $=f(E.name)?te(this.n,"c",E.name):d(E.name,E.columns),A=D(r.schema,$);this.changes.push(`unique ${a}.${E.name}`),this.online.push({kind:"statement",sql:`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ${N($)} ON ${n} (${Re(E.columns.map(I=>e.cols.get(I)))})`,why:`unique ${E.name}`}),this.settle.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${v($)} AND conrelid = ${v(n)}::regclass) THEN ALTER TABLE ${n} ADD CONSTRAINT ${N($)} UNIQUE USING INDEX ${N($)}; END IF; END $palgres$`],why:`unique ${E.name}`}),s.undo.unshift(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N($)}`,`DROP INDEX IF EXISTS ${A}`),y($,E.name,!0)}let T=u(o.checks,r.checks,E=>r.columns.filter($=>Oe(E.expr,$.name)).map($=>$.name),(E,$)=>E.expr.trim()===$.expr.trim());for(let E of T.gone)this.changes.push(`check ${a}.${E.name} goes`),s.tx.push(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N(E.name)}`),s.undo.push(`ALTER TABLE ${n} ADD CONSTRAINT ${N(E.name)} CHECK (${m(i.checks,E.name).expr}) NOT VALID`);for(let E of T.added)this.changes.push(`check ${a}.${E.name}`),s.tx.push(`ALTER TABLE ${n} ADD CONSTRAINT ${N(E.name)} CHECK (${me(E.expr,ke(e.cols))}) NOT VALID`),this.online.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${N(E.name)}`,why:`check ${E.name}`}),s.undo.unshift(`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N(E.name)}`);let h=u(o.foreignKeys,r.foreignKeys,E=>E.columns,(E,$)=>pt(E)===pt($)),p=E=>E.refColumns.some($=>this.matches.get(`${E.refSchema}.${E.refTable}`)?.retyped.has($)??!1);for(let E of r.foreignKeys){if(!p(E))continue;h.added.includes(E)||h.added.push(E);let $=o.foreignKeys.find(A=>A.name===E.name);$&&!h.gone.includes($)&&this.completeFks.push({kind:"tx",sql:[`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N($.name)}`],why:`foreign key ${E.name}, onto the old column`})}for(let E of h.gone)this.changes.push(`foreign key ${a}.${E.name} goes`),this.fkDrops.push({kind:"tx",sql:[`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N(E.name)}`],why:`foreign key ${E.name} goes`}),this.undoFksBack.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD ${this.fkSqlOld(m(i.foreignKeys,E.name))} NOT VALID`],why:`foreign key ${E.name} again`});for(let E of h.added){let $=p(E)?te(this.n,"c",E.name):d(E.name,E.columns);this.changes.push(`foreign key ${a}.${E.name}${p(E)?" references the new column (the old one goes at complete)":""}`),this.lateFks.push({kind:"tx",sql:[`ALTER TABLE ${n} ADD ${this.fkSql({...E,name:$},e.cols)} NOT VALID`],why:`foreign key ${E.name}`}),this.lateFks.push({kind:"statement",sql:`ALTER TABLE ${n} VALIDATE CONSTRAINT ${N($)}`,why:`foreign key ${E.name}`}),this.undoFksGone.push({kind:"tx",sql:[`ALTER TABLE ${n} DROP CONSTRAINT IF EXISTS ${N($)}`],why:`foreign key ${E.name}`}),y($,E.name,!0)}for(let E of r.foreignKeys){let $=o.foreignKeys.find(A=>A.name===E.name);!$||pt($)!==pt(E)||l(E.columns)||p(E)||($.deferrable??!1)===(E.deferrable??!1)||(this.changes.push(`foreign key ${a}.${E.name} is ${E.deferrable?"":"not "}deferrable (in the catalog, no row read again; ${a} locked a moment, the lock given way to while others hold it and tried again)`),s.tx.push(`ALTER TABLE ${n} ALTER CONSTRAINT ${N(E.name)} ${E.deferrable?"DEFERRABLE":"NOT DEFERRABLE"}`),s.undo.push(`ALTER TABLE ${n} ALTER CONSTRAINT ${N(E.name)} ${E.deferrable?"NOT DEFERRABLE":"DEFERRABLE"}`))}if(r.primaryKey.some(E=>e.retyped.has(E))){let E=te(this.n,"pk",r.name),$=`${r.name}_pkey`;this.changes.push(`the primary key of ${a} is made again on the new column (its index built at start, the key at complete)`),this.online.push({kind:"statement",sql:`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ${N(E)} ON ${n} (${Re(r.primaryKey.map(A=>e.cols.get(A)))})`,why:`the primary key of ${a}, on the new column`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${D(r.schema,E)}`,why:`the primary key of ${a}, on the new column`}),s.complete.push(`ALTER TABLE ${n} ADD PRIMARY KEY USING INDEX ${N(E)}`),Buffer.byteLength($)<=63&&s.complete.push(`DO $palgres$ BEGIN IF to_regclass(${v(D(r.schema,$))}) IS NULL THEN ALTER INDEX ${D(r.schema,E)} RENAME TO ${N($)}; END IF; END $palgres$`)}let S=E=>[...E.keys.flatMap($=>"column"in $?[$.column]:[]),...E.include??[]],b=u(o.indexes,r.indexes,S,(E,$)=>ft(E)===ft($));this.renamedTwins(b,(E,$)=>ft(E)===ft($)&&!l(S($)),(E,$)=>{this.changes.push(`index ${a}.${E.name} is renamed ${$.name} (at complete)`),s.complete.push(`ALTER INDEX ${D(r.schema,E.name)} RENAME TO ${N($.name)}`)});for(let E of b.added){if(!E.unique)continue;let $=S(E).slice(0,E.keys.length),A=b.gone.find(L=>L.unique&&S(L).slice(0,L.keys.length).join()===$.join());if(!A)continue;let I=this.to.tables.flatMap(L=>L.foreignKeys.filter(k=>k.refSchema===r.schema&&k.refTable===r.name&&k.refColumns.join()===$.join()).map(k=>`${F(L)}.${k.name}`));I.length>0&&this.refuse(`unique index ${a}.${A.name} is built again as ${E.name}, and foreign key ${I.join(", ")} reference its columns`,"Postgres binds a foreign key to the first unique index over its columns \u2014 the old one, which then cannot go: change the index in one deploy and the foreign keys in another, or give the new index other key columns")}for(let E of b.gone)b.added.some($=>$.name===E.name)?(this.changes.push(`index ${a}.${E.name} is built again (the old one goes at complete)`),s.complete.push(`DROP INDEX IF EXISTS ${D(r.schema,E.name)}`)):(this.changes.push(`index ${a}.${E.name} goes (at complete)`),this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${D(r.schema,E.name)}`,why:`index ${E.name}`}));for(let E of b.added){let $=f(E.name)?te(this.n,"i",E.name):d(E.name,S(E));this.changes.push(`index ${a}.${E.name}`),this.online.push({kind:"statement",sql:this.indexSql(r.schema,e.physical,{...E,name:$},e.cols,!0),why:`index ${E.name}`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${D(r.schema,$)}`,why:`index ${E.name}`}),y($,E.name,!1)}}renamedTwins(e,n,s){for(let r of[...e.gone]){let o=e.added.find(i=>i.name!==r.name&&n(r,i)&&!e.gone.some(a=>a.name===i.name));o&&(e.gone.splice(e.gone.indexOf(r),1),e.added.splice(e.added.indexOf(o),1),s(r,o))}}indexSql(e,n,s,r,o){let i=ke(r),a=s.keys.map(c=>{let d="column"in c?N(r.get(c.column)??c.column):`(${me(c.expr,i)})`;return c.desc&&(d+=" DESC"),c.nulls&&(d+=` NULLS ${c.nulls.toUpperCase()}`),d}),l=`CREATE ${s.unique?"UNIQUE ":""}INDEX ${o?"CONCURRENTLY ":""}IF NOT EXISTS ${N(s.name)} ON ${D(e,n)}`;return s.method&&s.method!=="btree"&&(l+=` USING ${s.method}`),l+=` (${a.join(", ")})`,s.include?.length&&(l+=` INCLUDE (${Re(s.include.map(c=>r.get(c)??c))})`),s.where!==void 0&&(l+=` WHERE ${me(s.where,i)}`),l}fkSql(e,n){let s=this.to.tables.find(o=>o.schema===e.refSchema&&o.name===e.refTable),r=s?this.where(s):{table:e.refTable,cols:new Map};return`CONSTRAINT ${N(e.name)} FOREIGN KEY (${Re(e.columns.map(o=>n.get(o)??o))}) REFERENCES ${D(e.refSchema,r.table)} (${Re(e.refColumns.map(o=>r.cols.get(o)??o))})${e.match==="full"?" MATCH FULL":""} ON DELETE ${e.onDelete.toUpperCase()} ON UPDATE ${e.onUpdate.toUpperCase()}${e.deferrable?" DEFERRABLE":""}`}fkSqlOld(e){return`CONSTRAINT ${N(e.name)} FOREIGN KEY (${Re(e.columns)}) REFERENCES ${D(e.refSchema,e.refTable)} (${Re(e.refColumns)})${e.match==="full"?" MATCH FULL":""} ON DELETE ${e.onDelete.toUpperCase()} ON UPDATE ${e.onUpdate.toUpperCase()}${e.deferrable?" DEFERRABLE":""}`}generations(e){return[...this.input.generations?.(e)??[]].sort((n,s)=>n.gen-s.gen)}search(e,n){let s=F(e),r=e.search,o=n?.from.search;if(r===void 0){n&&this.searchGone(n.from,n.physical);return}let i=Xs(`table ${s}`,e,r);if(i.length>0){this.refusals.push(...i);return}let a=e.columns.find(S=>S.name===e.primaryKey[0]),l=this.generations(n?F(n.from):s),c=l.filter(S=>S.status!=="retired"),d=c.find(S=>S.status==="active"),y=c.at(-1),u=y===void 0?[]:rt(y,r)?c:d?[d]:[],m=y===void 0?"active":rt(y,r)||d!==void 0&&rt(d,r)?void 0:"filling";if(n){let S="take search out of the table and deploy, make the change in the next deploy, and declare search again in the one after \u2014 every row is embedded again then";e.name!==n.from.name&&this.refuse(`table ${e.schema}.${n.from.name} is renamed ${e.name} while it declares search`,S);let b=new Set;for(let E of new Set([a.name,...r.from])){let $=E===a.name?"search keeps each row's vector by it":"search reads it";if(n.retyped.has(E))this.refuse(`column ${s}.${E} changes type, and ${$}`,S);else if((n.cols.get(E)??E)!==E)this.refuse(`column ${s}.${E} ${n.parked.has(E)?"takes a name another column leaves in this deploy":`is renamed from ${n.cols.get(E)}`}, and ${$}`,S);else continue;b.add(n.retyped.get(E)?.from.name??n.cols.get(E)??E)}for(let E of u)for(let $ of E.from){if(b.has($))continue;e.columns.some(I=>I.name===$)&&!n.retyped.has($)&&(n.cols.get($)??$)===$||this.refuse(`column ${s}.${$} goes or changes, and the vectors that serve search of ${s} now (generation ${E.gen}) are made from it`,"they serve until the new ones are complete: leave the column as it is in this deploy, and change it in a deploy after that")}}let f={schema:e.schema,name:n?n.physical:e.name},g=D(f.schema,f.name);if(m!==void 0){let S=(l.at(-1)?.gen??0)+1;this.changes.push(m==="active"?`search of ${s}: its rows are embedded with ${r.model} (${r.dimensions} dimensions) in the background; found by their words until then`:`search of ${s}: every row is embedded again with ${r.model} (${r.dimensions} dimensions) in the background; the vectors there serve until the new ones are complete`),this.searchStart.push({kind:"tx",sql:Lr({table:f,gen:S,search:r,status:m,pk:{name:a.name,type:this.typeSql(a.type)},roles:this.input.roles,types:this.input.vectorSchema??"public"}),why:`search of ${s}: generation ${S}`}),n&&this.searchStart.push({kind:"statement",sql:Cr(f,S,a.name),why:`search of ${s}: its rows queued`}),this.undoSearch.push({kind:"tx",sql:ct(f,S),why:`search of ${s}: generation ${S}`})}if(o!==void 0&&o.staleness!==r.staleness&&u.length>0){this.changes.push(`search of ${s}: a changed row's old vector ${r.staleness==="null"?"goes":"stays"} until the row is embedded again`);for(let S of u)this.searchStart.push({kind:"tx",sql:lt({table:f,gen:S.gen,from:S.from,staleness:r.staleness},!0),why:`search of ${s}: generation ${S.gen}'s triggers`}),this.undoSearch.push({kind:"tx",sql:lt({table:f,gen:S.gen,from:S.from,staleness:o.staleness},!0),why:`search of ${s}: generation ${S.gen}'s triggers`})}for(let S of l)u.includes(S)||(this.changes.push(`search of ${s}: generation ${S.gen}'s vectors, ${S.status==="retired"?"left behind":"never full"}, go (at complete)`),this.searchComplete.push({kind:"tx",sql:ct(f,S.gen),why:`search of ${s}: generation ${S.gen}`}));let T=ot(f,r.from),h=o===void 0?void 0:ot(f,o.from);if(T===h)return;let p=S=>`CREATE INDEX ${S?"CONCURRENTLY ":""}IF NOT EXISTS ${N(T)} ON ${g} USING gin (${at(r.from)})`;o!==void 0&&this.changes.push(`search of ${s} reads ${r.from.join(", ")}`),n?(this.online.push({kind:"statement",sql:p(!0),why:`search of ${s}: its words`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${D(f.schema,T)}`,why:`search of ${s}: its words`})):this.creates.push(p(!1)),h!==void 0&&this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${D(f.schema,h)}`,why:`search of ${s}: the words it read`})}searchGone(e,n){let s=this.generations(F(e));if(e.search===void 0&&s.length===0)return;let r={schema:e.schema,name:n},o=F(e);this.changes.push(`search of ${o} goes (at complete)`);for(let i of s)this.searchComplete.push({kind:"tx",sql:ct(r,i.gen),why:`search of ${o}: generation ${i.gen}`});e.search!==void 0&&this.searchComplete.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${D(r.schema,ot(r,e.search.from))}`,why:`search of ${o}: the words it read`})}compileAccess(){if(this.to.access!==void 0)try{let e=rr(this.to,{authenticated:this.input.roles.authenticated,service:this.input.roles.service,visitor:this.input.roles.anon},(this.input.from?.access?.names??[]).map(n=>({name:n.view,type:n.idType})));if(e.digest!==this.to.access.compiled){this.refuse(`the access schema compiles to ${e.digest} for this database's roles, and the schema carries ${this.to.access.compiled}`,"the model was made for other roles than the migration runs with: give toModel the same roles");return}this.toAccess=e,this.toRecorded=or(e,this.to.access.text)}catch(e){if(!(e instanceof Ys))throw e;this.refuse(`the access schema: ${e.message}`,"mend it: nothing is compiled from a schema that does not hold together")}}access(){let e=this.toRecorded,n=this.fromRecorded;if(!e&&!n){for(let w of this.accessPolicies){let O=w.to??w.from;w.to&&this.refuse(`policy ${F(w.table)}.${O.name} reads the access schema`,"the schema declares none: give the database one (db.access)")}return}let s=N("access"),r={authenticated:this.input.roles.authenticated,service:this.input.roles.service,visitor:this.input.roles.anon},o=e?.digest!==n?.digest;if(e&&this.to.access){let w=zs(Js(this.to.access.text));for(let O of e.tables){let C=this.to.tables.find(U=>U.schema===O.schema&&U.name===O.name);if(!C)continue;let W=this.from.tables.find(U=>U.schema===C.schema&&U.name===(C.renamedFrom??C.name)),M="rename or retype in this deploy, and have the access schema read it in the next";W&&C.renamedFrom!==void 0&&C.renamedFrom!==C.name&&this.refuse(`the access schema reads ${F(C)}, renamed in this deploy`,M);let j=new Set([O.key,...tr(w).filter(U=>U.type===O.type).map(U=>U.column)]);for(let U of C.columns){if(!j.has(U.name)||!W)continue;let H=W.columns.find(G=>G.name===(U.renamedFrom??U.name));H&&(U.renamedFrom!==void 0&&U.renamedFrom!==U.name?this.refuse(`the access schema reads ${F(C)}.${U.name}, renamed in this deploy`,M):ae(H.type)!==ae(U.type)&&this.refuse(`the access schema reads ${F(C)}.${U.name}, whose type changes in this deploy`,M))}}}let i=`(SELECT coalesce(pg_catalog.current_setting('palgres.version', true), '') = ${v(String(this.input.next))})`,a=(w,O,C,W)=>{let M=`CREATE POLICY ${N(O.name)} ON ${w} AS ${O.restrictive?"RESTRICTIVE":"PERMISSIVE"} FOR ${O.for.toUpperCase()} TO ${this.policyRoles(O,w)}`;return C!==void 0&&(M+=` USING (${C})`),W!==void 0&&(M+=` WITH CHECK (${W})`),M},l=(w,O)=>`DROP POLICY IF EXISTS ${N(O)} ON ${w}`,c=(w,O)=>O===void 0?void 0:w.restrictive?`(NOT ${i} OR (${O}))`:`(${i} AND (${O}))`,d=(w,O)=>O===void 0?void 0:w.restrictive?`(${i} OR (${O}))`:`(NOT ${i} AND (${O}))`,y=w=>`palgres_was_${Mr("sha256").update(w).digest("hex").slice(0,24)}`,u=[],m=[],f=[];for(let w of this.accessPolicies){let O=F(w.table);if(w.to&&(_e(w.to.using)||_e(w.to.withCheck))){let j=ir([w.to.using,w.to.withCheck],w.table,this.toAccess),U=j!==null&&j.length===0,H=w.to.to.length===0?["public"]:w.to.to.filter(G=>Ve[G]!=="authenticated"&&Ve[G]!=="service"&&!(U&&Ve[G]==="anon"));if(H.length>0){let G=H.every(Q=>Ve[Q]==="anon")&&j!==null;this.refuse(`policy ${O}.${w.to.name} reads the access schema and is for ${H.join(", ")}`,G?`nothing opens ${j.join(", ")} to the public, so nobody who has not signed in could hold it: the policy is for authenticated \u2014 or the name is read through a relation that takes public`:"the access schema answers for whoever asks through the app: a policy that reads it is for authenticated \u2014 and for anon too, where the public can hold every name it reads")}}let C=(j,U,H)=>{if(j===void 0||H===void 0)return;let G=ar(H,w.table,U);if("refused"in G){U===e?this.refuse(`policy ${O}.${j.name} reads the access schema`,G.refused):this.refuse(`policy ${O}.${j.name} of the version in force reads an access schema the database does not record (${G.refused})`,"nothing is changed: what the policy says could not be kept, or put back");return}return G.sql},W={using:C(w.to,e,w.to?.using),check:C(w.to,e,w.to?.withCheck)},M={using:C(w.from,n,w.from?.using),check:C(w.from,n,w.from?.withCheck)};if(w.to&&w.from){let j=U=>JSON.stringify([U.for,[...U.to].sort(),U.restrictive??!1,U.using===void 0,U.withCheck===void 0]);if(j(w.to)===j(w.from)&&W.using===M.using&&W.check===M.check)continue;if(this.changes.push(`policy ${O}.${w.to.name} changes`),m.push(l(w.q,w.to.name),a(w.q,w.to,W.using,W.check)),j(w.to)===j(w.from)){let U=(H,G)=>H===void 0||G===void 0?H:`CASE WHEN ${i} THEN (${H}) ELSE (${G}) END`;u.push(l(w.q,w.to.name),a(w.q,w.to,U(W.using,M.using),U(W.check,M.check))),f.push(l(w.q,w.to.name),a(w.q,w.from,M.using,M.check))}else{let U=y(w.from.name);u.push(l(w.q,w.to.name),l(w.q,U),a(w.q,w.to,c(w.to,W.using),c(w.to,W.check)),a(w.q,{...w.from,name:U},d(w.from,M.using),d(w.from,M.check))),m.unshift(l(w.q,U)),f.push(l(w.q,U),l(w.q,w.to.name),a(w.q,w.from,M.using,M.check))}}else if(w.to)this.changes.push(`policy ${O}.${w.to.name}`),u.push(l(w.q,w.to.name),a(w.q,w.to,c(w.to,W.using),c(w.to,W.check))),m.push(l(w.q,w.to.name),a(w.q,w.to,W.using,W.check)),f.push(l(w.q,w.to.name));else if(w.from){this.changes.push(`policy ${O}.${w.from.name} goes`);let j=[l(w.q,w.from.name),a(w.q,w.from,M.using,M.check)];u.push(l(w.q,w.from.name),a(w.q,w.from,d(w.from,M.using),d(w.from,M.check))),m.push(l(w.q,w.from.name)),f.push(...j)}}if(!o&&u.length===0){this.toAccess&&this.toAccess.recheck.length>0&&this.accessStart.push({kind:"tx",sql:this.toAccess.recheck,why:"the access schema, checked again"});return}o&&this.changes.push(e?`access schema ${e.digest}${n?` in place of ${n.digest}`:""}`:`access schema ${n?.digest} goes`);let g=new Set((e?.stored??[]).map(w=>w.join("\0"))),T=(n?.stored??[]).filter(w=>!g.has(w.join("\0"))),h=T.map(w=>`(${w.map(v).join(", ")})`).join(", ");T.length>0&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
|
|
147
147
|
DECLARE n bigint;
|
|
148
148
|
BEGIN
|
|
149
149
|
IF pg_catalog.to_regclass('access.relationships') IS NULL THEN RETURN; END IF;
|
|
150
|
-
SELECT count(*) INTO n FROM ${s}.relationships WHERE (object_type, relation,
|
|
150
|
+
SELECT count(*) INTO n FROM ${s}.relationships r WHERE (r.object_type, r.relation, ${Bt("r")}) IN (${h}) AND ${Zs("r")};
|
|
151
151
|
IF n > 0 THEN
|
|
152
|
-
RAISE EXCEPTION 'the access schema no longer keeps % (as type.relation): % relationships are kept in them \u2014 take them away before this deploy', ${
|
|
152
|
+
RAISE EXCEPTION 'the access schema no longer keeps % (as type.relation): % relationships are kept in them \u2014 take them away before this deploy', ${v(T.map(w=>`${w[0]}.${w[1]}`).join(", "))}, n;
|
|
153
153
|
END IF;
|
|
154
154
|
END $guard$`],why:"no relationship is left without its relation"}),e&&!n&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
|
|
155
155
|
DECLARE d text;
|
|
156
156
|
BEGIN
|
|
157
157
|
IF pg_catalog.to_regclass('access.schemas') IS NULL THEN RETURN; END IF;
|
|
158
|
-
SELECT digest INTO d FROM ${s}.schemas WHERE active AND digest <> ${
|
|
158
|
+
SELECT digest INTO d FROM ${s}.schemas WHERE active AND digest <> ${v(e.digest)} LIMIT 1;
|
|
159
159
|
IF d IS NOT NULL THEN
|
|
160
160
|
RAISE EXCEPTION 'this database already answers from an access schema put in from the command line (%): an app''s migrations do not take one over', d;
|
|
161
161
|
END IF;
|
|
162
|
-
END $guard$`],why:"no access schema is in force that this app did not migrate"});let p=(
|
|
162
|
+
END $guard$`],why:"no access schema is in force that this app did not migrate"});let p=(w,O)=>w.type===O.type&&w.schema===O.schema&&w.name===O.name&&w.key===O.key,S=(e?.tables??[]).filter(w=>!(n?.tables??[]).some(O=>p(O,w))),b=S.map(w=>v(w.type)).join(", ");S.length>0&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
|
|
163
163
|
DECLARE n bigint;
|
|
164
164
|
BEGIN
|
|
165
165
|
IF pg_catalog.to_regclass('access.relationships') IS NULL THEN RETURN; END IF;
|
|
166
|
-
EXECUTE ${
|
|
166
|
+
EXECUTE ${v(`SELECT count(*) FROM ${s}.relationships WHERE object_type IN (${b}) OR subject_type IN (${b})`)} INTO n;
|
|
167
167
|
IF n > 0 THEN
|
|
168
|
-
RAISE EXCEPTION '% relationships are kept of % while this deploy gives the type its table (or another): the ids they name are not that table''s rows \u2014 take them away before this deploy', n, ${
|
|
168
|
+
RAISE EXCEPTION '% relationships are kept of % while this deploy gives the type its table (or another): the ids they name are not that table''s rows \u2014 take them away before this deploy', n, ${v(S.map(w=>w.type).join(", "))};
|
|
169
169
|
END IF;
|
|
170
|
-
END $guard$`],why:"no relationship names a row it was not given on"});let E=`access_binding_${this.input.next}`,$=S.length>0?[`DROP TRIGGER IF EXISTS ${
|
|
170
|
+
END $guard$`],why:"no relationship names a row it was not given on"});let E=`access_binding_${this.input.next}`,$=S.length>0?[`DROP TRIGGER IF EXISTS ${N(E)} ON ${s}.relationships`,`CREATE TRIGGER ${N(E)} BEFORE INSERT OR UPDATE ON ${s}.relationships FOR EACH ROW EXECUTE FUNCTION ${s}.binding_guard(${[String(this.input.next),...S.map(w=>w.type)].map(v).join(", ")})`]:[],A=S.length>0?[`DROP TRIGGER IF EXISTS ${N(E)} ON ${s}.relationships`]:[],I=o?(this.toAccess?.kept??[]).filter(w=>!(n?.kept??[]).some(O=>O.type===w.type&&O.relation===w.relation&&O.depth<=w.depth)):[],L=`access_nesting_${this.input.next}`,k=I.length>0?[`DROP TRIGGER IF EXISTS ${N(L)} ON ${s}.relationships`,`CREATE TRIGGER ${N(L)} BEFORE INSERT OR UPDATE ON ${s}.relationships FOR EACH ROW EXECUTE FUNCTION ${s}.nest_guard(${[String(this.input.next),...I.flatMap(w=>[w.type,w.relation])].map(v).join(", ")})`]:[],x=I.length>0?[`DROP TRIGGER IF EXISTS ${N(L)} ON ${s}.relationships`]:[],R=o&&this.toAccess?[...nr(r),...this.toAccess.build,...this.toAccess.watch,...this.toAccess.open]:this.toAccess?[...this.toAccess.open]:[],_=this.toAccess?this.toAccess.recheck:[];R.length+u.length+$.length+k.length+_.length>0&&this.accessStart.push({kind:"tx",sql:[...R,...$,...k,...u,..._],why:"the access schema, beside the one in force"});let P=[...A,...x,...m];if(o&&this.toAccess&&e){P.push(er(),...this.toAccess.point,...this.toAccess.record);for(let w of n?.names??[])e.names.some(O=>O.view===w.view)||P.push(`DROP VIEW IF EXISTS ${s}.${N(w.view)}`)}if(o&&n){T.length>0&&P.push("SELECT pg_catalog.set_config('access.actor', 'access: schema changed', true)",`DELETE FROM ${s}.relationships r WHERE (r.object_type, r.relation, ${Bt("r")}) IN (${h})`,"SELECT pg_catalog.set_config('access.actor', '', true)");for(let w of n.tables)if(!e?.tables.some(O=>O.schema===w.schema&&O.name===w.name)&&this.to.tables.some(O=>O.schema===w.schema&&O.name===w.name))for(let O of[...Ut,Hn])P.push(`DROP TRIGGER IF EXISTS ${N(O)} ON ${D(w.schema,w.name)}`);if(!e){for(let w of n.names)P.push(`DROP VIEW IF EXISTS ${s}.${N(w.view)}`);P.push(...sr())}P.push(...Wt(n.schema))}P.length>0&&this.accessComplete.push({kind:"tx",sql:P,why:"the access schema in force"});let B=[...A,...x,...f];if(o&&e){S.length>0&&B.push(`DO $undo$
|
|
171
171
|
BEGIN
|
|
172
172
|
IF pg_catalog.to_regclass('access.relationships') IS NULL THEN RETURN; END IF;
|
|
173
173
|
PERFORM pg_catalog.set_config('access.actor', 'access: rolled back', true);
|
|
174
|
-
EXECUTE ${
|
|
174
|
+
EXECUTE ${v(`DELETE FROM ${s}.relationships WHERE object_type IN (${b}) OR subject_type IN (${b})`)};
|
|
175
175
|
PERFORM pg_catalog.set_config('access.actor', '', true);
|
|
176
|
-
END $undo$`),_.push(...Ut(e.schema));for(let y of e.tables)if(!n?.tables.some(k=>k.schema===y.schema&&k.name===y.name)&&this.from.tables.some(k=>k.schema===y.schema&&k.name===y.name))for(let k of qt)_.push(`DROP TRIGGER IF EXISTS ${b(k)} ON ${M(y.schema,y.name)}`)}_.length>0&&this.accessUndo.push({kind:"tx",sql:_,why:"the access schema, as it was"})}policyRoles(e,n){let s=new Set;for(let r of e.to){if(r.startsWith("role:")&&r.length>5){s.add(b(r.slice(5)));continue}let o=On[r];if(!o){this.refuse(`policy ${n}.${e.name} is for role ${r}`,`a policy is for ${Object.keys(On).join(", ")}`);continue}s.add(o==="public"?"PUBLIC":b(this.input.roles[o]))}return[...s].join(", ")}policySql(e,n,s){let r=ke(s),o=`CREATE POLICY ${b(n.name)} ON ${e} AS ${n.restrictive?"RESTRICTIVE":"PERMISSIVE"} FOR ${n.for.toUpperCase()} TO ${this.policyRoles(n,e)}`;return n.using!==void 0&&(o+=` USING (${me(n.using,r)})`),n.withCheck!==void 0&&(o+=` WITH CHECK (${me(n.withCheck,r)})`),o}policies(e,n,s){let{to:r}=e,o=this.inNewNames(e.from),i=F(r),a=m=>JSON.stringify([m.for,[...new Set(m.to.map(f=>On[f]??f))].sort(),m.using??null,m.withCheck??null,m.restrictive??!1]),l=m=>e.from.policies.find(f=>f.name===m),c=m=>m!==void 0&&(_e(m.using)||_e(m.withCheck)),d=r.policies.some(c)||o.policies.some(c),w=ke(e.cols).size>0,u=m=>({...m,...m.using!==void 0?{using:me(m.using,ke(e.cols))}:{},...m.withCheck!==void 0?{withCheck:me(m.withCheck,ke(e.cols))}:{}});for(let m of r.policies){let f=o.policies.find(h=>h.name===m.name);if(c(m)||c(f)){this.accessPolicies.push({q:n,table:r,to:m,...f?{from:l(m.name)}:{}});continue}if(!(f&&a(f)===a(m))){if(d){w&&this.refuse(`policy ${i}.${m.name} changes on a table whose policies read the access schema, in a deploy that renames its columns`,"rename the columns in one deploy, and change the policy in the next"),this.accessPolicies.push({q:n,table:r,to:u(m),...f?{from:l(m.name)}:{}});continue}this.readsOthersRenamed(r,m,i)||(this.changes.push(`policy ${i}.${m.name}${f?" changes":""}`),s.undo.push(`DROP POLICY IF EXISTS ${b(m.name)} ON ${n}`),f&&(s.tx.push(`DROP POLICY IF EXISTS ${b(m.name)} ON ${n}`),s.undo.push(this.policySql(n,l(m.name),Lr(e.from)))),s.tx.push(this.policySql(n,m,e.cols)))}}for(let m of o.policies)if(!r.policies.some(f=>f.name===m.name)){if(c(m)||d){this.accessPolicies.push({q:n,table:r,from:l(m.name)});continue}this.changes.push(`policy ${i}.${m.name} goes`),s.tx.push(`DROP POLICY IF EXISTS ${b(m.name)} ON ${n}`),s.undo.push(this.policySql(n,l(m.name),Lr(e.from)))}}readsOthersRenamed(e,n,s){let r=`${n.using??""} ${n.withCheck??""}`;for(let o of this.to.tables){if(o===e)continue;let i=this.from.tables.find(l=>l.schema===o.schema&&l.name===(o.renamedFrom??o.name));if(!i)continue;let a=[...o.name!==i.name&&Oe(r,o.name)?[`${o.schema}.${o.name}`]:[],...Oe(r,o.name)?o.columns.filter(l=>l.renamedFrom!==void 0&&l.renamedFrom!==l.name&&i.columns.some(c=>c.name===l.renamedFrom)&&Oe(r,l.name)).map(l=>`${o.schema}.${o.name}.${l.name}`):[]];if(a.length>0)return this.refuse(`policy ${s}.${n.name} reads ${a.join(", ")}, renamed in this deploy`,"Postgres has the new name only from complete on: rename in this deploy, change the policy in the next"),!0}return!1}rawUnitsBefore(){let e=!0;for(let n of this.to.raw){if(!n.before)continue;let s=this.from.raw.find(r=>r.name===n.name);if(!(s&&s.sql.trim()===n.sql.trim())){if(s&&/^\s*CREATE\s+(?:DOMAIN|TYPE|SEQUENCE)\b/i.test(s.sql)){this.refuse(`raw ${n.name} changes`,"Postgres cannot drop a domain or a type a column uses, and a sequence made again starts over: say the change as an ALTER (ALTER DOMAIN \u2026 ADD CONSTRAINT \u2026 NOT VALID, ALTER TYPE, ALTER SEQUENCE) in a unit of its own, or make a new one and move the columns to it");continue}this.changes.push(`raw ${n.name}${s?" changes":""}`),e&&this.creates.push("SET LOCAL check_function_bodies = off"),e=!1,this.creates.push(...this.rawApply(n,s)),!s&&n.drop!==void 0&&this.undoCreates.push(n.drop),s&&this.undoRawsBack.push(...this.rawApply(s,n))}}}rawApply(e,n){return!n||/^\s*CREATE\s+OR\s+REPLACE\b/i.test(e.sql)||n.drop===void 0?[e.sql]:[n.drop,e.sql]}rawUnits(){let e=this.to.raw.filter(c=>!c.before),n=c=>/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\b/i.test(c),s=this.namesAtComplete,r=this.dropsColumnsAtComplete,o=e.findIndex(c=>{let d=this.from.raw.find(w=>w.name===c.name);return n(c.sql)?r&&d!==void 0?!0:d===void 0?s:d.sql.trim()!==c.sql.trim():!1}),i=new Set,a=new Set,l=null;if(o>=0){let c=e.slice(o),d=u=>n(u)||/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i.test(u)||zt.test(u),w=[];for(let u of[...this.from.raw].reverse()){if(u.before||u.drop===void 0)continue;let m=c.some(h=>h.name===u.name),f=!this.to.raw.some(h=>h.name===u.name);(m&&d(u.sql)||f&&n(u.sql))&&w.push(u.drop),f&&n(u.sql)&&a.add(u.name)}for(let u of c){let m=this.from.raw.find(f=>f.name===u.name);(!m||m.sql.trim()!==u.sql.trim())&&this.changes.push(`raw ${u.name}${m?" changes":""}`),i.add(u.name)}if(s){this.viewsAtComplete={drops:w,creates:c.map(u=>u.sql)};for(let u of c){let m=this.changes.findIndex(f=>f===`raw ${u.name}`||f===`raw ${u.name} changes`);m>=0&&(this.changes[m]+=" (at complete)")}}else{l={kind:"tx",sql:["SET LOCAL check_function_bodies = off",...w,...c.map(u=>u.sql)],why:`raw ${c[0].name} and what follows it, made again`};for(let u of[...c].reverse())u.drop!==void 0&&this.undoRawsGone.push(u.drop);for(let u of this.from.raw){if(u.before||u.drop===void 0)continue;let m=c.some(h=>h.name===u.name),f=!this.to.raw.some(h=>h.name===u.name);(m&&d(u.sql)||f&&n(u.sql))&&this.undoRawsBack.push(u.sql)}}}for(let c of this.to.raw){if(c.before||(l!==null&&c.name===e[o].name&&this.raws.push(l),i.has(c.name)))continue;let d=this.from.raw.find(u=>u.name===c.name),w=Cr(c.sql);if(!(d&&d.sql.trim()===c.sql.trim())){if(d&&w){this.refuse(`raw index ${c.name} changes under its name`,"an index is built CONCURRENTLY next to the one serving, so under a name of its own: give the new one its own name (the old one goes at complete)");continue}if(this.changes.push(`raw ${c.name}${d?" changes":""}`),w)this.raws.push({kind:"statement",sql:w.create,why:`raw ${c.name}`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${w.qualified(c,this.to)}`,why:`raw ${c.name}`});else{if(c.drop===void 0&&(zt.test(c.sql)||n(c.sql))){this.refuse(`raw ${c.name} has no drop`,"a rollback could not take it back, and the old version would write and read past it: give it its drop (raw(name, up, { drop }))");continue}this.raws.push({kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.rawApply(c,d)],why:`raw ${c.name}`}),c.drop!==void 0&&this.undoRawsGone.unshift(c.drop),d&&this.undoRawsBack.push(...c.drop!==void 0?[d.sql]:this.rawApply(d,c))}}}for(let c of[...this.from.raw].reverse()){if(this.to.raw.some(w=>w.name===c.name))continue;if(a.has(c.name)){this.changes.push(`raw ${c.name} goes (with the views made again)`);continue}let d=Cr(c.sql);if(!d){if(c.drop===void 0){this.refuse(`raw ${c.name} is gone from the schema`,"Palgres does not know how to take back what its SQL made: keep it, or give the unit its drop (raw(name, up, { drop })) and remove it in the deploy after that");continue}this.changes.push(`raw ${c.name} goes (at complete)`),zt.test(c.sql)?this.completeUnitDrops.push(c.drop):this.completeIndexes.push({kind:"tx",sql:[c.drop],why:`raw ${c.name}`});continue}this.changes.push(`raw index ${c.name} goes (at complete)`),this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${d.qualified(c,this.from)}`,why:`raw ${c.name}`})}}views(){let{anon:e,authenticated:n,service:s}=this.input.roles,r=[e,n,s].map(b).join(", "),o=[];for(let i of[...new Set(this.layout.tables.map(a=>a.schema))]){let a=b(Le(this.n,i));o.push(`DROP SCHEMA IF EXISTS ${a} CASCADE`,`CREATE SCHEMA ${a}`,`GRANT USAGE ON SCHEMA ${a} TO ${r}`)}for(let i of this.layout.tables){let a=i.columns.map(c=>c.physical===c.name?b(c.name):`${b(c.physical)} AS ${b(c.name)}`).join(", "),l=M(Le(this.n,i.schema),i.name);o.push(`CREATE VIEW ${l} WITH (security_invoker = true) AS SELECT ${a} FROM ${M(i.schema,i.physical)}`),o.push(`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${l} TO ${r}`)}return o}dropViews(e,n){let s=[...new Set(n.tables.map(r=>r.schema))];return s.length>0?s.map(r=>`DROP SCHEMA IF EXISTS ${b(Le(e,r))} CASCADE`):["SELECT 1"]}keyOf(e){let n=this.where(e);return e.primaryKey.map(s=>{let r=this.matches.get(F(e))?.retyped.get(s);return r?r.from.name:n.cols.get(s)??s})}};function Lr(t){return new Map(t.columns.map(e=>[e.name,e.name]))}function ke(t){return new Map([...t].filter(([e,n])=>e!==n))}function ln(t,e,n){return e?[`ALTER TABLE ${t} ENABLE ROW LEVEL SECURITY`]:n?[`ALTER TABLE ${t} DISABLE ROW LEVEL SECURITY`]:[]}function mt(t){return JSON.stringify([t.columns,t.refSchema,t.refTable,t.refColumns,t.onDelete,t.onUpdate,t.match??"simple"])}function pt(t){return JSON.stringify([t.keys,t.unique,t.where??null,t.method??"btree",t.include??[]])}var zt=/^\s*(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:TRIGGER|CONSTRAINT\s+TRIGGER|RULE)\b|DO\s+\$\w*\$\s+BEGIN\s+IF\s+NOT\s+\(EXISTS\s+\(SELECT\s+1\s+FROM\s+pg_catalog\.pg_trigger)/i,_r=/^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*)\s+ON\s+/i;function Ir(t){return gt(t).map(e=>e.schema===void 0?b(e.name):M(e.schema,e.name))}var Dr=/\bnextval\('((?:[^']|'')+)'(?:::regclass)?\)/gi;function gt(t){if(t===void 0)return[];let e=[];for(let n of t.matchAll(Dr)){let s=n[1].replace(/''/g,"'"),r='("(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)',o=new RegExp(`^(?:${r}\\.)?${r}$`).exec(s);if(!o)continue;let i=a=>a.startsWith('"')?a.slice(1,-1).replace(/""/g,'"'):a.toLowerCase();e.push(o[1]===void 0?{name:i(o[2])}:{schema:i(o[1]),name:i(o[2])})}return e}function ss(t){let e=t.sql.trim().replace(/;\s*$/,""),n=_r.exec(e);return!n||e.includes(";")?void 0:n[2].replace(/^"|"$/g,"")}function Cr(t){let e=t.trim().replace(/;\s*$/,""),n=_r.exec(e);if(!n||e.includes(";"))return;let s=n[2].replace(/^"|"$/g,""),r=e.slice(n[0].length);return{unique:!!n[1],create:`CREATE ${n[1]?"UNIQUE ":""}INDEX CONCURRENTLY IF NOT EXISTS ${b(s)} ON ${r}`,qualified:(o,i)=>{let a=/^\s*(?:ONLY\s+)?("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*)(?:\.("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*))?/i.exec(r),l=d=>d.replace(/^"|"$/g,""),c=a?.[2]?l(a[1]):o.table?.split(".")[0]??i.tables.find(d=>d.name===l(a?.[1]??""))?.schema??"public";return M(c,s)}}}import{randomBytes as Gi}from"node:crypto";var Ye=(t,e)=>JSON.stringify(t)===JSON.stringify(e),Ln=t=>new Map(t.map(e=>[e.name,e])),cn=t=>({type:t.type,nullable:t.nullable,default:t.default??null,identity:t.identity??null,generated:t.generated??null});function Mi(t,e){if(t.name===e)return t;let{renamedFrom:n,...s}=t;return{...s,name:e}}function rs(t,e,n){let s=he(n),r=[],o=[...t.unmanaged],i=new Map(t.schema.tables.map(g=>[F(g),g])),a=new Map(e.schema.tables.map(g=>[F(g),g])),l=new Set,c=[],d=new Set(s.raw.map(g=>ss(g)).filter(g=>g!==void 0));for(let g of s.tables){let p=i.get(F(g))??(g.renamedFrom!==void 0?i.get(`${g.schema}.${g.renamedFrom}`):void 0);if(!p)continue;l.add(F(p));let S=a.get(F(g));if(!S)throw new Error(`palgres: the shadow database has no ${F(g)}: the schema did not make it`);let R=Ln(S.columns),E=p.columns.map(A=>{let O=g.columns.find(N=>N.name===A.name)??g.columns.find(N=>N.renamedFrom===A.name&&!p.columns.some(_=>_.name===N.name)),L=O&&R.get(O.name);return O&&L&&Ye(cn(A),cn(L))?Mi(O,A.name):A}),$=(A,O,L)=>{let N=Ln(O),_=Ln(L);return A.map(y=>{let k=N.get(y.name),D=_.get(y.name);return D&&k&&Ye(y,k)?D:y})};c.push({schema:p.schema,name:p.name,...g.ignored!==void 0?{ignored:g.ignored}:{},...g.renamedFrom!==void 0&&g.name===p.name?{renamedFrom:g.renamedFrom}:{},columns:E,primaryKey:p.primaryKey,uniques:$(p.uniques,S.uniques,g.uniques),indexes:$(p.indexes.filter(A=>!d.has(A.name)),S.indexes,g.indexes),checks:$(p.checks,S.checks,g.checks),foreignKeys:$(p.foreignKeys.filter(A=>i.has(`${A.refSchema}.${A.refTable}`)&&s.tables.some(O=>O.schema===A.refSchema&&O.name===A.refTable||O.schema===A.refSchema&&O.renamedFrom===A.refTable)?!0:(o.push(`foreign key ${F(p)}.${A.name} references ${A.refSchema}.${A.refTable}, outside the schema \u2014 kept as it is; drop it when its target goes`),!1)),S.foreignKeys,g.foreignKeys),rls:p.rls,policies:$(p.policies,S.policies,g.policies)})}for(let g of i.keys())l.has(g)||o.push(`table ${g}: not in the schema \u2014 kept as it is`);for(let g of t.forced)l.has(g)||o.push(`table ${g}: row-level security FORCEd on its owner \u2014 kept as it is`);let w=new Map(t.schema.tables.flatMap(g=>g.indexes.map(p=>[`${g.schema}.${p.name}`,{t:g,i:p}]))),u=new Map(e.schema.tables.flatMap(g=>g.indexes.map(p=>[`${g.schema}.${p.name}`,{t:g,i:p}]))),m=[],f=!0;for(let[g,p]of e.objects){let S=t.objects.get(g);S===void 0?f=!1:S!==p&&r.push(`${g} is not what the schema's raw SQL makes: drop it, and the migration makes it as the schema says`)}for(let g of s.raw){let p=ss(g);if(p===void 0){f&&m.push(g);continue}let S=[...u.keys()].find($=>$.endsWith(`.${p}`)),R=S&&u.get(S),E=S&&w.get(S);if(!R||!E){let $=[...e.objects.keys()].find(A=>A.startsWith("index ")&&A.endsWith(`.${p}`));$!==void 0&&t.objects.get($)===e.objects.get($)&&m.push(g);continue}Ye(E.i,R.i)&&F(E.t)===F(R.t)?m.push(g):r.push(`index ${S} is not what the schema's raw unit ${g.name} makes: drop it, and the migration makes it as the schema says`)}let h=[];for(let g of s.enums){let p=t.schema.enums.find(S=>S.schema===g.schema&&S.name===g.name);p&&h.push(Ye(p.values,g.values)?g:p)}let T=s.extensions.filter(g=>t.schema.extensions.includes(g));return{schema:he({tables:c,enums:h,extensions:T,raw:m}),unforce:t.forced.filter(g=>l.has(g)),refusals:r,unmanaged:o}}function Fi(t,e){let n=[],s=new Map(t.schema.tables.map(r=>[F(r),r]));for(let r of e.schema.tables){let o=F(r),i=s.get(o);if(!i){n.push(`table ${o} is missing`);continue}for(let d of r.columns)i.columns.some(w=>w.name===d.name)||n.push(`column ${o}.${d.name} is missing`);for(let d of i.columns)r.columns.some(w=>w.name===d.name)||n.push(`column ${o}.${d.name}: not declared`);for(let d of r.columns){let w=i.columns.find(u=>u.name===d.name);w&&!Ye(cn(w),cn(d))&&n.push(`column ${o}.${d.name}: ${JSON.stringify(cn(w))}, declared ${JSON.stringify(cn(d))}`)}Ye(i.primaryKey,r.primaryKey)||n.push(`table ${o}: primary key (${i.primaryKey.join(", ")}), declared (${r.primaryKey.join(", ")})`),i.rls!==r.rls&&n.push(`table ${o}: row-level security ${i.rls?"on":"off"}, declared ${r.rls?"on":"off"}`);let a={uniques:"unique",indexes:"index",checks:"check",foreignKeys:"foreign key",policies:"policy"},l=(d,w)=>e.schema.tables.some(u=>u.schema===d&&u.name===w),c={...i,foreignKeys:i.foreignKeys.filter(d=>l(d.refSchema,d.refTable))};for(let[d,w]of Object.entries(a)){let u=Ln(c[d]),m=Ln(r[d]);for(let[f,h]of m)Ye(u.get(f),h)||n.push(`${w} ${o}.${f}: ${u.has(f)?`${JSON.stringify(u.get(f))}, declared ${JSON.stringify(h)}`:"missing"}`);for(let f of u.keys())m.has(f)||n.push(`${w} ${o}.${f}: not declared`)}}return n}function We(t,e){let n=t.join("_").replace(/[^A-Za-z0-9_]/g,"_").replace(/^([^A-Za-z_])/,"_$1");if(Buffer.byteLength(n)>55){let r=0;for(let o of t.join("."))r=Math.imul(r,31)+o.charCodeAt(0)>>>0;n=`${n.slice(0,46)}_${r.toString(36)}`}let s=n;for(let r=2;e.has(s);r++)s=`${n}_${r}`;return e.add(s),s}function qi(t){let e="$palgres$";for(let n=1;t.includes(e);n++)e=`$palgres${n}$`;return e}var os=(t,e)=>{let n=qi(e+t);return`DO ${n} BEGIN IF NOT (${t}) THEN ${e}; END IF; END ${n}`};async function Pr(t,e,n,s){let r=new Set,o=[],i=[],a=[],l=await t(`SELECT n.nspname AS schema, t.typname AS name, pg_catalog.format_type(t.typbasetype, t.typtypmod) AS base,
|
|
176
|
+
END $undo$`),B.push(...Wt(e.schema));for(let w of e.tables)if(!n?.tables.some(O=>O.schema===w.schema&&O.name===w.name)&&this.from.tables.some(O=>O.schema===w.schema&&O.name===w.name))for(let O of Ut)B.push(`DROP TRIGGER IF EXISTS ${N(O)} ON ${D(w.schema,w.name)}`);for(let w of e.tables)this.from.tables.some(O=>O.schema===w.schema&&O.name===w.name)&&B.push(`DROP TRIGGER IF EXISTS ${N(Hn)} ON ${D(w.schema,w.name)}`);for(let w of n?.nests??[])B.push(`CREATE OR REPLACE TRIGGER ${N(Hn)} AFTER INSERT OR UPDATE ON ${D(w.schema,w.table)} FOR EACH ROW EXECUTE FUNCTION ${N(Qs)}.nest_rows(${w.args.map(v).join(", ")})`)}B.length>0&&this.accessUndo.push({kind:"tx",sql:B,why:"the access schema, as it was"})}policyRoles(e,n){let s=new Set;for(let r of e.to){if(r.startsWith("role:")&&r.length>5){s.add(N(r.slice(5)));continue}let o=Ve[r];if(!o){this.refuse(`policy ${n}.${e.name} is for role ${r}`,`a policy is for ${Object.keys(Ve).join(", ")}`);continue}s.add(o==="public"?"PUBLIC":N(this.input.roles[o]))}return[...s].join(", ")}policySql(e,n,s){let r=ke(s),o=`CREATE POLICY ${N(n.name)} ON ${e} AS ${n.restrictive?"RESTRICTIVE":"PERMISSIVE"} FOR ${n.for.toUpperCase()} TO ${this.policyRoles(n,e)}`;return n.using!==void 0&&(o+=` USING (${me(n.using,r)})`),n.withCheck!==void 0&&(o+=` WITH CHECK (${me(n.withCheck,r)})`),o}policies(e,n,s){let{to:r}=e,o=this.inNewNames(e.from),i=F(r),a=m=>JSON.stringify([m.for,[...new Set(m.to.map(f=>Ve[f]??f))].sort(),m.using??null,m.withCheck??null,m.restrictive??!1]),l=m=>e.from.policies.find(f=>f.name===m),c=m=>m!==void 0&&(_e(m.using)||_e(m.withCheck)),d=r.policies.some(c)||o.policies.some(c),y=ke(e.cols).size>0,u=m=>({...m,...m.using!==void 0?{using:me(m.using,ke(e.cols))}:{},...m.withCheck!==void 0?{withCheck:me(m.withCheck,ke(e.cols))}:{}});for(let m of r.policies){let f=o.policies.find(g=>g.name===m.name);if(c(m)||c(f)){this.accessPolicies.push({q:n,table:r,to:m,...f?{from:l(m.name)}:{}});continue}if(!(f&&a(f)===a(m))){if(d){y&&this.refuse(`policy ${i}.${m.name} changes on a table whose policies read the access schema, in a deploy that renames its columns`,"rename the columns in one deploy, and change the policy in the next"),this.accessPolicies.push({q:n,table:r,to:u(m),...f?{from:l(m.name)}:{}});continue}this.readsOthersRenamed(r,m,i)||(this.changes.push(`policy ${i}.${m.name}${f?" changes":""}`),s.undo.push(`DROP POLICY IF EXISTS ${N(m.name)} ON ${n}`),f&&(s.tx.push(`DROP POLICY IF EXISTS ${N(m.name)} ON ${n}`),s.undo.push(this.policySql(n,l(m.name),Dr(e.from)))),s.tx.push(this.policySql(n,m,e.cols)))}}for(let m of o.policies)if(!r.policies.some(f=>f.name===m.name)){if(c(m)||d){this.accessPolicies.push({q:n,table:r,from:l(m.name)});continue}this.changes.push(`policy ${i}.${m.name} goes`),s.tx.push(`DROP POLICY IF EXISTS ${N(m.name)} ON ${n}`),s.undo.push(this.policySql(n,l(m.name),Dr(e.from)))}}readsOthersRenamed(e,n,s){let r=`${n.using??""} ${n.withCheck??""}`;for(let o of this.to.tables){if(o===e)continue;let i=this.from.tables.find(l=>l.schema===o.schema&&l.name===(o.renamedFrom??o.name));if(!i)continue;let a=[...o.name!==i.name&&Oe(r,o.name)?[`${o.schema}.${o.name}`]:[],...Oe(r,o.name)?o.columns.filter(l=>l.renamedFrom!==void 0&&l.renamedFrom!==l.name&&i.columns.some(c=>c.name===l.renamedFrom)&&Oe(r,l.name)).map(l=>`${o.schema}.${o.name}.${l.name}`):[]];if(a.length>0)return this.refuse(`policy ${s}.${n.name} reads ${a.join(", ")}, renamed in this deploy`,"Postgres has the new name only from complete on: rename in this deploy, change the policy in the next"),!0}return!1}rawUnitsBefore(){let e=!0;for(let n of this.to.raw){if(!n.before)continue;let s=this.from.raw.find(r=>r.name===n.name);if(!(s&&s.sql.trim()===n.sql.trim())){if(s&&/^\s*CREATE\s+(?:DOMAIN|TYPE|SEQUENCE)\b/i.test(s.sql)){this.refuse(`raw ${n.name} changes`,"Postgres cannot drop a domain or a type a column uses, and a sequence made again starts over: say the change as an ALTER (ALTER DOMAIN \u2026 ADD CONSTRAINT \u2026 NOT VALID, ALTER TYPE, ALTER SEQUENCE) in a unit of its own, or make a new one and move the columns to it");continue}this.changes.push(`raw ${n.name}${s?" changes":""}`),e&&this.creates.push("SET LOCAL check_function_bodies = off"),e=!1,this.creates.push(...this.rawApply(n,s)),!s&&n.drop!==void 0&&this.undoCreates.push(n.drop),s&&this.undoRawsBack.push(...this.rawApply(s,n))}}}rawApply(e,n){return!n||/^\s*CREATE\s+OR\s+REPLACE\b/i.test(e.sql)||n.drop===void 0?[e.sql]:[n.drop,e.sql]}rawUnits(){let e=this.to.raw.filter(c=>!c.before),n=c=>/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\b/i.test(c),s=this.namesAtComplete,r=this.dropsColumnsAtComplete,o=e.findIndex(c=>{let d=this.from.raw.find(y=>y.name===c.name);return n(c.sql)?r&&d!==void 0?!0:d===void 0?s:d.sql.trim()!==c.sql.trim():!1}),i=new Set,a=new Set,l=null;if(o>=0){let c=e.slice(o),d=u=>n(u)||/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i.test(u)||Zt.test(u),y=[];for(let u of[...this.from.raw].reverse()){if(u.before||u.drop===void 0)continue;let m=c.some(g=>g.name===u.name),f=!this.to.raw.some(g=>g.name===u.name);(m&&d(u.sql)||f&&n(u.sql))&&y.push(u.drop),f&&n(u.sql)&&a.add(u.name)}for(let u of c){let m=this.from.raw.find(f=>f.name===u.name);(!m||m.sql.trim()!==u.sql.trim())&&this.changes.push(`raw ${u.name}${m?" changes":""}`),i.add(u.name)}if(s){this.viewsAtComplete={drops:y,creates:c.map(u=>u.sql)};for(let u of c){let m=this.changes.findIndex(f=>f===`raw ${u.name}`||f===`raw ${u.name} changes`);m>=0&&(this.changes[m]+=" (at complete)")}}else{l={kind:"tx",sql:["SET LOCAL check_function_bodies = off",...y,...c.map(u=>u.sql)],why:`raw ${c[0].name} and what follows it, made again`};for(let u of[...c].reverse())u.drop!==void 0&&this.undoRawsGone.push(u.drop);for(let u of this.from.raw){if(u.before||u.drop===void 0)continue;let m=c.some(g=>g.name===u.name),f=!this.to.raw.some(g=>g.name===u.name);(m&&d(u.sql)||f&&n(u.sql))&&this.undoRawsBack.push(u.sql)}}}for(let c of this.to.raw){if(c.before||(l!==null&&c.name===e[o].name&&this.raws.push(l),i.has(c.name)))continue;let d=this.from.raw.find(u=>u.name===c.name),y=Fr(c.sql);if(!(d&&d.sql.trim()===c.sql.trim())){if(d&&y){this.refuse(`raw index ${c.name} changes under its name`,"an index is built CONCURRENTLY next to the one serving, so under a name of its own: give the new one its own name (the old one goes at complete)");continue}if(this.changes.push(`raw ${c.name}${d?" changes":""}`),y)this.raws.push({kind:"statement",sql:y.create,why:`raw ${c.name}`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${y.qualified(c,this.to)}`,why:`raw ${c.name}`});else{if(c.drop===void 0&&(Zt.test(c.sql)||n(c.sql))){this.refuse(`raw ${c.name} has no drop`,"a rollback could not take it back, and the old version would write and read past it: give it its drop (raw(name, up, { drop }))");continue}this.raws.push({kind:"tx",sql:["SET LOCAL check_function_bodies = off",...this.rawApply(c,d)],why:`raw ${c.name}`}),c.drop!==void 0&&this.undoRawsGone.unshift(c.drop),d&&this.undoRawsBack.push(...c.drop!==void 0?[d.sql]:this.rawApply(d,c))}}}for(let c of[...this.from.raw].reverse()){if(this.to.raw.some(y=>y.name===c.name))continue;if(a.has(c.name)){this.changes.push(`raw ${c.name} goes (with the views made again)`);continue}let d=Fr(c.sql);if(!d){if(c.drop===void 0){this.refuse(`raw ${c.name} is gone from the schema`,"Palgres does not know how to take back what its SQL made: keep it, or give the unit its drop (raw(name, up, { drop })) and remove it in the deploy after that");continue}this.changes.push(`raw ${c.name} goes (at complete)`),Zt.test(c.sql)?this.completeUnitDrops.push(c.drop):this.completeIndexes.push({kind:"tx",sql:[c.drop],why:`raw ${c.name}`});continue}this.changes.push(`raw index ${c.name} goes (at complete)`),this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${d.qualified(c,this.from)}`,why:`raw ${c.name}`})}}views(){let{anon:e,authenticated:n,service:s}=this.input.roles,r=[e,n,s].map(N).join(", "),o=[];for(let i of[...new Set(this.layout.tables.map(a=>a.schema))]){let a=N(Ie(this.n,i));o.push(`DROP SCHEMA IF EXISTS ${a} CASCADE`,`CREATE SCHEMA ${a}`,`GRANT USAGE ON SCHEMA ${a} TO ${r}`)}for(let i of this.layout.tables){let a=i.columns.map(c=>c.physical===c.name?N(c.name):`${N(c.physical)} AS ${N(c.name)}`).join(", "),l=D(Ie(this.n,i.schema),i.name);o.push(`CREATE VIEW ${l} WITH (security_invoker = true) AS SELECT ${a} FROM ${D(i.schema,i.physical)}`),o.push(`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${l} TO ${r}`)}return o}dropViews(e,n){let s=[...new Set(n.tables.map(r=>r.schema))];return s.length>0?s.map(r=>`DROP SCHEMA IF EXISTS ${N(Ie(e,r))} CASCADE`):["SELECT 1"]}keyOf(e){let n=this.where(e);return e.primaryKey.map(s=>{let r=this.matches.get(F(e))?.retyped.get(s);return r?r.from.name:n.cols.get(s)??s})}};function Dr(t){return new Map(t.columns.map(e=>[e.name,e.name]))}function ke(t){return new Map([...t].filter(([e,n])=>e!==n))}function cn(t,e,n){return e?[`ALTER TABLE ${t} ENABLE ROW LEVEL SECURITY`]:n?[`ALTER TABLE ${t} DISABLE ROW LEVEL SECURITY`]:[]}function pt(t){return JSON.stringify([t.columns,t.refSchema,t.refTable,t.refColumns,t.onDelete,t.onUpdate,t.match??"simple"])}function ft(t){return JSON.stringify([t.keys,t.unique,t.where??null,t.method??"btree",t.include??[]])}var Zt=/^\s*(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:TRIGGER|CONSTRAINT\s+TRIGGER|RULE)\b|DO\s+\$\w*\$\s+BEGIN\s+IF\s+NOT\s+\(EXISTS\s+\(SELECT\s+1\s+FROM\s+pg_catalog\.pg_trigger)/i,Ur=/^\s*CREATE\s+(UNIQUE\s+)?INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*)\s+ON\s+/i;function Pr(t){return gt(t).map(e=>e.schema===void 0?N(e.name):D(e.schema,e.name))}var Br=/\bnextval\('((?:[^']|'')+)'(?:::regclass)?\)/gi;function gt(t){if(t===void 0)return[];let e=[];for(let n of t.matchAll(Br)){let s=n[1].replace(/''/g,"'"),r='("(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)',o=new RegExp(`^(?:${r}\\.)?${r}$`).exec(s);if(!o)continue;let i=a=>a.startsWith('"')?a.slice(1,-1).replace(/""/g,'"'):a.toLowerCase();e.push(o[1]===void 0?{name:i(o[2])}:{schema:i(o[1]),name:i(o[2])})}return e}function os(t){let e=t.sql.trim().replace(/;\s*$/,""),n=Ur.exec(e);return!n||e.includes(";")?void 0:n[2].replace(/^"|"$/g,"")}function Fr(t){let e=t.trim().replace(/;\s*$/,""),n=Ur.exec(e);if(!n||e.includes(";"))return;let s=n[2].replace(/^"|"$/g,""),r=e.slice(n[0].length);return{unique:!!n[1],create:`CREATE ${n[1]?"UNIQUE ":""}INDEX CONCURRENTLY IF NOT EXISTS ${N(s)} ON ${r}`,qualified:(o,i)=>{let a=/^\s*(?:ONLY\s+)?("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*)(?:\.("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*))?/i.exec(r),l=d=>d.replace(/^"|"$/g,""),c=a?.[2]?l(a[1]):o.table?.split(".")[0]??i.tables.find(d=>d.name===l(a?.[1]??""))?.schema??"public";return D(c,s)}}}import{randomBytes as Qi}from"node:crypto";var Je=(t,e)=>JSON.stringify(t)===JSON.stringify(e),In=t=>new Map(t.map(e=>[e.name,e])),un=t=>({type:t.type,nullable:t.nullable,default:t.default??null,identity:t.identity??null,generated:t.generated??null});function ji(t,e){if(t.name===e)return t;let{renamedFrom:n,...s}=t;return{...s,name:e}}function is(t,e,n){let s=ge(n),r=[],o=[...t.unmanaged],i=new Map(t.schema.tables.map(h=>[F(h),h])),a=new Map(e.schema.tables.map(h=>[F(h),h])),l=new Set,c=[],d=new Set(s.raw.map(h=>os(h)).filter(h=>h!==void 0));for(let h of s.tables){let p=i.get(F(h))??(h.renamedFrom!==void 0?i.get(`${h.schema}.${h.renamedFrom}`):void 0);if(!p)continue;l.add(F(p));let S=a.get(F(h));if(!S)throw new Error(`palgres: the shadow database has no ${F(h)}: the schema did not make it`);let b=In(S.columns),E=p.columns.map(A=>{let I=h.columns.find(k=>k.name===A.name)??h.columns.find(k=>k.renamedFrom===A.name&&!p.columns.some(x=>x.name===k.name)),L=I&&b.get(I.name);return I&&L&&Je(un(A),un(L))?ji(I,A.name):A}),$=(A,I,L)=>{let k=In(I),x=In(L);return A.map(R=>{let _=k.get(R.name),P=x.get(R.name);return P&&_&&Je(R,_)?P:R})};c.push({schema:p.schema,name:p.name,...h.ignored!==void 0?{ignored:h.ignored}:{},...h.renamedFrom!==void 0&&h.name===p.name?{renamedFrom:h.renamedFrom}:{},columns:E,primaryKey:p.primaryKey,uniques:$(p.uniques,S.uniques,h.uniques),indexes:$(p.indexes.filter(A=>!d.has(A.name)),S.indexes,h.indexes),checks:$(p.checks,S.checks,h.checks),foreignKeys:$(p.foreignKeys.filter(A=>i.has(`${A.refSchema}.${A.refTable}`)&&s.tables.some(I=>I.schema===A.refSchema&&I.name===A.refTable||I.schema===A.refSchema&&I.renamedFrom===A.refTable)?!0:(o.push(`foreign key ${F(p)}.${A.name} references ${A.refSchema}.${A.refTable}, outside the schema \u2014 kept as it is; drop it when its target goes`),!1)),S.foreignKeys,h.foreignKeys),rls:p.rls,policies:$(p.policies,S.policies,h.policies)})}for(let h of i.keys())l.has(h)||o.push(`table ${h}: not in the schema \u2014 kept as it is`);for(let h of t.forced)l.has(h)||o.push(`table ${h}: row-level security FORCEd on its owner \u2014 kept as it is`);let y=new Map(t.schema.tables.flatMap(h=>h.indexes.map(p=>[`${h.schema}.${p.name}`,{t:h,i:p}]))),u=new Map(e.schema.tables.flatMap(h=>h.indexes.map(p=>[`${h.schema}.${p.name}`,{t:h,i:p}]))),m=[],f=!0;for(let[h,p]of e.objects){let S=t.objects.get(h);S===void 0?f=!1:S!==p&&r.push(`${h} is not what the schema's raw SQL makes: drop it, and the migration makes it as the schema says`)}for(let h of s.raw){let p=os(h);if(p===void 0){f&&m.push(h);continue}let S=[...u.keys()].find($=>$.endsWith(`.${p}`)),b=S&&u.get(S),E=S&&y.get(S);if(!b||!E){let $=[...e.objects.keys()].find(A=>A.startsWith("index ")&&A.endsWith(`.${p}`));$!==void 0&&t.objects.get($)===e.objects.get($)&&m.push(h);continue}Je(E.i,b.i)&&F(E.t)===F(b.t)?m.push(h):r.push(`index ${S} is not what the schema's raw unit ${h.name} makes: drop it, and the migration makes it as the schema says`)}let g=[];for(let h of s.enums){let p=t.schema.enums.find(S=>S.schema===h.schema&&S.name===h.name);p&&g.push(Je(p.values,h.values)?h:p)}let T=s.extensions.filter(h=>t.schema.extensions.includes(h));return{schema:ge({tables:c,enums:g,extensions:T,raw:m}),unforce:t.forced.filter(h=>l.has(h)),refusals:r,unmanaged:o}}function Hi(t,e){let n=[],s=new Map(t.schema.tables.map(r=>[F(r),r]));for(let r of e.schema.tables){let o=F(r),i=s.get(o);if(!i){n.push(`table ${o} is missing`);continue}for(let d of r.columns)i.columns.some(y=>y.name===d.name)||n.push(`column ${o}.${d.name} is missing`);for(let d of i.columns)r.columns.some(y=>y.name===d.name)||n.push(`column ${o}.${d.name}: not declared`);for(let d of r.columns){let y=i.columns.find(u=>u.name===d.name);y&&!Je(un(y),un(d))&&n.push(`column ${o}.${d.name}: ${JSON.stringify(un(y))}, declared ${JSON.stringify(un(d))}`)}Je(i.primaryKey,r.primaryKey)||n.push(`table ${o}: primary key (${i.primaryKey.join(", ")}), declared (${r.primaryKey.join(", ")})`),i.rls!==r.rls&&n.push(`table ${o}: row-level security ${i.rls?"on":"off"}, declared ${r.rls?"on":"off"}`);let a={uniques:"unique",indexes:"index",checks:"check",foreignKeys:"foreign key",policies:"policy"},l=(d,y)=>e.schema.tables.some(u=>u.schema===d&&u.name===y),c={...i,foreignKeys:i.foreignKeys.filter(d=>l(d.refSchema,d.refTable))};for(let[d,y]of Object.entries(a)){let u=In(c[d]),m=In(r[d]);for(let[f,g]of m)Je(u.get(f),g)||n.push(`${y} ${o}.${f}: ${u.has(f)?`${JSON.stringify(u.get(f))}, declared ${JSON.stringify(g)}`:"missing"}`);for(let f of u.keys())m.has(f)||n.push(`${y} ${o}.${f}: not declared`)}}return n}function We(t,e){let n=t.join("_").replace(/[^A-Za-z0-9_]/g,"_").replace(/^([^A-Za-z_])/,"_$1");if(Buffer.byteLength(n)>55){let r=0;for(let o of t.join("."))r=Math.imul(r,31)+o.charCodeAt(0)>>>0;n=`${n.slice(0,46)}_${r.toString(36)}`}let s=n;for(let r=2;e.has(s);r++)s=`${n}_${r}`;return e.add(s),s}function Ki(t){let e="$palgres$";for(let n=1;t.includes(e);n++)e=`$palgres${n}$`;return e}var as=(t,e)=>{let n=Ki(e+t);return`DO ${n} BEGIN IF NOT (${t}) THEN ${e}; END IF; END ${n}`};async function Wr(t,e,n,s){let r=new Set,o=[],i=[],a=[],l=await t(`SELECT n.nspname AS schema, t.typname AS name, pg_catalog.format_type(t.typbasetype, t.typtypmod) AS base,
|
|
177
177
|
CASE WHEN t.typcollation <> 0 AND t.typcollation <> (SELECT b.typcollation FROM pg_catalog.pg_type b WHERE b.oid = t.typbasetype) THEN (SELECT format('%I.%I', cn.nspname, co.collname) FROM pg_catalog.pg_collation co JOIN pg_catalog.pg_namespace cn ON cn.oid = co.collnamespace WHERE co.oid = t.typcollation) END AS collation,
|
|
178
178
|
pg_catalog.pg_get_expr(t.typdefaultbin, 0) AS default, t.typnotnull AS notnull,
|
|
179
179
|
(SELECT json_agg(json_build_object('name', c.conname, 'def', pg_catalog.pg_get_constraintdef(c.oid, true)) ORDER BY c.conname) FROM pg_catalog.pg_constraint c WHERE c.contypid = t.oid AND c.contype = 'c') AS checks
|
|
180
180
|
FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
181
181
|
WHERE n.nspname IN ${e} AND t.typtype = 'd'
|
|
182
182
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = t.oid AND d.deptype = 'e')
|
|
183
|
-
ORDER BY t.oid`);for(let p of l){let S=[`AS ${p.base}`];p.collation!==null&&S.push(`COLLATE ${p.collation}`),p.default!==null&&S.push(`DEFAULT ${p.default}`),p.notnull&&S.push("NOT NULL");for(let E of p.checks??[])S.push(`CONSTRAINT ${
|
|
183
|
+
ORDER BY t.oid`);for(let p of l){let S=[`AS ${p.base}`];p.collation!==null&&S.push(`COLLATE ${p.collation}`),p.default!==null&&S.push(`DEFAULT ${p.default}`),p.notnull&&S.push("NOT NULL");for(let E of p.checks??[])S.push(`CONSTRAINT ${N(E.name)} ${E.def}`);let b=`domain ${p.schema}.${p.name}`;s.set(b,S.join(" ")),o.push({schema:p.schema,key:b,listed:`type ${p.schema}.${p.name} (`,kind:"domain",name:We(["domain",p.schema==="public"?p.name:`${p.schema}_${p.name}`],r),before:!0,create:as(`EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = ${ze(p.schema)} AND t.typname = ${ze(p.name)})`,`CREATE DOMAIN ${D(p.schema,p.name)} ${S.join(" ")}`),drop:`DROP DOMAIN IF EXISTS ${D(p.schema,p.name)}`})}let c=await t(`SELECT n.nspname AS schema, t.typname AS name,
|
|
184
184
|
(SELECT json_agg(json_build_object('name', a.attname, 'type', pg_catalog.format_type(a.atttypid, a.atttypmod)) ORDER BY a.attnum) FROM pg_catalog.pg_attribute a WHERE a.attrelid = t.typrelid AND a.attnum > 0 AND NOT a.attisdropped) AS attrs,
|
|
185
185
|
EXISTS (SELECT 1 FROM pg_catalog.pg_attribute a JOIN pg_catalog.pg_type at ON at.oid = a.atttypid JOIN pg_catalog.pg_class rc ON rc.oid = at.typrelid WHERE a.attrelid = t.typrelid AND rc.relkind <> 'c') AS "usesTable"
|
|
186
186
|
FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace JOIN pg_catalog.pg_class c ON c.oid = t.typrelid
|
|
187
187
|
WHERE n.nspname IN ${e} AND t.typtype = 'c' AND c.relkind = 'c'
|
|
188
188
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = t.oid AND d.deptype = 'e')
|
|
189
|
-
ORDER BY t.oid`);for(let p of c){let S=(p.attrs??[]).map($=>`${
|
|
189
|
+
ORDER BY t.oid`);for(let p of c){let S=(p.attrs??[]).map($=>`${N($.name)} ${$.type}`).join(", "),b=`type ${p.schema}.${p.name}`;s.set(b,S);let E={schema:p.schema,key:b,listed:`type ${p.schema}.${p.name} (`,kind:"type",name:We(["type",p.schema==="public"?p.name:`${p.schema}_${p.name}`],r),before:!p.usesTable,create:as(`EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = ${ze(p.schema)} AND t.typname = ${ze(p.name)})`,`CREATE TYPE ${D(p.schema,p.name)} AS (${S})`),drop:`DROP TYPE IF EXISTS ${D(p.schema,p.name)}`};(E.before?o:i).push(E)}let d=await t(`SELECT n.nspname AS schema, c.relname AS name, pg_catalog.format_type(s.seqtypid, NULL) AS type, s.seqstart::text AS start, s.seqincrement::text AS increment,
|
|
190
190
|
s.seqmin::text AS min, s.seqmax::text AS max, s.seqcache::text AS cache, s.seqcycle AS cycle
|
|
191
191
|
FROM pg_catalog.pg_sequence s JOIN pg_catalog.pg_class c ON c.oid = s.seqrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
192
192
|
WHERE n.nspname IN ${e}
|
|
193
193
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('a', 'i', 'e'))
|
|
194
|
-
ORDER BY c.oid`);for(let p of d){let S=`AS ${p.type} INCREMENT BY ${p.increment} MINVALUE ${p.min} MAXVALUE ${p.max} START WITH ${p.start} CACHE ${p.cache}${p.cycle?" CYCLE":" NO CYCLE"}`,
|
|
194
|
+
ORDER BY c.oid`);for(let p of d){let S=`AS ${p.type} INCREMENT BY ${p.increment} MINVALUE ${p.min} MAXVALUE ${p.max} START WITH ${p.start} CACHE ${p.cache}${p.cycle?" CYCLE":" NO CYCLE"}`,b=`sequence ${p.schema}.${p.name}`;s.set(b,S),o.push({schema:p.schema,key:b,listed:`sequence ${p.schema}.${p.name} (`,kind:"sequence",name:We(["sequence",p.schema==="public"?p.name:`${p.schema}_${p.name}`],r),before:!0,create:`CREATE SEQUENCE IF NOT EXISTS ${D(p.schema,p.name)} ${S}`,drop:`DROP SEQUENCE IF EXISTS ${D(p.schema,p.name)}`})}let y=await t(`SELECT n.nspname AS schema, p.proname AS name, pg_catalog.pg_get_function_identity_arguments(p.oid) AS args, p.prokind AS kind, pg_catalog.pg_get_functiondef(p.oid) AS def,
|
|
195
195
|
EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_class rc ON rc.oid = t.typrelid
|
|
196
196
|
WHERE rc.relkind <> 'c' AND (t.oid = p.prorettype OR t.oid = ANY (p.proargtypes::oid[]) OR t.oid = ANY (coalesce(p.proallargtypes, '{}'::oid[]))
|
|
197
197
|
OR t.typarray = p.prorettype)) AS "usesRelation"
|
|
198
198
|
FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
|
|
199
199
|
WHERE n.nspname IN ${e} AND p.proname NOT LIKE '\\_palgres\\_%' AND p.prokind IN ('f', 'p', 'w')
|
|
200
200
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
|
|
201
|
-
ORDER BY p.oid`);for(let p of
|
|
201
|
+
ORDER BY p.oid`);for(let p of y){let S=`function ${p.schema}.${p.name}(${p.args})`,b={schema:p.schema,key:S,listed:`function ${p.schema}.${p.name}(${p.args})`,kind:"function",name:We(["fn",p.schema==="public"?p.name:`${p.schema}_${p.name}`,p.args===""?"":p.args.replace(/\s+/g,"_")].filter(Boolean),r),before:!p.usesRelation,create:p.def.trim(),drop:`DROP ${p.kind==="p"?"PROCEDURE":"FUNCTION"} IF EXISTS ${D(p.schema,p.name)}(${p.args})`};(b.before?o:a).push(b)}let u=await t(`SELECT n.nspname AS schema, p.proname AS name, pg_catalog.pg_get_function_identity_arguments(p.oid) AS args,
|
|
202
202
|
a.aggtransfn::regprocedure::text AS sfunc, pg_catalog.format_type(a.aggtranstype, NULL) AS stype,
|
|
203
203
|
CASE WHEN a.aggfinalfn <> 0 THEN a.aggfinalfn::regproc::text END AS final, CASE WHEN a.aggcombinefn <> 0 THEN a.aggcombinefn::regproc::text END AS combine,
|
|
204
204
|
a.agginitval AS init, CASE WHEN a.aggsortop <> 0 THEN a.aggsortop::regoperator::text END AS sortop, p.proparallel AS parallel,
|
|
@@ -206,65 +206,65 @@ END $palgres$`)}else o.complete.push(`ALTER TABLE ${n} DROP COLUMN ${f}`);o.comp
|
|
|
206
206
|
FROM pg_catalog.pg_aggregate a JOIN pg_catalog.pg_proc p ON p.oid = a.aggfnoid JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
|
|
207
207
|
WHERE n.nspname IN ${e} AND a.aggkind = 'n' AND a.aggmtransfn = 0
|
|
208
208
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
|
|
209
|
-
ORDER BY p.oid`);for(let p of u){let S=p.sfunc.replace(/\(.*\)$/,""),
|
|
209
|
+
ORDER BY p.oid`);for(let p of u){let S=p.sfunc.replace(/\(.*\)$/,""),b=[`SFUNC = ${S}`,`STYPE = ${p.stype}`];p.final!==null&&b.push(`FINALFUNC = ${p.final}`),p.combine!==null&&b.push(`COMBINEFUNC = ${p.combine}`),p.init!==null&&b.push(`INITCOND = ${ze(p.init)}`),p.sortop!==null&&b.push(`SORTOP = ${p.sortop.replace(/\(.*\)$/,"")}`),b.push(`PARALLEL = ${p.parallel==="s"?"SAFE":p.parallel==="r"?"RESTRICTED":"UNSAFE"}`);let E=`aggregate ${p.schema}.${p.name}(${p.args})`;s.set(E,b.join(", "));let $={schema:p.schema,key:E,listed:`function ${p.schema}.${p.name}(${p.args})`,kind:"function",name:We(["agg",p.schema==="public"?p.name:`${p.schema}_${p.name}`,p.args.replace(/\s+/g,"_")].filter(Boolean),r),before:!p.usesRelation&&!a.some(A=>A.key.startsWith(`function ${S}(`)||p.final!==null&&A.key.startsWith(`function ${p.final}(`)),create:`CREATE OR REPLACE AGGREGATE ${D(p.schema,p.name)}(${p.args}) (${b.join(", ")})`,drop:`DROP AGGREGATE IF EXISTS ${D(p.schema,p.name)}(${p.args})`};($.before?o:a).push($)}let m=await t(`SELECT c.oid::int AS oid, n.nspname AS schema, c.relname AS name, c.relkind AS kind, pg_catalog.pg_get_viewdef(c.oid, true) AS def, c.reloptions AS options,
|
|
210
210
|
(SELECT array_agg(DISTINCT format('%s.%s', rn.nspname, rc.relname)) FROM pg_catalog.pg_rewrite r JOIN pg_catalog.pg_depend d ON d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = r.oid
|
|
211
211
|
JOIN pg_catalog.pg_class rc ON rc.oid = d.refobjid JOIN pg_catalog.pg_namespace rn ON rn.oid = rc.relnamespace
|
|
212
212
|
WHERE r.ev_class = c.oid AND d.refclassid = 'pg_catalog.pg_class'::regclass AND d.refobjid <> c.oid) AS reads
|
|
213
213
|
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
214
214
|
WHERE n.nspname IN ${e} AND c.relkind IN ('v', 'm')
|
|
215
215
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = c.oid AND d.deptype = 'e')
|
|
216
|
-
ORDER BY c.oid`),f=new Set(n),
|
|
216
|
+
ORDER BY c.oid`),f=new Set(n),g=[...m];for(let p=!0;p&&g.length>0;){p=!1;for(let S=0;S<g.length;S++){let b=g[S];if(!(b.reads??[]).every(L=>f.has(L)))continue;g.splice(S--,1),p=!0,f.add(`${b.schema}.${b.name}`);let E=b.def.trim().replace(/;$/,""),$=b.options?.length?` WITH (${b.options.join(", ")})`:"",A=b.kind==="m",I=`${A?"materialized view":"view"} ${b.schema}.${b.name}`;s.set(I,JSON.stringify({options:b.options??[],query:E})),i.push({schema:b.schema,key:I,listed:`${A?"materialized view":"view"} ${b.schema}.${b.name}`,kind:A?"materialized view":"view",name:We([A?"matview":"view",b.schema==="public"?b.name:`${b.schema}_${b.name}`],r),before:!1,create:A?`CREATE MATERIALIZED VIEW IF NOT EXISTS ${D(b.schema,b.name)}${$} AS ${E}`:`CREATE OR REPLACE VIEW ${D(b.schema,b.name)}${$} AS ${E}`,drop:`DROP ${A?"MATERIALIZED VIEW":"VIEW"} IF EXISTS ${D(b.schema,b.name)}`})}}i.push(...a);let T=await t(`SELECT n.nspname AS schema, c.relname AS table, ic.relname AS name, pg_catalog.pg_get_indexdef(i.indexrelid) AS def
|
|
217
217
|
FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class ic ON ic.oid = i.indexrelid JOIN pg_catalog.pg_class c ON c.oid = i.indrelid
|
|
218
218
|
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace JOIN pg_catalog.pg_am am ON am.oid = ic.relam
|
|
219
219
|
WHERE n.nspname IN ${e} AND i.indisvalid AND ic.relname NOT LIKE '\\_palgres\\_search\\_%' AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_constraint k WHERE k.conindid = i.indexrelid AND k.contype IN ('p', 'u', 'x'))
|
|
220
|
-
AND (c.relkind = 'm' OR (c.relkind = 'r' AND (am.amname NOT IN ('btree', 'hash', 'gin', 'gist', 'brin') OR NOT ${
|
|
221
|
-
ORDER BY ic.oid`);for(let p of T){if(!f.has(`${p.schema}.${p.table}`))continue;let S=`index ${p.schema}.${p.name}`;s.set(S,p.def),i.push({schema:p.schema,key:S,listed:`index ${p.schema}.${p.name} `,kind:"index",name:We(["index",p.schema==="public"?p.name:`${p.schema}_${p.name}`],r),before:!1,create:p.def.replace(/^CREATE (UNIQUE )?INDEX /,"CREATE $1INDEX IF NOT EXISTS "),drop:`DROP INDEX IF EXISTS ${
|
|
220
|
+
AND (c.relkind = 'm' OR (c.relkind = 'r' AND (am.amname NOT IN ('btree', 'hash', 'gin', 'gist', 'brin') OR NOT ${Kn("ic")})))
|
|
221
|
+
ORDER BY ic.oid`);for(let p of T){if(!f.has(`${p.schema}.${p.table}`))continue;let S=`index ${p.schema}.${p.name}`;s.set(S,p.def),i.push({schema:p.schema,key:S,listed:`index ${p.schema}.${p.name} `,kind:"index",name:We(["index",p.schema==="public"?p.name:`${p.schema}_${p.name}`],r),before:!1,create:p.def.replace(/^CREATE (UNIQUE )?INDEX /,"CREATE $1INDEX IF NOT EXISTS "),drop:`DROP INDEX IF EXISTS ${D(p.schema,p.name)}`})}let h=await t(`SELECT n.nspname AS schema, c.relname AS table, t.tgname AS name, pg_catalog.pg_get_triggerdef(t.oid, true) AS def, t.tgconstraint <> 0 AS constraint
|
|
222
222
|
FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
223
223
|
WHERE n.nspname IN ${e} AND NOT t.tgisinternal AND t.tgname NOT LIKE '\\_palgres\\_%'
|
|
224
|
-
ORDER BY t.oid`);for(let p of
|
|
224
|
+
ORDER BY t.oid`);for(let p of h){if(!f.has(`${p.schema}.${p.table}`))continue;let S=`trigger ${p.schema}.${p.table}.${p.name}`;i.push({schema:p.schema,key:S,listed:`trigger ${p.name} on ${p.schema}.${p.table} `,kind:"trigger",name:We(["trigger",p.schema==="public"?p.table:`${p.schema}_${p.table}`,p.name],r),before:!1,create:p.constraint?as(`EXISTS (SELECT 1 FROM pg_catalog.pg_trigger x WHERE x.tgrelid = ${ze(`${N(p.schema)}.${N(p.table)}`)}::regclass AND x.tgname = ${ze(p.name)})`,p.def):p.def.replace(/^CREATE TRIGGER /,"CREATE OR REPLACE TRIGGER "),drop:`DROP TRIGGER IF EXISTS ${N(p.name)} ON ${D(p.schema,p.table)}`})}return[...o,...i]}var ze=t=>`'${t.replace(/'/g,"''")}'`;var Et={a:"no action",r:"restrict",c:"cascade",n:"set null",d:"set default"},Gi={ALL:"all",SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"};async function yt(t,e,n){let s=await t.reserve();try{return await Xi(async r=>await s.unsafe(r),e,n)}finally{s.release()}}async function Xi(t,e,n){let s=[],r=[],o=new Map,i=`(${e.map(v).join(", ")})`;await t("BEGIN READ ONLY");try{await t("SET LOCAL search_path = ''");let a=await t(`SELECT c.oid::int AS oid, n.nspname AS schema, c.relname AS name, c.relkind AS kind, c.relrowsecurity AS rls, c.relforcerowsecurity AS forced, c.relispartition AS partition,
|
|
225
225
|
EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid = c.oid OR i.inhparent = c.oid) AS inherits,
|
|
226
226
|
(SELECT e.extname FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_extension e ON e.oid = d.refobjid
|
|
227
227
|
WHERE d.classid = 'pg_catalog.pg_class'::regclass AND d.objid = c.oid AND d.refclassid = 'pg_catalog.pg_extension'::regclass AND d.deptype = 'e' LIMIT 1) AS extension
|
|
228
228
|
FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
229
229
|
WHERE n.nspname IN ${i} AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
230
|
-
ORDER BY n.nspname, c.relname`),l=[],c=new Map;for(let
|
|
230
|
+
ORDER BY n.nspname, c.relname`),l=[],c=new Map;for(let h of a){let p=`${h.schema}.${h.name}`;if(h.extension!==null){s.push(`table ${p}: the extension ${h.extension}'s own \u2014 left to it`);continue}if(h.kind==="v"||h.kind==="m"||h.kind==="f"){s.push(`${h.kind==="v"?"view":h.kind==="m"?"materialized view":"foreign table"} ${p}`);continue}if(h.kind==="p"||h.partition||h.inherits){s.push(`table ${p}: partitioned or inherited \u2014 Palgres does not migrate it`);continue}h.forced&&r.push(p);let S={schema:h.schema,name:h.name,columns:[],primaryKey:[],uniques:[],indexes:[],checks:[],foreignKeys:[],rls:h.rls,policies:[]};l.push(S),c.set(h.oid,S)}let d=[...c.keys()];if(d.length>0){let h=`(${d.join(", ")})`,p=await t(`SELECT a.attrelid::int AS rel, a.attname AS name, pg_catalog.format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS notnull,
|
|
231
231
|
pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS default, a.attidentity AS identity, a.attgenerated AS generated,
|
|
232
232
|
CASE WHEN a.attcollation <> t.typcollation THEN co.collname END AS collation
|
|
233
233
|
FROM pg_catalog.pg_attribute a
|
|
234
234
|
JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
|
|
235
235
|
LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
|
|
236
236
|
LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation
|
|
237
|
-
WHERE a.attrelid IN ${
|
|
238
|
-
ORDER BY a.attrelid, a.attnum`);for(let
|
|
237
|
+
WHERE a.attrelid IN ${h} AND a.attnum > 0 AND NOT a.attisdropped
|
|
238
|
+
ORDER BY a.attrelid, a.attnum`);for(let R of p){let _=c.get(R.rel),P=`${_.schema}.${_.name}.${R.name}`,B=R.generated==="s"||R.generated==="v"?{expr:R.default??"",stored:R.generated==="s"}:void 0;R.collation!==null&&s.push(`column ${P}: collation ${R.collation} \u2014 kept, the model does not say it`);let w={name:R.name,type:ae(R.type),nullable:!R.notnull};B?w.generated=B:R.identity==="a"||R.identity==="d"?w.identity=R.identity==="a"?"always":"by default":R.default!==null&&(w.default=R.default),_.columns.push(w)}let S=await t(`SELECT c.conrelid::int AS rel, c.conname AS name, c.contype AS type, pg_catalog.pg_get_constraintdef(c.oid, true) AS def,
|
|
239
239
|
(SELECT array_agg(a.attname ORDER BY k.i) FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, i) JOIN pg_catalog.pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum) AS cols,
|
|
240
240
|
c.confrelid::int AS refrel,
|
|
241
241
|
(SELECT array_agg(a.attname ORDER BY k.i) FROM unnest(c.confkey) WITH ORDINALITY AS k(attnum, i) JOIN pg_catalog.pg_attribute a ON a.attrelid = c.confrelid AND a.attnum = k.attnum) AS refcols,
|
|
242
242
|
c.confdeltype AS del, c.confupdtype AS upd, c.confmatchtype AS match, c.condeferrable AS deferrable, c.condeferred AS deferred, i.relname AS index
|
|
243
243
|
FROM pg_catalog.pg_constraint c LEFT JOIN pg_catalog.pg_class i ON i.oid = c.conindid
|
|
244
|
-
WHERE c.conrelid IN ${
|
|
245
|
-
ORDER BY c.conrelid, c.conname`),
|
|
244
|
+
WHERE c.conrelid IN ${h}
|
|
245
|
+
ORDER BY c.conrelid, c.conname`),b=new Map,E=[...new Set(S.filter(R=>R.refrel).map(R=>R.refrel))];if(E.length>0)for(let R of await t(`SELECT c.oid::int AS oid, n.nspname AS schema, c.relname AS name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid IN (${E.join(", ")})`))b.set(R.oid,{schema:R.schema,name:R.name});let $=new Set;for(let R of S){let _=c.get(R.rel),P=`${_.schema}.${_.name}`;R.index&&(R.type==="p"||R.type==="u"||R.type==="x")&&$.add(`${_.schema}.${R.index}`);let B=R.type==="f"&&!R.deferred&&en(Et[R.del],Et[R.upd]);if(R.deferrable&&R.type!=="n"&&!B){s.push(`constraint ${P}.${R.name}: deferrable \u2014 kept as it is, the model does not say it`);continue}switch(R.type){case"p":_.primaryKey=R.cols??[];break;case"u":if(/NULLS NOT DISTINCT/i.test(R.def)){s.push(`constraint ${P}.${R.name}: UNIQUE NULLS NOT DISTINCT \u2014 kept as it is`);break}_.uniques.push({name:R.name,columns:R.cols??[]});break;case"c":{let w=/^CHECK \((.*)\)( NOT VALID)?$/s.exec(R.def);if(!w||/\bNO INHERIT\b/.test(R.def)){s.push(`constraint ${P}.${R.name}: ${R.def} \u2014 kept as it is`);break}_.checks.push({name:R.name,expr:w[1]});break}case"f":{let w=R.refrel===null?void 0:b.get(R.refrel);if(!w||R.match==="p"){s.push(`constraint ${P}.${R.name}: ${R.def} \u2014 kept as it is`);break}let O={name:R.name,columns:R.cols??[],refSchema:w.schema,refTable:w.name,refColumns:R.refcols??[],onDelete:Et[R.del],onUpdate:Et[R.upd]};R.match==="f"&&(O.match="full"),R.deferrable&&(O.deferrable=!0),_.foreignKeys.push(O);break}case"n":break;default:s.push(`constraint ${P}.${R.name}: ${R.def} \u2014 kept as it is`)}}let A=await t(`SELECT i.indrelid::int AS rel, n.nspname AS schema, c.relname AS name, i.indisunique AS unique, am.amname AS method, i.indnkeyatts::int AS keyatts,
|
|
246
246
|
-- indkey and indoption count from 0, and Bun cannot read an array that does not start at 1 ("[0:1]={\u2026}").
|
|
247
247
|
ARRAY(SELECT k::int FROM unnest(i.indkey::int2[]) AS k) AS attnums, ARRAY(SELECT o::int FROM unnest(i.indoption::int2[]) AS o) AS options,
|
|
248
248
|
ARRAY(SELECT pg_catalog.pg_get_indexdef(i.indexrelid, k, true) FROM generate_series(1, i.indnatts) AS k) AS exprs,
|
|
249
249
|
pg_catalog.pg_get_expr(i.indpred, i.indrelid, true) AS where,
|
|
250
|
-
${
|
|
250
|
+
${Kn("c")} AS "defaultOps",
|
|
251
251
|
i.indisvalid AS valid
|
|
252
252
|
FROM pg_catalog.pg_index i JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace JOIN pg_catalog.pg_am am ON am.oid = c.relam
|
|
253
|
-
WHERE i.indrelid IN ${
|
|
254
|
-
ORDER BY i.indrelid, c.relname`);for(let
|
|
255
|
-
FROM pg_catalog.pg_policies WHERE schemaname IN ${i} ORDER BY schemaname, tablename, policyname`),L=new Map([[n.anon,"anon"],[n.authenticated,"authenticated"],[n.service,"service_role"],["public","public"]]);for(let
|
|
256
|
-
WHERE t.tgrelid IN ${
|
|
253
|
+
WHERE i.indrelid IN ${h} AND c.relname NOT LIKE '\\_palgres\\_search\\_%'
|
|
254
|
+
ORDER BY i.indrelid, c.relname`);for(let R of A){let _=c.get(R.rel);if($.has(`${R.schema}.${R.name}`))continue;let P=`${_.schema}.${_.name}`;if(!R.valid){s.push(`index ${R.schema}.${R.name}: INVALID (a build that did not finish) \u2014 drop it, or Palgres would take it for built`);continue}if(!["btree","hash","gin","gist","brin"].includes(R.method)||!R.defaultOps){s.push(`index ${R.schema}.${R.name} of ${P}: ${R.method}${R.defaultOps?"":" with an operator class, a collation, NULLS NOT DISTINCT or storage options of its own"} \u2014 kept as it is`);continue}let B=[];for(let O=0;O<R.keyatts;O++){let C=(R.options[O]&1)!==0,W=(R.options[O]&2)!==0,M={};C&&(M.desc=!0),W!==C&&(M.nulls=W?"first":"last");let j=R.attnums[O];B.push(j===0?{expr:R.exprs[O],...M}:{column:R.exprs[O].replace(/^"(.*)"$/,"$1").replace(/""/g,'"'),...M})}let w={name:R.name,keys:B,unique:R.unique};R.method!=="btree"&&(w.method=R.method),R.where!==null&&(w.where=R.where),R.keyatts<R.attnums.length&&(w.include=R.exprs.slice(R.keyatts).map(O=>O.replace(/^"(.*)"$/,"$1").replace(/""/g,'"'))),_.indexes.push(w)}let I=await t(`SELECT schemaname AS schema, tablename AS table, policyname AS name, permissive, roles::text[] AS roles, cmd, qual, with_check AS check
|
|
255
|
+
FROM pg_catalog.pg_policies WHERE schemaname IN ${i} ORDER BY schemaname, tablename, policyname`),L=new Map([[n.anon,"anon"],[n.authenticated,"authenticated"],[n.service,"service_role"],["public","public"]]);for(let R of I){let _=l.find(w=>w.schema===R.schema&&w.name===R.table);if(!_)continue;let P=R.roles.map(w=>L.get(w)??`role:${w}`),B={name:R.name,for:Gi[R.cmd],to:P};R.qual!==null&&(B.using=R.qual),R.check!==null&&(B.withCheck=R.check),R.permissive==="RESTRICTIVE"&&(B.restrictive=!0),_.policies.push(B)}let k=await t(`SELECT format('%s.%s', n.nspname, c.relname) AS table, t.tgname AS name, pg_catalog.pg_get_triggerdef(t.oid, true) AS def FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON c.oid = t.tgrelid JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
256
|
+
WHERE t.tgrelid IN ${h} AND NOT t.tgisinternal AND t.tgname NOT LIKE '\\_palgres\\_%' ORDER BY 1, 2`);for(let R of k)s.push(`trigger ${R.name} on ${R.table} \u2014 kept as it is`),o.set(`trigger ${R.table}.${R.name}`,R.def);let x=await t(`SELECT format('%s.%s', schemaname, tablename) AS table, rulename AS name FROM pg_catalog.pg_rules WHERE schemaname IN ${i} ORDER BY 1, 2`);for(let R of x)s.push(`rule ${R.name} on ${R.table} \u2014 kept as it is`)}let y=await t(`SELECT n.nspname AS schema, t.typname AS name, t.typtype AS kind,
|
|
257
257
|
CASE WHEN t.typtype = 'e' THEN ARRAY(SELECT e.enumlabel::text FROM pg_catalog.pg_enum e WHERE e.enumtypid = t.oid ORDER BY e.enumsortorder) END AS values
|
|
258
258
|
FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
|
|
259
259
|
WHERE n.nspname IN ${i} AND t.typtype IN ('e', 'd', 'c', 'r', 'm')
|
|
260
260
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class c WHERE c.reltype = t.oid)
|
|
261
|
-
ORDER BY 1, 2`),u=[];for(let
|
|
261
|
+
ORDER BY 1, 2`),u=[];for(let h of y)h.kind==="e"?u.push({schema:h.schema,name:h.name,values:h.values??[]}):s.push(`type ${h.schema}.${h.name} (${h.kind==="d"?"domain":h.kind==="c"?"composite":"range"}) \u2014 kept as it is`);let m=await t(`SELECT format('%s.%s(%s)', n.nspname, p.proname, pg_catalog.pg_get_function_identity_arguments(p.oid)) AS name, CASE WHEN p.prokind IN ('f', 'p', 'w') THEN pg_catalog.pg_get_functiondef(p.oid) ELSE '' END AS def FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
|
|
262
262
|
WHERE n.nspname IN ${i} AND p.proname NOT LIKE '\\_palgres\\_%'
|
|
263
263
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
|
|
264
|
-
ORDER BY 1`);for(let
|
|
264
|
+
ORDER BY 1`);for(let h of m)s.push(`function ${h.name} \u2014 kept as it is`),o.set(`function ${h.name}`,h.def);let f=await t(`SELECT format('%s.%s', n.nspname, c.relname) AS name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
|
|
265
265
|
WHERE n.nspname IN ${i} AND c.relkind = 'S'
|
|
266
266
|
AND NOT EXISTS (SELECT 1 FROM pg_catalog.pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('a', 'i'))
|
|
267
|
-
ORDER BY 1`);for(let
|
|
267
|
+
ORDER BY 1`);for(let h of f)s.push(`sequence ${h.name} (owned by no column) \u2014 kept as it is`);let g=(await t("SELECT extname AS name FROM pg_catalog.pg_extension WHERE extname <> 'plpgsql' ORDER BY 1")).map(h=>h.name),T=await Wr(t,i,new Set(l.map(h=>`${h.schema}.${h.name}`)),o);return{schema:{tables:l,enums:u,extensions:g,raw:[]},unmanaged:s,forced:r,objects:o,units:T}}finally{await t("ROLLBACK")}}var qe={SHARE:1,"SHARE ROW EXCLUSIVE":2,"ACCESS EXCLUSIVE":3},Te=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`,we=String.raw`${Te}(?:\s*\.\s*${Te}){0,2}`,z=t=>new RegExp(t,"i");function Hr(t){let e={needs:[],made:[]};for(let n of t)for(let s of $t(n))Kr(s,e);return e}function jr(t){return t.startsWith('"')?t.slice(1,-1).replace(/""/g,'"'):t.toLowerCase()}var $e=t=>[...t.matchAll(new RegExp(Te,"g"))].map(e=>e[0]).join("."),Vi=z(String.raw`\b(?:ALTER\s+TABLE|DROP\s+TABLE|CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER|DROP\s+TRIGGER|(?:CREATE|ALTER|DROP)\s+POLICY|CREATE\s+(?:UNIQUE\s+)?INDEX|DROP\s+INDEX|CREATE\s+(?:OR\s+REPLACE\s+)?RULE|DROP\s+RULE|TRUNCATE|CREATE\s+(?:UNLOGGED\s+|TEMP(?:ORARY)?\s+)?TABLE|DROP\s+VIEW|CREATE\s+OR\s+REPLACE\s+VIEW|ALTER\s+VIEW)\b`);function Kr(t,e){let n;if(n=/^DO\s+(?:LANGUAGE\s+\w+\s+)?(\$[A-Za-z_0-9]*\$)([\s\S]*?)\1/i.exec(t)){for(let s of $t(n[2],!0)){let r=Vi.exec(s);r&&Kr(s.slice(r.index),e)}return}if(n=z(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(${we})\s*\*?\s*([\s\S]*)$`).exec(t))return Ji($e(n[1]),n[2],e);if(n=z(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]*?)(?:\s+(?:CASCADE|RESTRICT))?\s*$`).exec(t)){for(let s of wt(n[1]))e.needs.push({of:"relation",name:s,mode:"ACCESS EXCLUSIVE"},{of:"table",name:s});return}if(n=z(String.raw`^DROP\s+VIEW\s+(?:IF\s+EXISTS\s+)?([\s\S]*?)(?:\s+(?:CASCADE|RESTRICT))?\s*$`).exec(t)){for(let s of wt(n[1]))e.needs.push({of:"view",name:s});return}if(n=z(String.raw`^(?:CREATE\s+OR\s+REPLACE\s+(?:(?:TEMP|TEMPORARY)\s+)?(?:RECURSIVE\s+)?VIEW|ALTER\s+VIEW\s+(?:IF\s+EXISTS\s+)?)\s*(${we})`).exec(t)){e.needs.push({of:"view",name:$e(n[1])});return}if(n=z(String.raw`^CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+${Te}\s+[\s\S]*?\bON\s+(?:ONLY\s+)?(${we})`).exec(t)){e.needs.push({of:"relation",name:$e(n[1]),mode:"SHARE ROW EXCLUSIVE"});return}if(n=z(String.raw`^(?:DROP\s+TRIGGER|(?:CREATE|ALTER|DROP)\s+POLICY|DROP\s+RULE)\s+(?:IF\s+EXISTS\s+)?${Te}\s+ON\s+(${we})`).exec(t)){e.needs.push({of:"relation",name:$e(n[1]),mode:"ACCESS EXCLUSIVE"});return}if(n=z(String.raw`^CREATE\s+(?:OR\s+REPLACE\s+)?RULE\s+${Te}\s+AS\s+ON\s+\w+\s+TO\s+(${we})`).exec(t)){e.needs.push({of:"relation",name:$e(n[1]),mode:"ACCESS EXCLUSIVE"});return}if(n=z(String.raw`^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!CONCURRENTLY\b)(?:IF\s+NOT\s+EXISTS\s+)?(?:${Te}\s+)?ON\s+(?:ONLY\s+)?(${we})`).exec(t)){e.needs.push({of:"relation",name:$e(n[1]),mode:"SHARE"});return}if(n=z(String.raw`^DROP\s+INDEX\s+(?!CONCURRENTLY\b)(?:IF\s+EXISTS\s+)?([\s\S]*?)(?:\s+(?:CASCADE|RESTRICT))?\s*$`).exec(t)){for(let s of wt(n[1]))e.needs.push({of:"index",name:s});return}if(n=z(String.raw`^TRUNCATE\s+(?:TABLE\s+)?([\s\S]*?)(?:\s+(?:RESTART|CONTINUE|CASCADE|RESTRICT)\b[\s\S]*)?$`).exec(t)){for(let s of wt(n[1]))e.needs.push({of:"relation",name:s,mode:"ACCESS EXCLUSIVE"});return}if(n=z(String.raw`^CREATE\s+(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(${we})([\s\S]*)$`).exec(t)){e.made.push($e(n[1]));let s=z(String.raw`^\s*PARTITION\s+OF\s+(${we})`).exec(n[2]);s&&e.needs.push({of:"relation",name:$e(s[1]),mode:"ACCESS EXCLUSIVE"});for(let r of Gr(n[2]))e.needs.push({of:"relation",name:r,mode:"SHARE ROW EXCLUSIVE"})}}var Yi=[/^VALIDATE\s+CONSTRAINT\b/i,z(String.raw`^(?:ALTER\s+(?:COLUMN\s+)?${Te}\s+)?SET\s+STATISTICS\b`),z(String.raw`^(?:ALTER\s+(?:COLUMN\s+)?${Te}\s+)?(?:SET|RESET)\s*\(`),/^CLUSTER\s+ON\b/i,/^SET\s+WITHOUT\s+CLUSTER\b/i];function Ji(t,e,n){let s=null,r=[];for(let o of $t(e,!1,",")){let i,a="ACCESS EXCLUSIVE";z(String.raw`^ADD\s+(?:CONSTRAINT\s+${Te}\s+)?FOREIGN\s+KEY\b`).test(o)||/^(?:ENABLE|DISABLE)\s+(?:REPLICA\s+|ALWAYS\s+)?TRIGGER\b/i.test(o)?a="SHARE ROW EXCLUSIVE":Yi.some(l=>l.test(o))?a=null:(i=z(String.raw`^ATTACH\s+PARTITION\s+(${we})`).exec(o))?(a=null,r.push({of:"relation",name:$e(i[1]),mode:"ACCESS EXCLUSIVE"})):(i=z(String.raw`^DETACH\s+PARTITION\s+(${we})`).exec(o))?r.push({of:"relation",name:$e(i[1]),mode:"ACCESS EXCLUSIVE"}):(i=z(String.raw`^DROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?(${Te})`).exec(o))?r.push({of:"constraint",table:t,name:jr(i[1])}):(i=z(String.raw`^DROP\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?(${Te})`).exec(o))&&r.push({of:"column",table:t,name:jr(i[1])});for(let l of Gr(o))r.push({of:"relation",name:l,mode:"SHARE ROW EXCLUSIVE"});a!==null&&(s===null||qe[a]>qe[s])&&(s=a)}s!==null&&n.needs.push({of:"relation",name:t,mode:s}),n.needs.push(...r)}function Gr(t){return[...t.matchAll(new RegExp(String.raw`\bREFERENCES\s+(${we})`,"gi"))].map(e=>$e(e[1]))}function wt(t){return $t(t,!1,",").map(e=>z(String.raw`^(?:ONLY\s+)?(${we})\s*\*?$`).exec(e)?.[1]).filter(e=>e!==void 0).map($e)}async function Xr(t,e){if(e.length===0)return[];let n=e.map((l,c)=>l.of==="relation"?{i:c,of:l.of,rel:l.name,mode:l.mode}:l.of==="constraint"||l.of==="column"?{i:c,of:l.of,rel:l.table,name:l.name}:{i:c,of:l.of,rel:l.name}),s=await t(`WITH r AS (SELECT n.*, to_regclass(n.rel)::oid AS oid FROM jsonb_to_recordset(${v(JSON.stringify(n))}::jsonb) AS n(i int, "of" text, rel text, name text, mode text)),
|
|
268
268
|
got AS (
|
|
269
269
|
SELECT r.i, r.oid AS rel, r.mode FROM r WHERE r.of IN ('relation', 'view') AND r.oid IS NOT NULL
|
|
270
270
|
UNION ALL
|
|
@@ -285,18 +285,18 @@ END $palgres$`)}else o.complete.push(`ALTER TABLE ${n} DROP COLUMN ${f}`);o.comp
|
|
|
285
285
|
FROM got g JOIN pg_catalog.pg_class k ON k.oid = g.rel
|
|
286
286
|
WHERE k.relkind IN ('r', 'p', 'v')
|
|
287
287
|
AND (pg_catalog.pg_has_role(k.relowner, 'USAGE') OR pg_catalog.has_table_privilege(g.rel, 'UPDATE, DELETE, TRUNCATE, MAINTAIN'))
|
|
288
|
-
ORDER BY g.i`),r=new Map,o=new Map;for(let l of s){let c=String(l.oid),d=l.mode;if(l.kind==="v"){o.has(c)||o.set(c,{lock:{oid:c,name:String(l.name),mode:"ACCESS EXCLUSIVE"},reads:l.reads.map(String)});continue}let
|
|
288
|
+
ORDER BY g.i`),r=new Map,o=new Map;for(let l of s){let c=String(l.oid),d=l.mode;if(l.kind==="v"){o.has(c)||o.set(c,{lock:{oid:c,name:String(l.name),mode:"ACCESS EXCLUSIVE"},reads:l.reads.map(String)});continue}let y=r.get(c);y?qe[d]>qe[y.mode]&&(y.mode=d):r.set(c,{oid:c,name:String(l.name),mode:d})}let i=l=>r.get(l)?.mode==="ACCESS EXCLUSIVE";return[...[...o.values()].filter(l=>l.reads.length>0&&l.reads.every(i)).map(l=>l.lock),...r.values()]}async function Vr(t,e,n){if(e.length===0)return new Set;let s=e.map(o=>`(${v(o.oid)}::oid, ${v(o.mode)})`).join(", "),r=await t(`SELECT DISTINCT h.relation::text AS oid
|
|
289
289
|
FROM pg_catalog.pg_locks h JOIN (VALUES ${s}) AS want(rel, mode) ON want.rel = h.relation
|
|
290
290
|
JOIN pg_catalog.pg_locks w ON w.pid = h.pid AND NOT w.granted
|
|
291
291
|
WHERE h.locktype = 'relation' AND h.granted AND h.pid <> pg_backend_pid()
|
|
292
292
|
AND (want.mode = 'ACCESS EXCLUSIVE' OR h.mode NOT IN ('AccessShareLock', 'RowShareLock'))
|
|
293
|
-
AND w.waitstart < clock_timestamp() - make_interval(secs => ${Math.max(0,n)/1e3})`);return new Set(r.map(o=>String(o.oid)))}var
|
|
293
|
+
AND w.waitstart < clock_timestamp() - make_interval(secs => ${Math.max(0,n)/1e3})`);return new Set(r.map(o=>String(o.oid)))}var zi={ShareLock:"SHARE",ShareRowExclusiveLock:"SHARE ROW EXCLUSIVE",ExclusiveLock:"ACCESS EXCLUSIVE",AccessExclusiveLock:"ACCESS EXCLUSIVE"};async function Yr(t,e){let n=e.length===0?"":`AND l.relation NOT IN (SELECT o FROM unnest(ARRAY[${e.map(o=>`to_regclass(${v(o)})::oid`).join(", ")}]) AS o WHERE o IS NOT NULL)`,s=await t(`SELECT l.relation::text AS oid, l.relation::regclass::text AS name, l.mode
|
|
294
294
|
FROM pg_catalog.pg_locks l JOIN pg_catalog.pg_class c ON c.oid = l.relation
|
|
295
295
|
WHERE l.pid = pg_backend_pid() AND l.locktype = 'relation' AND l.granted AND c.relkind IN ('r', 'p')
|
|
296
|
-
AND l.mode IN ('ShareLock', 'ShareRowExclusiveLock', 'ExclusiveLock', 'AccessExclusiveLock') ${n}`),r=new Map;for(let o of s){let i=String(o.oid),a=
|
|
297
|
-
`;)i++;r+=" ";continue}if(l==="/"&&t[i+1]==="*"){let c=0;do t[i]==="/"&&t[i+1]==="*"?(c++,i+=2):t[i]==="*"&&t[i+1]==="/"?(c--,i+=2):i++;while(i<a&&c>0);r+=" ";continue}if(l==="'"){let c=/[Ee]/.test(t[i-1]??"")&&!/[A-Za-z0-9_$]/.test(t[i-2]??""),d=i+1;for(;d<a;)if(c&&t[d]==="\\")d+=2;else if(t[d]==="'"&&t[d+1]==="'")d+=2;else{if(t[d]==="'")break;d++}r+=e?`'${" ".repeat(Math.max(0,d-i-1))}'`:t.slice(i,d+1),i=d+1;continue}if(l==='"'){let c=i+1;for(;c<a&&!(t[c]==='"'&&t[c+1]!=='"');)c+=t[c]==='"'?2:1;r+=t.slice(i,c+1),i=c+1;continue}if(l==="$"&&!/[A-Za-z0-9_$]/.test(t[i-1]??"")){let c=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(t.slice(i));if(c){let d=t.indexOf(c[0],i+c[0].length),
|
|
296
|
+
AND l.mode IN ('ShareLock', 'ShareRowExclusiveLock', 'ExclusiveLock', 'AccessExclusiveLock') ${n}`),r=new Map;for(let o of s){let i=String(o.oid),a=zi[String(o.mode)],l=r.get(i);l?qe[a]>qe[l.mode]&&(l.mode=a):r.set(i,{oid:i,name:String(o.name),mode:a})}return[...r.values()]}function $t(t,e=!1,n=";"){let s=[],r="",o=0,i=0,a=t.length;for(;i<a;){let l=t[i];if(l==="-"&&t[i+1]==="-"){for(;i<a&&t[i]!==`
|
|
297
|
+
`;)i++;r+=" ";continue}if(l==="/"&&t[i+1]==="*"){let c=0;do t[i]==="/"&&t[i+1]==="*"?(c++,i+=2):t[i]==="*"&&t[i+1]==="/"?(c--,i+=2):i++;while(i<a&&c>0);r+=" ";continue}if(l==="'"){let c=/[Ee]/.test(t[i-1]??"")&&!/[A-Za-z0-9_$]/.test(t[i-2]??""),d=i+1;for(;d<a;)if(c&&t[d]==="\\")d+=2;else if(t[d]==="'"&&t[d+1]==="'")d+=2;else{if(t[d]==="'")break;d++}r+=e?`'${" ".repeat(Math.max(0,d-i-1))}'`:t.slice(i,d+1),i=d+1;continue}if(l==='"'){let c=i+1;for(;c<a&&!(t[c]==='"'&&t[c+1]!=='"');)c+=t[c]==='"'?2:1;r+=t.slice(i,c+1),i=c+1;continue}if(l==="$"&&!/[A-Za-z0-9_$]/.test(t[i-1]??"")){let c=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(t.slice(i));if(c){let d=t.indexOf(c[0],i+c[0].length),y=d<0?a:d+c[0].length;r+=t.slice(i,y),i=y;continue}}if(l==="("?o++:l===")"&&o--,l===n&&o===0){r.trim()&&s.push(r.trim()),r="",i++;continue}r+=l,i++}return r.trim()&&s.push(r.trim()),s}var Se=class extends Error{refusals;constructor(e){super(`palgres: the migration is refused:
|
|
298
298
|
- ${e.join(`
|
|
299
|
-
- `)}`),this.name="MigrationRefused",this.refusals=e}},Cn=class extends Error{from;to;openedBy;constructor(e,n,s=null){super(`palgres: the migration from version ${e??"none"} to ${n}${s?`, opened by ${s},`:""} is still open: complete it or roll it back first`),this.name="MigrationOpen",this.from=e,this.to=n,this.openedBy=s}},vn=class extends Error{version;constructor(e,n,s){super(`palgres: ${n} connection(s) of version ${e} are still open after ${s} ms`),this.name="VersionStillConnected",this.version=e}},
|
|
299
|
+
- `)}`),this.name="MigrationRefused",this.refusals=e}},Cn=class extends Error{from;to;openedBy;constructor(e,n,s=null){super(`palgres: the migration from version ${e??"none"} to ${n}${s?`, opened by ${s},`:""} is still open: complete it or roll it back first`),this.name="MigrationOpen",this.from=e,this.to=n,this.openedBy=s}},vn=class extends Error{version;constructor(e,n,s){super(`palgres: ${n} connection(s) of version ${e} are still open after ${s} ms`),this.name="VersionStillConnected",this.version=e}},ls=1e4,Jr=`CREATE OR REPLACE FUNCTION palgres.defer_keys(keys text[], deferred boolean) RETURNS void
|
|
300
300
|
LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $palgres$
|
|
301
301
|
DECLARE
|
|
302
302
|
named text;
|
|
@@ -307,26 +307,26 @@ BEGIN
|
|
|
307
307
|
IF named IS NOT NULL THEN
|
|
308
308
|
EXECUTE 'SET CONSTRAINTS ' || named || CASE WHEN deferred THEN ' DEFERRED' ELSE ' IMMEDIATE' END;
|
|
309
309
|
END IF;
|
|
310
|
-
END $palgres$`,
|
|
310
|
+
END $palgres$`,Ln=class extends Error{constructor(e,n){super(`palgres: ${e} was not had in the step's time`,{cause:n}),this.name="LockNotHad"}},dn=class extends Error{constructor(e,n){super(`palgres: rows of ${e} to fill were held by writers through ${n} passes`),this.name="RowsHeld"}},Zi=new Set(["55P03","40P01","40001","57014","25006"]);function ea(t){if(Ee(t)!==void 0)return!0;let e=t;for(let n=0;n<4&&typeof e=="object"&&e!==null;n++){if(e instanceof vn||e instanceof dn)return!0;let s=ce(e);if(s!==void 0)return Zi.has(s)||s.startsWith("53");e=e.cause}return!1}var mn={anon:"anon",authenticated:"authenticated",service:"service_role"},St=t=>`palgres:v${t}`,zr="palgres.migrate",cs=class t{pool;roles;openedBy;lockTimeoutMs;statementWaitMs;lockTimeoutFor(e){return e>=3?Math.max(this.lockTimeoutMs,1500):this.lockTimeoutMs}attempts;batchSize;disconnectTimeoutMs;log;shadow;fieldsSource;fields;constructor(e,n={}){this.fieldsSource=n.fields,this.pool=e,this.roles={...mn,...n.roles},this.lockTimeoutMs=n.lockTimeoutMs??500,this.statementWaitMs=n.statementWaitMs??6e5,this.attempts=n.attempts??10,this.batchSize=n.batchSize??1e3,this.disconnectTimeoutMs=n.disconnectTimeoutMs??6e4,this.log=n.log??(()=>{}),this.shadow=n.shadow,this.openedBy=n.openedBy??"deploy"}async status(){return this.session(async e=>{let n=await this.active(e),s=await this.open(e);return{active:n&&{n:n.n,digest:n.digest,state:"active"},open:s&&{from:s.from_n,to:s.to_n,phase:s.phase,opened_by:s.opened_by}}},!1)}async plan(e){Qr(e);let n=Xe(e),s=async(r,o)=>{let i;try{i=await this.adopt(r,e)}catch(c){if(!(c instanceof Se))throw c;return{from:null,to:1,changes:[],refusals:c.refusals,start:[],complete:[],rollback:[],layout:{tables:[]}}}let a=o?[]:await this.authRefusals(r);if(!i){let c=await this.planFrom(r,null,e);return{...c,refusals:[...a,...c.refusals]}}if(i.version.digest===n)return{from:null,to:i.version.n,changes:[],refusals:a,start:[],complete:[],rollback:[],layout:i.layout,adoption:i.adoption};let l=await this.planFrom(r,i.version,e);return{...l,refusals:[...a,...l.refusals],adoption:i.adoption}};return this.session(async r=>{let o=await this.active(r);return o?this.planFrom(r,o,e):s(r,!0)},!1,r=>s(r,!1))}async start(e){Qr(e);let n=Xe(e);return this.session(async s=>{let r=await this.open(s);if(r){if((await this.version(s,r.to_n))?.digest!==n)throw new Cn(r.from_n,r.to_n,r.opened_by);if(r.phase==="started")return{state:"resumed",from:r.from_n,to:r.to_n,changes:r.plan.changes,completed:!1};if(r.phase!=="starting")throw new Cn(r.from_n,r.to_n);return this.log(`palgres: resuming the start of version ${r.to_n}`),await this.runStart(s,r),{state:"resumed",from:r.from_n,to:r.to_n,changes:r.plan.changes,completed:!1}}let o=await this.active(s);if(o?.digest===n)return{state:"in-sync",version:o.n};let i=o?null:await this.adopt(s,e),a=async()=>{s.ledger===!1&&(await this.ownAuth(s),await this.ensure(s),s.ledger=!0)};if(i){if(i.version.digest===n)return await a(),await i.record(),{state:"adopted",version:i.version.n,adoption:i.adoption};o=i.version}let l=i?.adoption,c=await this.planFrom(s,o,e);if(c.refusals.length>0)throw new Se(c.refusals);await this.cipherFor(c),await a(),await i?.record(),await this.tx(s,["ALTER TABLE palgres.migration ADD COLUMN IF NOT EXISTS opened_by text",Jr,`INSERT INTO palgres.versions (n, digest, schema, layout, state, direct) VALUES (${c.to}, ${v(n)}, ${v(JSON.stringify(Vs(e)))}::jsonb, ${v(JSON.stringify(c.layout))}::jsonb, 'starting', ${eo(c.layout)})`,`INSERT INTO palgres.migration (from_n, to_n, plan, phase, opened_by) VALUES (${c.from??"NULL"}, ${c.to}, ${v(JSON.stringify(c))}::jsonb, 'starting', ${v(this.openedBy)})`]),this.log(`palgres: version ${c.from??"none"} \u2192 ${c.to}:
|
|
311
311
|
${c.changes.join(`
|
|
312
|
-
`)||"(no change but the views)"}`);let d={from_n:c.from,to_n:c.to,plan:c,done:{},phase:"starting",opened_by:this.openedBy};return await this.runStart(s,d),c.from===null?(await this.runComplete(s,{...d,phase:"started"}),{state:"started",from:null,to:c.to,changes:c.changes,completed:!0}):{state:"started",from:c.from,to:c.to,changes:c.changes,completed:!1,...l?{adoption:l}:{}}})}async complete(){return this.session(async e=>{let n=await this.open(e);if(!n)return{state:"none"};if(n.phase==="starting"||n.phase==="rolling_back")throw new Error(`palgres: version ${n.to_n} is ${n.phase==="starting"?"still starting: run start again to finish it":"being rolled back: run rollback again"}`);await this.cipherFor(n.plan),n.from_n!==null&&await this.waitGone(e,n.from_n),await this.runComplete(e,n);let s=await this.kept(e,n.plan),r=await this.unconverted(e,n.plan);return s.length+r.length===0?{state:"completed",version:n.to_n}:(s.length>0&&this.log(`palgres: kept, holding what version ${n.from_n} wrote while version ${n.to_n} rolled out \u2014 outside the schema now, and no longer migrated: ${s.join("; ")}. Drop them yourself once their data may go.`),r.length>0&&this.log(`palgres: kept, the values a type change did not convert \u2014 outside the schema now, the new column NULL in their rows (and not NOT NULL while one is): ${r.join("; ")}. Write those rows' values yourself, then drop the old column.`),{state:"completed",version:n.to_n,kept:[...s,...r]})})}async unconverted(e,n){let s=[];for(let r of n.guarded?.retyped??[]){let o=M(r.schema,r.table);if((await e.query(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = to_regclass(${x(o)}) AND attname = ${x(r.kept)} AND NOT attisdropped) AS there`))[0]?.there!==!0)continue;let a=`FROM ${o} WHERE ${b(r.column)} IS NULL AND ${b(r.kept)} IS NOT NULL`,l=r.key.length===0?"ctid::text":r.key.length===1?`${b(r.key[0])}::text`:`ROW(${r.key.map(b).join(", ")})::text`,[{n:c}]=await e.query(`SELECT count(*)::int AS n ${a}`),d=(await e.query(`SELECT ${l} AS k ${a} ORDER BY ${r.key.length===0?"ctid":r.key.map(b).join(", ")} LIMIT 10`)).map(u=>String(u.k)),w=r.key.length===0?"ctid":r.key.join(", ");s.push(`column ${r.schema}.${r.table}.${r.kept}: the values of ${r.column} that did not become ${r.type}, in ${Number(c)} row(s) \u2014 ${w} ${d.join(", ")}${Number(c)>d.length?", \u2026":""}`)}return s}async kept(e,n){let s=[];for(let[r,o]of n.guarded?.tables??[])(await e.query(`SELECT to_regclass(${x(M(r,o))}) IS NOT NULL AS there`))[0]?.there===!0&&s.push(`table ${r}.${o}`);for(let[r,o,i]of n.guarded?.columns??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = to_regclass(${x(M(r,o))}) AND attname = ${x(i)} AND NOT attisdropped) AS there`))[0]?.there===!0&&s.push(`column ${r}.${o}.${i}`);return s}async rollback(){return this.session(async e=>{let n=await this.open(e);if(!n)return{state:"none"};if(n.phase==="completing")throw new Error(`palgres: version ${n.to_n} is completing: what the old version used is going; run complete again`);return await this.cipherFor(n.plan),await this.waitGone(e,n.to_n),n.phase!=="rolling_back"&&(await this.tx(e,["UPDATE palgres.migration SET phase = 'rolling_back', updated_at = now()"]),n.phase="rolling_back"),await this.runSteps(e,n,"rollback",[`UPDATE palgres.versions SET state = 'abandoned', retired_at = now() WHERE n = ${n.to_n}`,"DELETE FROM palgres.migration"]),this.log(`palgres: version ${n.to_n} rolled back; ${n.from_n??"no version"} serves`),{state:"rolled-back",version:n.from_n}})}async runStart(e,n){await this.runSteps(e,n,"start",[`UPDATE palgres.versions SET state = 'active', ready_at = now() WHERE n = ${n.to_n}`,"UPDATE palgres.migration SET phase = 'started', updated_at = now()"])}async runComplete(e,n){n.phase!=="completing"&&(await this.tx(e,["UPDATE palgres.migration SET phase = 'completing', updated_at = now()"]),n.phase="completing"),await this.runSteps(e,n,"complete",[...n.from_n!==null?[`UPDATE palgres.versions SET state = 'retired', retired_at = now() WHERE n = ${n.from_n}`]:[],`UPDATE palgres.versions SET direct = true WHERE n = ${n.to_n}`,"DELETE FROM palgres.migration"]),this.log(`palgres: version ${n.to_n} serves alone`)}async runSteps(e,n,s,r){let o=n.plan[s],i=n.done[s]??0;for(let a=i;a<o.length;a++){let l=o[a],c=`UPDATE palgres.migration SET done = done || ${x(JSON.stringify({[s]:a+1}))}::jsonb, updated_at = now()`,d=a===o.length-1;if(this.log(`palgres: ${s} ${a+1}/${o.length}: ${l.why}`),l.kind==="tx"){await this.tx(e,[...l.sql,...d?r:[c]]);continue}if(l.kind==="statement")await this.statement(e,l.sql);else if(l.kind==="backfill")await this.backfill(e,n,a,l);else if(l.kind==="seal")await this.seal(e,l);else if(l.kind==="settle")await new Promise(w=>setTimeout(w,l.ms));else throw new Se([`version ${n.to_n}'s migration has a step of a kind this Palgres does not run (${JSON.stringify(l.kind)})`]);await this.tx(e,d?r:[c])}o.length===0&&await this.tx(e,r)}async tx(e,n){let s=n.every(d=>/^(?:UPDATE|INSERT\s+INTO|DELETE\s+FROM)\s+palgres\./i.test(d)),{needs:r,made:o}=s?{needs:[],made:[]}:Fr(n),i=await Br(e.query,r),{holding:a,statementTimeout:l}=await this.settings(e),c=0;await this.retrying(e,async d=>{await e.query("BEGIN");try{let w=this.lockTimeoutFor(d);await e.query(`SET LOCAL lock_timeout = ${w}`);let u=Date.now()+a,m=f=>e.query(`SELECT set_config('lock_timeout', '${Math.max(1,Math.floor(f))}', true)`);if(!s&&i.length>0){let f=Date.now();u=f+a;let h=[i[c],...i.filter((g,p)=>p!==c)],T=new Set;for(let[g,p]of h.entries()){let S=Math.max(1,Math.floor(u-Date.now())),R=g>0&&(u-Date.now()<1||T.has(p.oid));g>0&&await e.query(`SELECT set_config('lock_timeout', '${S}', true), set_config('statement_timeout', '${S}', true)`);try{await e.query(`LOCK TABLE ${p.name} IN ${p.mode} MODE${R?" NOWAIT":""}`)}catch(E){let $=ce(E);throw($==="55P03"||$==="57014")&&(c=i.indexOf(p),this.log(`palgres: ${p.name} is held by others (${p.mode} not had${R?" at once":` in ${g===0?w:S} ms`}): the step gives way`)),$==="57014"?new In(p.name,E):E}g===0&&h.length>1&&(T=await Wr(e.query,h.slice(1),Date.now()-f))}await e.query(`SET LOCAL statement_timeout = ${x(l)}`)}for(let[f,h]of n.entries())!s&&i.length===0&&f===0?u=Date.now()+a:s||await m(u-Date.now()),await e.query(h);s||await this.notTakenFirst(e,i,o),await e.query("COMMIT")}catch(w){throw await e.query("ROLLBACK").catch(()=>{}),w}})}async settings(e){if(e.deadlockMs===void 0||e.statementTimeout===void 0){let[n]=await e.query("SELECT (SELECT setting::int FROM pg_catalog.pg_settings WHERE name = 'deadlock_timeout') AS ms, current_setting('statement_timeout') AS st");e.deadlockMs=Number(n?.ms??1e3),e.statementTimeout=String(n?.st??"0")}return{holding:Math.max(1,Math.min(this.lockTimeoutMs,Math.floor(e.deadlockMs/2))),statementTimeout:e.statementTimeout}}async notTakenFirst(e,n,s){for(let r of await jr(e.query,s)){let o=n.find(i=>i.oid===r.oid);o&&qe[o.mode]>=qe[r.mode]||this.log(`palgres: ${r.name} was locked ${r.mode} by a statement, ${o?`more strongly than the step took it first (${o.mode})`:"not taken first"}`)}}async statement(e,n){let s=/^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS ("(?:[^"]|"")+") ON /.exec(n);await this.retrying(e,async()=>{if(s){let r=await e.query(`SELECT n.nspname AS schema FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = ${x(Xr(s[1]))} AND NOT i.indisvalid`);for(let o of r)await e.query(`DROP INDEX CONCURRENTLY IF EXISTS ${M(String(o.schema),Xr(s[1]))}`)}await e.query(`SET lock_timeout = ${this.statementWaitMs}`);try{await e.query(n)}finally{await e.query("RESET lock_timeout")}})}async backfill(e,n,s,r){let{holding:o}=await this.settings(e),i=r.key.length>0,a=n.done.cursor?.step===s?n.done.cursor:void 0,l=a?.last??(i?null:0),c=a?.inclusive??!1,d=i?0:await this.pages(e,r.table),w=i?await this.highest(e,r):null,u=!1,m=a?.skippedFrom??null,f=m===null?[]:null,h=null,T=0,g=0,p=0;for(;;){let S=h?.splice(0,this.batchSize),R=S!==void 0,E=R?S.length===0:u?!1:i?w===null:Number(l)>=d,$;if(E||await this.retrying(e,async()=>{await e.query("BEGIN");try{await e.query(`SET LOCAL lock_timeout = ${o}`),await e.query("SET LOCAL statement_timeout = 30000");let O=(await e.query(i?this.keyedBatch(r,S??null,l,c,w,u):this.pageBatch(r,S??null,u?d:Number(l),u)))[0],L=O.left??[],N=R?!0:i?Number(O.seen)>0:!u,_={gone:Number(O.gone),seen:N,last:R||u&&!i?l:i?O.last??l:Number(l)+this.pagesPerBatch(),left:L},y=m??(L.length>0?i?L[0]:!0:h||S?i?S[0]??null:!0:null);await e.query(`UPDATE palgres.migration SET done = done || ${x(JSON.stringify({cursor:{step:s,last:_.last,inclusive:S?c:!1,skippedFrom:y}}))}::jsonb, updated_at = now()`),await e.query("COMMIT"),$=_}catch(O){throw await e.query("ROLLBACK").catch(()=>{}),O}}),$&&(T+=$.gone,g+=$.gone,R||(l=$.last,c=!1),$.left.length>0&&(m??=i?$.left[0]:!0,f!==null&&(f=f.length+$.left.length>is?null:[...f,...$.left])),$.seen))continue;if(!R&&!u){u=!0;continue}if(m===null)break;if(g>0)p=0;else if(++p>=this.attempts)throw new un(r.table,p);let A=Math.min(250*2**Math.max(0,p-1),5e3);this.log(`palgres: ${f===null?"rows":`${f.length} row(s)`} of ${r.table} held by writers; gone over again in ${A} ms`),await new Promise(O=>setTimeout(O,A)),f!==null?h=f:i?(h=null,l=m,c=!0,w=await this.highest(e,r)):(h=null,l=0,d=await this.pages(e,r.table)),m=null,f=[],g=0,u=!1}this.log(`palgres: ${T} row(s)`)}async highest(e,n){let s=n.key.map(b).join(", ");return(await e.query(`SELECT (SELECT to_jsonb(x) FROM (SELECT ${s} FROM ${n.table} ORDER BY ${s} DESC LIMIT 1) x) AS k`))[0].k??null}pagesPerBatch(){return Math.max(1,Math.ceil(this.batchSize/50))}async pages(e,n){return Number((await e.query(`SELECT (pg_catalog.pg_relation_size(${x(n)}::regclass) / current_setting('block_size')::int)::int AS n`))[0].n)}keyedBatch(e,n,s,r,o,i){let a="_palgres_t",l=e.key.map(b).join(", "),c=e.key.map(g=>`${a}.${b(g)}`).join(", "),d=e.key.map((g,p)=>b(`_palgres_k${p}`)),w=e.key.map((g,p)=>`${a}.${b(g)} AS ${d[p]}`).join(", "),u=g=>e.key.map((p,S)=>`${g}.${d[S]} AS ${b(p)}`).join(", "),m=g=>`(SELECT ${l} FROM jsonb_populate_record(NULL::${e.table}, ${x(JSON.stringify(g))}::jsonb))`,f=s===null?"true":`(${c}) ${r?">=":">"} ${m(s)}`,h=n!==null?`(${c}) IN (SELECT ${l} FROM jsonb_populate_recordset(NULL::${e.table}, ${x(JSON.stringify(n))}::jsonb))`:i?`${f} AND (${e.where})`:`${f} AND (${c}) <= ${m(o)}`,T=n!==null?h:`${f} AND (${c}) <= (SELECT ${d.join(", ")} FROM edge)`;return`WITH win AS (SELECT ${w} FROM ${e.table} ${a} WHERE ${h} ORDER BY ${c} LIMIT ${this.batchSize}),
|
|
312
|
+
`)||"(no change but the views)"}`);let d={from_n:c.from,to_n:c.to,plan:c,done:{},phase:"starting",opened_by:this.openedBy};return await this.runStart(s,d),c.from===null?(await this.runComplete(s,{...d,phase:"started"}),{state:"started",from:null,to:c.to,changes:c.changes,completed:!0}):{state:"started",from:c.from,to:c.to,changes:c.changes,completed:!1,...l?{adoption:l}:{}}})}async complete(){return this.session(async e=>{let n=await this.open(e);if(!n)return{state:"none"};if(n.phase==="starting"||n.phase==="rolling_back")throw new Error(`palgres: version ${n.to_n} is ${n.phase==="starting"?"still starting: run start again to finish it":"being rolled back: run rollback again"}`);await this.cipherFor(n.plan),n.from_n!==null&&await this.waitGone(e,n.from_n),await this.runComplete(e,n);let s=await this.kept(e,n.plan),r=await this.unconverted(e,n.plan);return s.length+r.length===0?{state:"completed",version:n.to_n}:(s.length>0&&this.log(`palgres: kept, holding what version ${n.from_n} wrote while version ${n.to_n} rolled out \u2014 outside the schema now, and no longer migrated: ${s.join("; ")}. Drop them yourself once their data may go.`),r.length>0&&this.log(`palgres: kept, the values a type change did not convert \u2014 outside the schema now, the new column NULL in their rows (and not NOT NULL while one is): ${r.join("; ")}. Write those rows' values yourself, then drop the old column.`),{state:"completed",version:n.to_n,kept:[...s,...r]})})}async unconverted(e,n){let s=[];for(let r of n.guarded?.retyped??[]){let o=D(r.schema,r.table);if((await e.query(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = to_regclass(${v(o)}) AND attname = ${v(r.kept)} AND NOT attisdropped) AS there`))[0]?.there!==!0)continue;let a=`FROM ${o} WHERE ${N(r.column)} IS NULL AND ${N(r.kept)} IS NOT NULL`,l=r.key.length===0?"ctid::text":r.key.length===1?`${N(r.key[0])}::text`:`ROW(${r.key.map(N).join(", ")})::text`,[{n:c}]=await e.query(`SELECT count(*)::int AS n ${a}`),d=(await e.query(`SELECT ${l} AS k ${a} ORDER BY ${r.key.length===0?"ctid":r.key.map(N).join(", ")} LIMIT 10`)).map(u=>String(u.k)),y=r.key.length===0?"ctid":r.key.join(", ");s.push(`column ${r.schema}.${r.table}.${r.kept}: the values of ${r.column} that did not become ${r.type}, in ${Number(c)} row(s) \u2014 ${y} ${d.join(", ")}${Number(c)>d.length?", \u2026":""}`)}return s}async kept(e,n){let s=[];for(let[r,o]of n.guarded?.tables??[])(await e.query(`SELECT to_regclass(${v(D(r,o))}) IS NOT NULL AS there`))[0]?.there===!0&&s.push(`table ${r}.${o}`);for(let[r,o,i]of n.guarded?.columns??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = to_regclass(${v(D(r,o))}) AND attname = ${v(i)} AND NOT attisdropped) AS there`))[0]?.there===!0&&s.push(`column ${r}.${o}.${i}`);return s}async rollback(){return this.session(async e=>{let n=await this.open(e);if(!n)return{state:"none"};if(n.phase==="completing")throw new Error(`palgres: version ${n.to_n} is completing: what the old version used is going; run complete again`);return await this.cipherFor(n.plan),await this.waitGone(e,n.to_n),n.phase!=="rolling_back"&&(await this.tx(e,["UPDATE palgres.migration SET phase = 'rolling_back', updated_at = now()"]),n.phase="rolling_back"),await this.runSteps(e,n,"rollback",[`UPDATE palgres.versions SET state = 'abandoned', retired_at = now() WHERE n = ${n.to_n}`,"DELETE FROM palgres.migration"]),this.log(`palgres: version ${n.to_n} rolled back; ${n.from_n??"no version"} serves`),{state:"rolled-back",version:n.from_n}})}async runStart(e,n){await this.runSteps(e,n,"start",[`UPDATE palgres.versions SET state = 'active', ready_at = now() WHERE n = ${n.to_n}`,"UPDATE palgres.migration SET phase = 'started', updated_at = now()"])}async runComplete(e,n){n.phase!=="completing"&&(await this.tx(e,["UPDATE palgres.migration SET phase = 'completing', updated_at = now()"]),n.phase="completing"),await this.runSteps(e,n,"complete",[...n.from_n!==null?[`UPDATE palgres.versions SET state = 'retired', retired_at = now() WHERE n = ${n.from_n}`]:[],`UPDATE palgres.versions SET direct = true WHERE n = ${n.to_n}`,"DELETE FROM palgres.migration"]),this.log(`palgres: version ${n.to_n} serves alone`)}async runSteps(e,n,s,r){let o=n.plan[s],i=n.done[s]??0;for(let a=i;a<o.length;a++){let l=o[a],c=`UPDATE palgres.migration SET done = done || ${v(JSON.stringify({[s]:a+1}))}::jsonb, updated_at = now()`,d=a===o.length-1;if(this.log(`palgres: ${s} ${a+1}/${o.length}: ${l.why}`),l.kind==="tx"){await this.tx(e,[...l.sql,...d?r:[c]]);continue}if(l.kind==="statement")await this.statement(e,l.sql);else if(l.kind==="backfill")await this.backfill(e,n,a,l);else if(l.kind==="seal")await this.seal(e,l);else if(l.kind==="settle")await new Promise(y=>setTimeout(y,l.ms));else throw new Se([`version ${n.to_n}'s migration has a step of a kind this Palgres does not run (${JSON.stringify(l.kind)})`]);await this.tx(e,d?r:[c])}o.length===0&&await this.tx(e,r)}async tx(e,n){let s=n.every(d=>/^(?:UPDATE|INSERT\s+INTO|DELETE\s+FROM)\s+palgres\./i.test(d)),{needs:r,made:o}=s?{needs:[],made:[]}:Hr(n),i=await Xr(e.query,r),{holding:a,statementTimeout:l}=await this.settings(e),c=0;await this.retrying(e,async d=>{await e.query("BEGIN");try{let y=this.lockTimeoutFor(d);await e.query(`SET LOCAL lock_timeout = ${y}`);let u=Date.now()+a,m=f=>e.query(`SELECT set_config('lock_timeout', '${Math.max(1,Math.floor(f))}', true)`);if(!s&&i.length>0){let f=Date.now();u=f+a;let g=[i[c],...i.filter((h,p)=>p!==c)],T=new Set;for(let[h,p]of g.entries()){let S=Math.max(1,Math.floor(u-Date.now())),b=h>0&&(u-Date.now()<1||T.has(p.oid));h>0&&await e.query(`SELECT set_config('lock_timeout', '${S}', true), set_config('statement_timeout', '${S}', true)`);try{await e.query(`LOCK TABLE ${p.name} IN ${p.mode} MODE${b?" NOWAIT":""}`)}catch(E){let $=ce(E);throw($==="55P03"||$==="57014")&&(c=i.indexOf(p),this.log(`palgres: ${p.name} is held by others (${p.mode} not had${b?" at once":` in ${h===0?y:S} ms`}): the step gives way`)),$==="57014"?new Ln(p.name,E):E}h===0&&g.length>1&&(T=await Vr(e.query,g.slice(1),Date.now()-f))}await e.query(`SET LOCAL statement_timeout = ${v(l)}`)}for(let[f,g]of n.entries())!s&&i.length===0&&f===0?u=Date.now()+a:s||await m(u-Date.now()),await e.query(g);s||await this.notTakenFirst(e,i,o),await e.query("COMMIT")}catch(y){throw await e.query("ROLLBACK").catch(()=>{}),y}})}async settings(e){if(e.deadlockMs===void 0||e.statementTimeout===void 0){let[n]=await e.query("SELECT (SELECT setting::int FROM pg_catalog.pg_settings WHERE name = 'deadlock_timeout') AS ms, current_setting('statement_timeout') AS st");e.deadlockMs=Number(n?.ms??1e3),e.statementTimeout=String(n?.st??"0")}return{holding:Math.max(1,Math.min(this.lockTimeoutMs,Math.floor(e.deadlockMs/2))),statementTimeout:e.statementTimeout}}async notTakenFirst(e,n,s){for(let r of await Yr(e.query,s)){let o=n.find(i=>i.oid===r.oid);o&&qe[o.mode]>=qe[r.mode]||this.log(`palgres: ${r.name} was locked ${r.mode} by a statement, ${o?`more strongly than the step took it first (${o.mode})`:"not taken first"}`)}}async statement(e,n){let s=/^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS ("(?:[^"]|"")+") ON /.exec(n);await this.retrying(e,async()=>{if(s){let r=await e.query(`SELECT n.nspname AS schema FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = ${v(Zr(s[1]))} AND NOT i.indisvalid`);for(let o of r)await e.query(`DROP INDEX CONCURRENTLY IF EXISTS ${D(String(o.schema),Zr(s[1]))}`)}await e.query(`SET lock_timeout = ${this.statementWaitMs}`);try{await e.query(n)}finally{await e.query("RESET lock_timeout")}})}async backfill(e,n,s,r){let{holding:o}=await this.settings(e),i=r.key.length>0,a=n.done.cursor?.step===s?n.done.cursor:void 0,l=a?.last??(i?null:0),c=a?.inclusive??!1,d=i?0:await this.pages(e,r.table),y=i?await this.highest(e,r):null,u=!1,m=a?.skippedFrom??null,f=m===null?[]:null,g=null,T=0,h=0,p=0;for(;;){let S=g?.splice(0,this.batchSize),b=S!==void 0,E=b?S.length===0:u?!1:i?y===null:Number(l)>=d,$;if(E||await this.retrying(e,async()=>{await e.query("BEGIN");try{await e.query(`SET LOCAL lock_timeout = ${o}`),await e.query("SET LOCAL statement_timeout = 30000");let I=(await e.query(i?this.keyedBatch(r,S??null,l,c,y,u):this.pageBatch(r,S??null,u?d:Number(l),u)))[0],L=I.left??[],k=b?!0:i?Number(I.seen)>0:!u,x={gone:Number(I.gone),seen:k,last:b||u&&!i?l:i?I.last??l:Number(l)+this.pagesPerBatch(),left:L},R=m??(L.length>0?i?L[0]:!0:g||S?i?S[0]??null:!0:null);await e.query(`UPDATE palgres.migration SET done = done || ${v(JSON.stringify({cursor:{step:s,last:x.last,inclusive:S?c:!1,skippedFrom:R}}))}::jsonb, updated_at = now()`),await e.query("COMMIT"),$=x}catch(I){throw await e.query("ROLLBACK").catch(()=>{}),I}}),$&&(T+=$.gone,h+=$.gone,b||(l=$.last,c=!1),$.left.length>0&&(m??=i?$.left[0]:!0,f!==null&&(f=f.length+$.left.length>ls?null:[...f,...$.left])),$.seen))continue;if(!b&&!u){u=!0;continue}if(m===null)break;if(h>0)p=0;else if(++p>=this.attempts)throw new dn(r.table,p);let A=Math.min(250*2**Math.max(0,p-1),5e3);this.log(`palgres: ${f===null?"rows":`${f.length} row(s)`} of ${r.table} held by writers; gone over again in ${A} ms`),await new Promise(I=>setTimeout(I,A)),f!==null?g=f:i?(g=null,l=m,c=!0,y=await this.highest(e,r)):(g=null,l=0,d=await this.pages(e,r.table)),m=null,f=[],h=0,u=!1}this.log(`palgres: ${T} row(s)`)}async highest(e,n){let s=n.key.map(N).join(", ");return(await e.query(`SELECT (SELECT to_jsonb(x) FROM (SELECT ${s} FROM ${n.table} ORDER BY ${s} DESC LIMIT 1) x) AS k`))[0].k??null}pagesPerBatch(){return Math.max(1,Math.ceil(this.batchSize/50))}async pages(e,n){return Number((await e.query(`SELECT (pg_catalog.pg_relation_size(${v(n)}::regclass) / current_setting('block_size')::int)::int AS n`))[0].n)}keyedBatch(e,n,s,r,o,i){let a="_palgres_t",l=e.key.map(N).join(", "),c=e.key.map(h=>`${a}.${N(h)}`).join(", "),d=e.key.map((h,p)=>N(`_palgres_k${p}`)),y=e.key.map((h,p)=>`${a}.${N(h)} AS ${d[p]}`).join(", "),u=h=>e.key.map((p,S)=>`${h}.${d[S]} AS ${N(p)}`).join(", "),m=h=>`(SELECT ${l} FROM jsonb_populate_record(NULL::${e.table}, ${v(JSON.stringify(h))}::jsonb))`,f=s===null?"true":`(${c}) ${r?">=":">"} ${m(s)}`,g=n!==null?`(${c}) IN (SELECT ${l} FROM jsonb_populate_recordset(NULL::${e.table}, ${v(JSON.stringify(n))}::jsonb))`:i?`${f} AND (${e.where})`:`${f} AND (${c}) <= ${m(o)}`,T=n!==null?g:`${f} AND (${c}) <= (SELECT ${d.join(", ")} FROM edge)`;return`WITH win AS (SELECT ${y} FROM ${e.table} ${a} WHERE ${g} ORDER BY ${c} LIMIT ${this.batchSize}),
|
|
313
313
|
edge AS (SELECT * FROM win ORDER BY ${d.join(" DESC, ")} DESC LIMIT 1),
|
|
314
|
-
batch AS (SELECT ${
|
|
315
|
-
done AS (UPDATE ${e.table} SET ${e.set} FROM batch WHERE (${e.key.map(
|
|
316
|
-
left_ AS (SELECT ${
|
|
314
|
+
batch AS (SELECT ${y} FROM ${e.table} ${a} WHERE ${T} AND (${e.where}) FOR NO KEY UPDATE OF ${a} SKIP LOCKED),
|
|
315
|
+
done AS (UPDATE ${e.table} SET ${e.set} FROM batch WHERE (${e.key.map(h=>`${e.table}.${N(h)}`).join(", ")}) = (${d.map(h=>`batch.${h}`).join(", ")}) AND (${e.where}) RETURNING NOT (${e.where}) AS gone),
|
|
316
|
+
left_ AS (SELECT ${y} FROM ${e.table} ${a} WHERE ${T} AND (${e.where}) AND NOT EXISTS (SELECT 1 FROM batch b WHERE (${d.map(h=>`b.${h}`).join(", ")}) = (${c})))
|
|
317
317
|
SELECT (SELECT count(*) FROM win)::int AS seen, (SELECT count(*) FROM done WHERE gone)::int AS gone,
|
|
318
318
|
(SELECT to_jsonb(x) FROM (SELECT ${u("edge")} FROM edge) x) AS last,
|
|
319
|
-
(SELECT jsonb_agg(to_jsonb(x)) FROM (SELECT ${u("left_")} FROM left_ ORDER BY ${d.join(", ")} LIMIT ${
|
|
319
|
+
(SELECT jsonb_agg(to_jsonb(x)) FROM (SELECT ${u("left_")} FROM left_ ORDER BY ${d.join(", ")} LIMIT ${ls+1}) x) AS left`}pageBatch(e,n,s,r){let o=n!==null?`ctid = ANY (${v(`{${n.map(i=>`"${String(i)}"`).join(",")}}`)}::tid[])`:r?`ctid >= '(${s},0)'::tid`:`ctid >= '(${s},0)'::tid AND ctid < '(${s+this.pagesPerBatch()},0)'::tid`;return`WITH batch AS (SELECT ctid AS c FROM ${e.table} WHERE ${o} AND (${e.where}) FOR NO KEY UPDATE SKIP LOCKED),
|
|
320
320
|
done AS (UPDATE ${e.table} SET ${e.set} WHERE ctid = ANY (ARRAY(SELECT c FROM batch)) AND (${e.where}) RETURNING NOT (${e.where}) AS gone),
|
|
321
321
|
left_ AS (SELECT ctid AS c FROM ${e.table} WHERE ${o} AND (${e.where}) AND ctid <> ALL (ARRAY(SELECT c FROM batch)))
|
|
322
|
-
SELECT (SELECT count(*) FROM done WHERE gone)::int AS gone, (SELECT array_agg(c::text) FROM (SELECT c FROM left_ LIMIT ${
|
|
322
|
+
SELECT (SELECT count(*) FROM done WHERE gone)::int AS gone, (SELECT array_agg(c::text) FROM (SELECT c FROM left_ LIMIT ${ls+1}) x) AS left`}async retrying(e,n){for(let s=1;;s++)try{await n(s);return}catch(r){let o=r instanceof Ln?"57014":ce(r);if(o!=="55P03"&&o!=="40P01"&&!(r instanceof Ln)||s>=this.attempts)throw r;let i=Math.min(250*2**(s-1),5e3);this.log(`palgres: a lock was busy (${o}); again in ${i} ms`),await new Promise(a=>setTimeout(a,i))}}async cipherFor(e){let n=[...new Set([...e.complete,...e.rollback].filter(s=>s.kind==="seal").map(s=>s.address))];if(!(n.length===0||this.fields!==void 0)){if(this.fieldsSource===void 0)throw new Se([`${n.join(", ")} ${n.length===1?"becomes":"become"} encrypted or stop being while the table holds rows: the migration seals or opens the rows with the project's field keys \u2014 Migrator({ fields })`]);this.fields=await et(this.fieldsSource)}}async seal(e,n){let s=this.fields;if(s===void 0)throw new Se([`${n.address}'s rows are sealed or opened with the project's field keys \u2014 Migrator({ fields })`]);await this.waitBegunBefore(e,n.address);let{holding:r}=await this.settings(e);for(let o=1;;o++){let i=null,a=0;do await this.retrying(e,async()=>{await e.query("BEGIN");try{await e.query(`SET LOCAL lock_timeout = ${r}`),await e.query("SET LOCAL statement_timeout = 30000");let c=await tt((d,y)=>e.query(d,y),n,s,i,this.batchSize);await e.query("COMMIT"),a+=c.done,i=c.last}catch(c){throw await e.query("ROLLBACK").catch(()=>{}),c}});while(i!==null);let l=await Or((c,d)=>e.query(c,d),n,s);if(this.log(`palgres: ${n.address}: pass ${o}, ${a} row(s) ${n.direction==="seal"?"sealed":"opened"}${l?", some written meanwhile":""}`),!l)return;if(o>=this.attempts)throw new dn(n.table,o);await new Promise(c=>setTimeout(c,Math.min(250*2**(o-1),5e3)))}}async waitBegunBefore(e,n){let s=(await e.query("SELECT coalesce(array_agg(x)::text[], ARRAY[]::text[]) AS xids FROM pg_snapshot_xip(pg_current_snapshot()) AS x"))[0].xids,r=Date.now()+this.statementWaitMs;for(let o=s;o.length>0;){if(o=(await e.query("SELECT coalesce(array_agg(x::text), ARRAY[]::text[]) AS xids FROM unnest($1::xid8[]) AS x WHERE pg_xact_status(x) = 'in progress'",[`{${o.join(",")}}`]))[0].xids,o.length===0)return;if(Date.now()>=r)throw new Error(`palgres: ${n}: ${o.length} transaction(s) open when its phase turned final are still open after ${this.statementWaitMs} ms \u2014 run complete again`);await new Promise(a=>setTimeout(a,200))}}async waitGone(e,n){let s=Date.now()+this.disconnectTimeoutMs;for(;;){let r=await e.query(`SELECT count(*)::int AS n FROM pg_stat_activity WHERE application_name = ${v(St(n))} AND datname = current_database() AND pid <> pg_backend_pid()`),o=Number(r[0].n);if(o===0)return;if(Date.now()>=s)throw new vn(n,o,this.disconnectTimeoutMs);await new Promise(i=>setTimeout(i,500))}}async adopt(e,n){let s=[...new Set([...n.tables.map(m=>m.schema),...n.raw.flatMap(m=>m.schema?[m.schema]:[])])],r=await yt(this.pool,s,this.roles);if(!n.tables.some(m=>r.schema.tables.some(f=>f.schema===m.schema&&(f.name===m.name||f.name===m.renamedFrom))))return null;if(!this.shadow)throw new Error("palgres: the database holds tables of the schema and no Palgres version: taking it over needs a shadow database (MigratorOptions.shadow) to read the schema as Postgres writes it");let i=await this.made(e,n,s,r),a=is(r,i,n);if(a.refusals.length>0)throw new Se(a.refusals);let l=[this.roles.anon,this.roles.authenticated,this.roles.service].map(N).join(", "),c={tables:a.schema.tables.filter(m=>!m.ignored).map(m=>({schema:m.schema,name:m.name,physical:m.name,columns:m.columns.filter(f=>!f.ignored).map(f=>({name:f.name,physical:f.name}))}))},d=a.schema.tables.map(m=>D(m.schema,m.name)),y=Xe(a.schema),u=async()=>{await this.tx(e,[...a.unforce.map(m=>`ALTER TABLE ${D(m.slice(0,m.indexOf(".")),m.slice(m.indexOf(".")+1))} NO FORCE ROW LEVEL SECURITY`),...[...new Set(a.schema.tables.map(m=>m.schema))].map(m=>`GRANT USAGE ON SCHEMA ${N(m)} TO ${l}`),...d.map(m=>`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${m} TO ${l}`),`DO $palgres$ DECLARE s regclass; BEGIN
|
|
323
323
|
FOR s IN SELECT d.objid::regclass FROM pg_depend d JOIN pg_class c ON c.oid = d.objid AND c.relkind = 'S'
|
|
324
|
-
WHERE d.deptype = 'a' AND d.refobjid = ANY (ARRAY[${d.length>0?d.map(m=>`${
|
|
324
|
+
WHERE d.deptype = 'a' AND d.refobjid = ANY (ARRAY[${d.length>0?d.map(m=>`${v(m)}::regclass`).join(", "):"NULL::regclass"}]::oid[]) LOOP
|
|
325
325
|
EXECUTE format('GRANT USAGE, SELECT ON SEQUENCE %s TO ${l.replace(/'/g,"''")}', s);
|
|
326
|
-
END LOOP; END $palgres$`,`INSERT INTO palgres.versions (n, digest, schema, layout, state, direct, ready_at) VALUES (1, ${
|
|
326
|
+
END LOOP; END $palgres$`,`INSERT INTO palgres.versions (n, digest, schema, layout, state, direct, ready_at) VALUES (1, ${v(y)}, ${v(JSON.stringify(a.schema))}::jsonb, ${v(JSON.stringify(c))}::jsonb, 'active', true, now())`]),this.log(`palgres: takes the database over as version 1 (${a.schema.tables.length} table(s))${a.unforce.length>0?`; FORCE row-level security off on ${a.unforce.join(", ")}`:""}${a.unmanaged.length>0?`
|
|
327
327
|
left as it is:
|
|
328
328
|
${a.unmanaged.join(`
|
|
329
|
-
`)}`:""}`)};return{version:{n:1,digest:
|
|
329
|
+
`)}`:""}`)};return{version:{n:1,digest:y,state:"active",schema:a.schema},adoption:{unforced:a.unforce,unmanaged:a.unmanaged},layout:c,record:u}}async made(e,n,s,r){let o=`palgres_shadow_${Qi(6).toString("hex")}`;await e.query(`CREATE DATABASE ${N(o)}`);try{let i=this.shadow(o);try{await new t(i,{roles:this.roles,lockTimeoutMs:this.lockTimeoutMs}).start(n);let a=await yt(i,s,this.roles);return await sa(i,r,a),a}finally{await i.end()}}finally{await e.query(`DROP DATABASE IF EXISTS ${N(o)}`)}}async planFrom(e,n,s){let r=new Set;for(let h of n?.schema.tables??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM ${D(h.schema,h.name)}) AS any`))[0].any&&r.add(F(h));let o=new Map,i=[],a=(h,p)=>{let S=`${h}\0${p}`;return o.has(S)||(o.set(S,void 0),i.push([h,p])),o.get(S)},c=(await e.query("SELECT to_regclass('palgres.versions') IS NOT NULL AS there"))[0]?.there===!0?Number((await e.query("SELECT coalesce(max(n), 0) AS n FROM palgres.versions"))[0].n):0,d=Math.max(c,n?.n??0)+1,y=new Map,u=h=>(y.has(h)||y.set(h,void 0),y.get(h)),m=new Map;if((await e.query(`SELECT to_regclass('${J}.generations') IS NOT NULL AS there`))[0]?.there===!0)for(let h of await e.query(`SELECT table_key, gen, model, dimensions, metric, from_columns, status FROM ${J}.generations ORDER BY table_key, gen`)){let p=String(h.table_key);m.has(p)||m.set(p,[]),m.get(p).push({gen:Number(h.gen),model:String(h.model),dimensions:Number(h.dimensions),metric:h.metric,from:h.from_columns.map(String),status:h.status})}let f=(await e.query("SELECT n.nspname AS schema FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector'"))[0]?.schema,g=()=>rs({from:n&&{n:n.n,schema:n.schema,access:n.access??null},next:d,to:s,hasRows:h=>r.has(h),castable:a,checkedDomain:u,roles:this.roles,generations:h=>m.get(h)??[],vectorSchema:typeof f=="string"?f:"public"}),T=g();if(i.length===0&&y.size===0)return T;for(let[h,p]of i)o.set(`${h}\0${p}`,await this.casts(e,h,p));for(let h of y.keys())y.set(h,await this.checkedDomain(e,h));return g()}async checkedDomain(e,n){let s=await e.query(`SELECT t.typtype = 'd' AND (t.typnotnull OR EXISTS (SELECT 1 FROM pg_catalog.pg_constraint c WHERE c.contypid = t.oid)) AS checked FROM pg_catalog.pg_type t WHERE t.oid = pg_catalog.to_regtype(${v(n)})`);return s.length===0?void 0:s[0].checked===!0}async casts(e,n,s){try{return await e.query(`SELECT CAST(NULL::${n} AS ${s})`),!0}catch(r){let o=ce(r);if(o==="42846")return!1;if(o==="42704")return;throw r}}async active(e){if(e.ledger===!1)return null;let n=await e.query("SELECT n, digest, schema, layout FROM palgres.versions WHERE state = 'active' ORDER BY n DESC LIMIT 1"),s=await this.open(e),o=(s?await e.query(`SELECT n, digest, schema, layout FROM palgres.versions WHERE n = ${s.from_n??-1}`):n)[0];return o?{n:Number(o.n),digest:String(o.digest),state:"active",schema:Tt(o.schema),access:Tt(o.layout)?.access??null}:null}async version(e,n){if(e.ledger===!1)return null;let s=await e.query(`SELECT n, digest, state FROM palgres.versions WHERE n = ${n}`);return s[0]?{n,digest:String(s[0].digest),state:s[0].state}:null}async open(e){if(e.ledger===!1)return null;let s=(await e.query("SELECT from_n, to_n, plan, done, phase, to_jsonb(m) ->> 'opened_by' AS opened_by FROM palgres.migration m"))[0];return s?{from_n:s.from_n===null?null:Number(s.from_n),to_n:Number(s.to_n),plan:ta(Tt(s.plan),Number(s.to_n)),done:Tt(s.done),phase:s.phase,opened_by:typeof s.opened_by=="string"?s.opened_by:null}:null}async session(e,n=!0,s){let r=await this.pool.reserve(),o={query:async(i,a)=>await r.unsafe(i,a)};try{if(await o.query("SET application_name = 'palgres:migrate'"),await o.query("SET search_path = public, pg_temp"),n){await o.query(`SELECT pg_advisory_lock(hashtextextended(${v(zr)}, 0))`);let i=(await o.query(`SELECT to_regclass('palgres.versions') IS NOT NULL AS there, (SELECT pg_catalog.obj_description(n.oid, 'pg_namespace') FROM pg_catalog.pg_namespace n WHERE n.nspname = '${J}') AS search`))[0];o.ledger=i.there===!0,o.searchLedger=typeof i.search=="string"?i.search:null,o.ledger&&await this.ensure(o)}else if((await o.query("SELECT to_regclass('palgres.migration') IS NULL AS none"))[0].none)return await(s?s(o):e(na));return await e(o)}finally{n&&await o.query(`SELECT pg_advisory_unlock(hashtextextended(${v(zr)}, 0))`).catch(()=>{}),r.release()}}async ownAuth(e){let n=await this.authRefusals(e);if(n.length>0)throw new Se(n)}async authRefusals(e){let n={jwt:["SELECT coalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb, '{}'::jsonb)"],uid:["SELECT nullif(auth.jwt() ->> 'sub', '')","SELECT current_setting('request.jwt.claims', true)::jsonb ->> 'sub'"],role:["SELECT nullif(auth.jwt() ->> 'role', '')"]},s=i=>i.replace(/\s+/g," ").trim();return(await e.query("SELECT p.proname AS name, p.prosrc AS src, pg_catalog.format_type(p.prorettype, NULL) AS returns FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace WHERE n.nspname = 'auth' AND p.proname IN ('jwt', 'uid', 'role') AND p.pronargs = 0")).filter(i=>!(n[String(i.name)]??[]).some(a=>s(a)===s(String(i.src)))).map(i=>`auth.${i.name}() is the database's own (returns ${i.returns}: ${s(String(i.src)).slice(0,120)}): Palgres makes it read the request's claims (request.jwt.claims), and the app there now would read its caller otherwise \u2014 rename yours, or make it read the claims as Palgres does, before the take-over`)}async ensure(e){let n=[this.roles.anon,this.roles.authenticated,this.roles.service],s=await e.query(`SELECT r FROM unnest(ARRAY[${n.map(v).join(", ")}]) AS r WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r)`);if(s.length>0)throw new Error(`palgres: the database has no role ${s.map(o=>o.r).join(", ")} \u2014 the app's roles are made with the database`);let r=n.map(N).join(", ");await this.tx(e,["CREATE SCHEMA IF NOT EXISTS palgres",`CREATE TABLE IF NOT EXISTS palgres.versions (
|
|
330
330
|
n integer PRIMARY KEY,
|
|
331
331
|
digest text NOT NULL,
|
|
332
332
|
schema jsonb NOT NULL,
|
|
@@ -349,60 +349,60 @@ END $palgres$`,In=class extends Error{constructor(e,n){super(`palgres: ${e} was
|
|
|
349
349
|
address text PRIMARY KEY,
|
|
350
350
|
direction text NOT NULL CHECK (direction IN ('seal', 'open')),
|
|
351
351
|
phase text NOT NULL CHECK (phase IN ('mixed', 'final'))
|
|
352
|
-
)`,`GRANT SELECT ON ${ye} TO PUBLIC`,
|
|
353
|
-
${A.map(L=>`// ${
|
|
352
|
+
)`,`GRANT SELECT ON ${ye} TO PUBLIC`,Jr,"CREATE SCHEMA IF NOT EXISTS auth","CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb LANGUAGE sql STABLE AS $palgres$ SELECT coalesce(nullif(current_setting('request.jwt.claims', true), '')::jsonb, '{}'::jsonb) $palgres$","CREATE OR REPLACE FUNCTION auth.uid() RETURNS text LANGUAGE sql STABLE AS $palgres$ SELECT nullif(auth.jwt() ->> 'sub', '') $palgres$","CREATE OR REPLACE FUNCTION auth.role() RETURNS text LANGUAGE sql STABLE AS $palgres$ SELECT nullif(auth.jwt() ->> 'role', '') $palgres$",`GRANT USAGE ON SCHEMA auth TO ${r}`,`GRANT EXECUTE ON FUNCTION auth.jwt(), auth.uid(), auth.role() TO ${r}`,...e.searchLedger===ut(this.roles)?[]:vr(this.roles)]),e.searchLedger=ut(this.roles)}},na={query:async()=>[]};function ta(t,e){let n=t.format??1;if(!Number.isInteger(n)||n<1||n>ts)throw new Se([`version ${e}'s migration was planned by a newer Palgres (plan format ${String(t.format)}; this one runs ${ts} and before): release the version that planned it, or one after, to go on with it`]);for(let s of["start","complete","rollback"])for(let r of t[s]??[])if(!qr.has(r.kind))throw new Se([`version ${e}'s migration has a step of a kind this Palgres does not run (${JSON.stringify(r.kind)}, in its ${s}): release the version that planned it, or one after, to go on with it`]);return t}function Qr(t){let e=qt(ge(t));if(e.length>0)throw new Ge(e)}function Tt(t){return typeof t=="string"?JSON.parse(t):t}function Zr(t){return t.slice(1,-1).replace(/""/g,'"')}function us(t,e="public"){return`${N(Ie(t,e))}, ${N(e)}, pg_temp`}function eo(t){return t.tables.every(e=>e.physical===e.name&&e.columns.every(n=>n.physical===n.name))}async function sa(t,e,n){for(let[s,r]of n.objects){if(!s.startsWith("view ")&&!s.startsWith("materialized view "))continue;let o=e.objects.get(s);if(o===void 0||o===r)continue;let{options:i,query:a}=JSON.parse(o),l=await t.reserve();try{await l.unsafe("BEGIN"),await l.unsafe("SET LOCAL search_path = ''"),await l.unsafe(`CREATE TEMP VIEW palgres_fixpoint AS ${a}`);let c=await l.unsafe("SELECT pg_catalog.pg_get_viewdef('pg_temp.palgres_fixpoint'::regclass, true) AS def");JSON.stringify({options:i,query:c[0].def.trim().replace(/;$/,"")})===r&&e.objects.set(s,r)}catch{}finally{await Promise.resolve(l.unsafe("ROLLBACK")).catch(()=>{}),l.release()}}}function ra(t){return{...t,pooled:!0}}function oa(t){return`SELECT set_config('application_name', ${ne(t.applicationName)}, false)`}function to(t,e,n,s){return{...n!==void 0?{access:n}:{},...n!==void 0&&s!==void 0?{accessText:s}:{},version:t,direct:e,searchPath:e?`${N("public")}, pg_temp`:us(t),applicationName:St(t),schema:r=>e?r:Ie(t,r)}}var Rt=class extends Error{digest;constructor(e){super(`palgres: this schema (${e}) has no version in the database yet \u2014 the deploy migrates it before the app serves (PALBASE_DB_MIGRATE=start)`),this.name="VersionNotMigrated",this.digest=e}};async function ia(t,e,n={}){let s=Xe(e),r=Date.now()+(n.waitMs??0);for(;;){let o;try{o=await t.unsafe("SELECT n, direct FROM palgres.versions WHERE digest = $1 AND state = 'active'",[s])}catch(i){let a=ce(i);if(a!=="42P01"&&a!=="3F000"){if(Ee(i)===void 0||Date.now()>=r)throw i;n.onUnreachable?.(i),await new Promise(l=>setTimeout(l,1e3));continue}o=[]}if(o.length>0)return to(Number(o[0].n),o[0].direct===!0,e.access?.compiled,e.access?.text);if(Date.now()>=r)throw new Rt(s);await new Promise(i=>setTimeout(i,500))}}function xn(t,e,n){let s=no.get(t);s||no.set(t,s=new Map);let r=s.get(e);return r===void 0&&(r=`SELECT set_config('role', ${ne(e)}, true), set_config('search_path', ${ne(t.searchPath)}, true), set_config('application_name', ${ne(t.applicationName)}, ${t.pooled===!0}), set_config('palgres.version', ${ne(String(t.version))}, true), set_config('request.jwt.claims', `,s.set(e,r)),`${r}${ne(JSON.stringify(n))}, true)`}var no=new WeakMap;async function aa(t,e,n,s,r="service_role"){let o=ro(e,n,s),i=n.access!==void 0;return o.length===0&&!i?{deleted:0,detached:0}:t.begin(async a=>{await a.unsafe(xn(e,r,{role:r})),await a.unsafe("SET CONSTRAINTS ALL DEFERRED");let l={query:(d,y)=>a.unsafe(d,y)},c=await oo(l,o,s);return i?{...c,relationships:await so(l,s)}:c})}async function la(t,e,n,s){let r=ro(e,n,s),o=n.access!==void 0;if(r.length===0&&!o)return{deleted:0,detached:0};let i=[...new Set(ge(n).tables.flatMap(l=>l.foreignKeys.filter(c=>c.deferrable).map(c=>`${l.schema}.${c.name}`)))].sort(),a=`ARRAY[${i.map(v).join(", ")}]::text[]`;return t.attempt(async l=>{i.length>0&&await l.query(`SELECT palgres.defer_keys(${a}, true)`);let c=await oo(l,r,s);return i.length>0&&await l.query(`SELECT palgres.defer_keys(${a}, false)`),o?{...c,relationships:await so(l,s)}:c})}async function so(t,e){let n=await t.query("SELECT access.forget_subject($1)::int AS n",[e]);return Number(n[0].n)}function ro(t,e,n){if(typeof n!="string"||n==="")throw new TypeError("forgetUser: the user id is a non-empty string");let s=[];for(let r of ge(e).tables)for(let o of r.columns){if(!o.user)continue;let i=r.ignored===!0||o.ignored===!0;s.push({view:D(i?r.schema:t.schema(r.schema),r.name),column:o.name,onDelete:o.user.onDelete})}return s}async function oo(t,e,n){let s=0,r=0;for(let o of e.filter(i=>i.onDelete==="set null")){let i=await t.query(`WITH t AS (UPDATE ${o.view} SET ${N(o.column)} = NULL WHERE ${N(o.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[n]);r+=Number(i[0].n)}for(let o of e.filter(i=>i.onDelete==="cascade")){let i=await t.query(`WITH t AS (DELETE FROM ${o.view} WHERE ${N(o.column)} = $1 RETURNING 1) SELECT count(*)::int AS n FROM t`,[n]);s+=Number(i[0].n)}return{deleted:s,detached:r}}var ca=new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" ")),ua=new Set(["defineSchema","defineTable","uuid","text","integer","bigint","numeric","boolean","timestamp","date","jsonb","policy","raw","foreignKey","enumType","sqlType","AnyColumn","TableHandle"]),ds=t=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t),ao=/^[A-Za-z_$][A-Za-z0-9_$]*$/,K=t=>JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),da=t=>t.replace(/[\r\n\u2028\u2029]+/g," "),lo=t=>t==="__proto__"?`[${K(t)}]`:ao.test(t)?t:K(t),io={uuid:"uuid()",text:"text()",integer:"integer()",bigint:"bigint()",numeric:"numeric()",boolean:"boolean()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"},ma=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp with time zone","date"]);function pa(t){let e=/^'((?:[^']|'')*)'(?:::[a-z_ ."]+(?:\[\])?)?$/i.exec(t);return e?e[1].replace(/''/g,"'"):void 0}function fa(t,e={}){let n=e.from??"palbase/backend",s=[],r=new Map,o=new Map(t.enums.map(f=>[$n(f.schema,f.name),f])),i=new Map,a=new Set;for(let f of t.tables){let g=ao.test(f.name)&&!ca.has(f.name)&&!ua.has(f.name)?f.name:`t_${f.name.replace(/[^A-Za-z0-9_$]/g,"_")}`;for(f.schema!=="public"&&a.has(g)&&(g=`${f.schema}_${g}`);a.has(g);)g=`${g}_`;a.add(g),i.set(F(f),g)}let l=e.units??[],c=ga(t),d=ha(t),y=[...new Set([...t.tables.map(f=>f.schema),...l.map(f=>f.schema)])].sort(),u=new Map,m=new Set;for(let f of y.filter(ds)){let g=f;for(let T=2;m.has(g.toLowerCase());T++)g=`${f}_${T}`;m.add(g.toLowerCase()),u.set(f,g)}for(let f of y){if(!ds(f)){s.push(`schema ${JSON.stringify(f)} is not a plain name: not pulled`);continue}let g=t.tables.filter(L=>L.schema===f),T=new Set(["defineSchema","defineTable"]),h=new Map,p=g.map(L=>Ea(L,t,o,i,T,h,s,c,d)),S=l.filter(L=>L.schema===f);S.length>0&&T.add("raw");let b=S.map(L=>` raw(${K(L.name)}, ${K(L.create)}, { drop: ${K(L.drop)}${L.before?", before: true":""} }),`),E=[`import { ${[...T].sort().join(", ")} } from ${K(n)};`];for(let[L,k]of[...h].sort())E.push(`import { ${[...k].sort().join(", ")} } from ${K(`./${u.get(L)}.ts`)};`);let $=f==="public"&&t.extensions.length>0?`, extensions: [${t.extensions.map(K).join(", ")}]`:"",A=(e.unmanaged??[]).filter(L=>L.includes(` ${f}.`)&&!l.some(k=>L.startsWith(k.listed))),I=A.length>0?`// Left as it is in the database, outside this file:
|
|
353
|
+
${A.map(L=>`// ${da(L)}`).join(`
|
|
354
354
|
`)}
|
|
355
355
|
|
|
356
356
|
`:"";r.set(`db/${u.get(f)}.ts`,`// Written by palgres pull from the database, ${new Date().toISOString().slice(0,10)}.
|
|
357
|
-
${
|
|
357
|
+
${I}${E.join(`
|
|
358
358
|
`)}
|
|
359
359
|
|
|
360
360
|
${p.join(`
|
|
361
361
|
|
|
362
362
|
`)}${p.length>0?`
|
|
363
363
|
|
|
364
|
-
`:""}export default defineSchema(${
|
|
365
|
-
tables: [${
|
|
366
|
-
${$.slice(2)},`:""}${
|
|
364
|
+
`:""}export default defineSchema(${K(f)}, {
|
|
365
|
+
tables: [${g.map(L=>i.get(F(L))).join(", ")}],${$?`
|
|
366
|
+
${$.slice(2)},`:""}${b.length>0?`
|
|
367
367
|
raw: [
|
|
368
|
-
${
|
|
368
|
+
${b.join(`
|
|
369
369
|
`)}
|
|
370
370
|
],`:""}
|
|
371
371
|
});
|
|
372
|
-
`)}return{files:r,notes:s}}function
|
|
372
|
+
`)}return{files:r,notes:s}}function co(t,e){let n=r=>`${t.schema==="public"?t.name:`${t.schema}_${t.name}`}_${r}_fkey`,s=new Map;for(let r of t.foreignKeys)r.columns.length===1&&r.name===n(r.columns[0])&&r.match!=="full"&&!ms(e,r)&&s.set(r.columns[0],r);return s}var ms=(t,e)=>!ds(e.refSchema)||!t.tables.some(n=>n.schema===e.refSchema&&n.name===e.refTable);function ha(t){let e=new Map(t.tables.map(d=>[F(d),d.foreignKeys.filter(y=>!ms(t,y)).map(y=>`${y.refSchema}.${y.refTable}`)])),n=new Map,s=new Map,r=new Map,o=[],i=new Set,a=0,l=0,c=d=>{n.set(d,a),s.set(d,a),a++,o.push(d),i.add(d);for(let u of e.get(d)??[])n.has(u)?i.has(u)&&s.set(d,Math.min(s.get(d),n.get(u))):(c(u),s.set(d,Math.min(s.get(d),s.get(u))));if(s.get(d)!==n.get(d))return;let y;do y=o.pop(),i.delete(y),r.set(y,l);while(y!==d);l++};for(let d of e.keys())n.has(d)||c(d);return(d,y,u)=>r.get(F(d))===r.get(`${y}.${u}`)}function ga(t){let e=a=>a.endsWith("_id")?a.slice(0,-3):a,n=new Map,s=[];for(let a of t.tables)for(let[l,c]of co(a,t))s.push({fk:`${F(a)}.${l}`,child:F(a),column:l,target:`${c.refSchema}.${c.refTable}`,childName:a.name});let r=new Map,o=(a,l)=>r.set(`${a}\0${l}`,(r.get(`${a}\0${l}`)??0)+1);for(let a of s)o(a.child,e(a.column)),a.target!==a.child&&o(a.target,a.childName);let i=(a,l)=>(r.get(`${a}\0${l}`)??0)>1;for(let a of s){let l={};i(a.child,e(a.column))&&(l.as=a.column),a.target!==a.child&&i(a.target,a.childName)&&(l.reverseAs=`${a.childName}_${e(a.column)}`),(l.as!==void 0||l.reverseAs!==void 0)&&n.set(a.fk,l)}return n}function Ea(t,e,n,s,r,o,i,a,l){let c=F(t),d=[],y=t.primaryKey.length===1?t.primaryKey[0]:void 0,u=new Set(t.uniques.filter(E=>E.columns.length===1&&E.name===`${t.name}_${E.columns[0]}_key`).map(E=>E.columns[0])),m=co(t,e),f=E=>ms(e,E);for(let E of t.foreignKeys)f(E)&&i.push(`foreign key ${c}.${E.name} references ${E.refSchema}.${E.refTable}, outside the pulled schemas: left out, kept in the database as it is`);for(let E of t.foreignKeys)f(E)||!en(E.onDelete,E.onUpdate)||E.deferrable||i.push(`foreign key ${c}.${E.name} is checked at once, so the files say deferrable: false \u2014 remove it to let the next migration make the key deferrable: forgetting a user needs that where the user's rows cascade onto a row with more than one key with an action`);let g=new Set(t.indexes.map(E=>E.name)),T={name(E,$){let A=s.get(`${E}.${$}`);if(E!==t.schema){let I=o.get(E)??new Set;I.add(A),o.set(E,I)}return A},arrow(E,$,A){return l(t,E,$)?(r.add(`type ${A}`),`(): ${A} =>`):"() =>"}};d.push(" columns: {");for(let E of t.columns)d.push(` ${lo(E.name)}: ${ya(t,E,n,r,i,y===E.name,u.has(E.name),m.get(E.name),g,T,a.get(`${c}.${E.name}`))},`);d.push(" },"),t.primaryKey.length>1&&d.push(` primaryKey: [${t.primaryKey.map(K).join(", ")}],`);let h=t.uniques.filter(E=>!(E.columns.length===1&&u.has(E.columns[0])&&E.name===`${t.name}_${E.columns[0]}_key`));h.length>0&&d.push(` unique: [${h.map(E=>`{ name: ${K(E.name)}, columns: [${E.columns.map(K).join(", ")}] }`).join(", ")}],`),t.checks.length>0&&d.push(` checks: [${t.checks.map(E=>`{ name: ${K(E.name)}, expr: ${K(E.expr)} }`).join(", ")}],`);let p=[],S=[];for(let E of t.indexes)($a(E)?p:S).push(E);p.length>0&&d.push(` indexes: () => [${p.map(E=>Ta(E)).join(", ")}],`);let b=t.foreignKeys.filter(E=>!f(E)&&m.get(E.columns[0])!==E);return b.length>0&&(r.add("foreignKey"),d.push(` foreignKeys: (c) => [${b.map(E=>Ra(t,E,T)).join(", ")}],`)),t.policies.length>0&&!t.rls?i.push(`table ${c} has ${t.policies.length} polic${t.policies.length===1?"y":"ies"} with row-level security off: they do nothing, and the files leave them out \u2014 the take-over drops them; to have them hold, declare rls: true and the policies`):t.policies.length>0&&(r.add("policy"),d.push(` policies: () => [${t.policies.map(E=>ba(t,E)).join(", ")}],`)),t.rls||d.push(" rls: false,"),S.length>0&&(r.add("raw"),d.push(` raw: [${S.map(E=>`raw(${K(E.name)}, ${K(Sa(t,E))})`).join(", ")}],`)),`export const ${s.get(c)} = defineTable(${K(t.name)}, {
|
|
373
373
|
${d.join(`
|
|
374
374
|
`)}
|
|
375
|
-
});`}function ma(t,e,n,s,r,o,i,a,l,c,d){let w=`${F(t)}.${e.name}`,u,m=e.type,f=!1;m.endsWith("[]")&&(ia.has(m.slice(0,-2))||n.has(m.slice(0,-2)))&&(m=m.slice(0,-2),f=!0);let h=n.get(m),T=/^numeric\((\d+),(\d+)\)$/.exec(m);if(eo[m]?u=eo[m]:h&&h.schema===t.schema?(u=`enumType(${j(h.name)}, [${h.values.map(j).join(", ")}])`,s.add("enumType")):T?u=`numeric({ precision: ${T[1]}, scale: ${T[2]} })`:(u=`sqlType(${j(e.type)})`,s.add("sqlType"),f=!1),s.add(u.slice(0,u.indexOf("("))),f&&(u+=".array()"),o&&(u+=".primaryKey()"),e.identity&&(u+=e.identity==="always"?".identity()":".identity({ always: false })"),e.nullable&&!o&&(u+=".nullable()"),i&&(u+=".unique()"),e.generated&&(u+=`.generated(${j(e.generated.expr)}${e.generated.stored?", { stored: true }":""})`),e.default!==void 0&&(u+=pa(e,f)),a){let g=c.name(a.refSchema,a.refTable),p=[];d?.as!==void 0&&p.push(`as: ${j(d.as)}`),d?.reverseAs!==void 0&&p.push(`reverseAs: ${j(d.reverseAs)}`),a.onDelete!=="no action"&&p.push(`onDelete: ${j(a.onDelete)}`),a.onUpdate!=="no action"&&p.push(`onUpdate: ${j(a.onUpdate)}`),ro(t,e.name)||p.push("index: false"),Ze(a.onDelete,a.onUpdate)&&!a.deferrable&&p.push("deferrable: false"),u+=`.references(${c.arrow(a.refSchema,a.refTable,"AnyColumn")} ${g}.${to(a.refColumns[0])}${p.length>0?`, { ${p.join(", ")} }`:""})`}return/^(owner|user_id|created_by|author_id|.*_user_id)$/.test(e.name)&&!a&&r.push(`column ${w} may hold a user's id: mark it ownedByUser() or userRef() so user.deleted reaches it`),u}function ro(t,e){let n=t.indexes.find(r=>r.name===`${t.name}_${e}_idx`);if(n===void 0||n.unique||n.where!==void 0||n.method!==void 0||n.include?.length||n.keys.length!==1)return!1;let s=n.keys[0];return"column"in s&&s.column===e&&!s.desc&&s.nulls===void 0}function pa(t,e){let n=t.default;if(n==="gen_random_uuid()")return".defaultRandom()";if(n==="now()"&&t.type==="timestamp with time zone"||n==="CURRENT_DATE"&&t.type==="date")return".defaultNow()";if(n==="true"||n==="false")return`.default(${n})`;if(/^-?\d+(\.\d+)?$/.test(n)&&(t.type==="integer"||t.type==="bigint"))return`.default(${n})`;if(n==="'{}'::text[]"||/^'\{\}'::/.test(n))return e?".default([])":`.defaultSql(${j(n)})`;let s=aa(n);if(s!==void 0&&(/^'(?:[^']|'')*'::text$/.test(n)||t.type.startsWith("public.")&&!/::(?:text|character varying|character)\b/.test(n)))return`.default(${j(s)})`;if(s!==void 0&&t.type==="jsonb"&&/^'(?:[^']|'')*'::jsonb$/.test(n))try{let r=JSON.stringify(JSON.parse(s));if(r===s&&!/"__proto__"\s*:/.test(s))return`.default(${r})`}catch{}return`.defaultSql(${j(n)})`}function fa(t){if(t.method!==void 0||t.where!==void 0||!t.keys.every(n=>"column"in n))return!1;let e=t.keys[0];return t.keys.every(n=>n.desc===e.desc&&n.nulls===e.nulls)}function ga(t){let e=t.keys[0],n=[`name: ${j(t.name)}`,`columns: [${t.keys.map(s=>j(s.column)).join(", ")}]`];return t.unique&&n.push("unique: true"),e.desc&&n.push("sort: 'desc'"),e.nulls&&n.push(`nulls: ${j(e.nulls)}`),t.include?.length&&n.push(`include: [${t.include.map(j).join(", ")}]`),`{ ${n.join(", ")} }`}function ha(t,e){let n=r=>`"${r.replace(/"/g,'""')}"`,s=e.keys.map(r=>`${"column"in r?n(r.column):r.expr}${r.desc?" DESC":""}${r.nulls?` NULLS ${r.nulls.toUpperCase()}`:""}`).join(", ");return`CREATE ${e.unique?"UNIQUE ":""}INDEX ${n(e.name)} ON ${n(t.schema)}.${n(t.name)}${e.method?` USING ${e.method}`:""} (${s})${e.include?.length?` INCLUDE (${e.include.map(n).join(", ")})`:""}${e.where?` WHERE ${e.where}`:""}`}function Ea(t,e,n){let s=`foreignKey(${j(e.name)}).on(${e.columns.map(r=>`c.col(${j(r)})`).join(", ")}).references(${n.arrow(e.refSchema,e.refTable,"TableHandle")} ${n.name(e.refSchema,e.refTable)}, ${e.refColumns.map(j).join(", ")})`;return e.onDelete!=="no action"&&(s+=`.onDelete(${j(e.onDelete)})`),e.onUpdate!=="no action"&&(s+=`.onUpdate(${j(e.onUpdate)})`),e.match==="full"&&(s+=".match('full')"),e.columns.length===1&&!ro(t,e.columns[0])&&(s+=".index(false)"),Ze(e.onDelete,e.onUpdate)&&!e.deferrable&&(s+=".deferrable(false)"),s}function ya(t,e){let n=`policy(${j(e.name)}).for(${j(e.for)}).to(${e.to.map(j).join(", ")})`;e.restrictive&&(n+=".as('restrictive')"),e.using!==void 0&&(n+=`.using(${j(e.using)})`),e.withCheck!==void 0&&(n+=`.withCheck(${j(e.withCheck)})`);let s=r=>t.primaryKey[0]===r||t.uniques.some(o=>o.columns[0]===r)||t.indexes.some(o=>o.where===void 0&&"column"in(o.keys[0]??{})&&o.keys[0].column===r);return ar(t,e).some(r=>!s(r)&&!t.indexes.some(o=>o.name===`${t.name}_${r}_idx`))&&(n+=".withoutIndexes()"),n}function lo(t,e){let n=t.prepare===void 0?void 0:Promise.resolve(e(t.prepare)),s=Promise.resolve(e(t.execute));s.catch(()=>{});let r=()=>s.catch(o=>{throw t.failed(o,!1),o});return n===void 0?r():n.then(r,o=>{throw t.failed(o,!0),o})}function mn(t){if(t==null)return null;switch(typeof t){case"string":return t;case"number":case"bigint":return String(t);case"boolean":return t?"true":"false";case"symbol":case"function":throw new TypeError(`a ${typeof t} is not a database value`)}return t instanceof Date?wa(t):t instanceof Uint8Array?`\\x${Buffer.from(t).toString("hex")}`:Array.isArray(t)&&co(t)?_n(t):JSON.stringify(t)}function co(t){return t.every(e=>e==null||typeof e!="object"&&typeof e!="function"&&typeof e!="symbol"||e instanceof Date||e instanceof Uint8Array||Array.isArray(e)&&co(e))}function _n(t){let e=n=>n==null?"NULL":Array.isArray(n)?_n(n):`"${String(mn(n)).replace(/(["\\])/g,"\\$1")}"`;return`{${t.map(e).join(",")}}`}function wa(t){if(Number.isNaN(t.getTime()))throw new TypeError("an invalid Date is not a database value");return t.toISOString()}var $a={json:{to:114,from:[114,3802],serialize:t=>t,parse:t=>JSON.parse(t)},boolean:{to:16,from:[16],serialize:t=>t,parse:t=>t==="t"},date:{to:1184,from:[1082,1114,1184],serialize:t=>t,parse:t=>new Date(t)},bytea:{to:17,from:[17],serialize:t=>t,parse:t=>Buffer.from(t.slice(2),"hex")}};function oo(t){let e=t;return e.length>0&&Array.isArray(e[e.length-1])?e[e.length-1]:e}var uo=/^[A-Za-z0-9:_-]{1,80}$/;function mo(t,e){let n=new Array(e.length).fill(!1),s="",r=0,o=0;for(;o<t.length;){let i=t.charCodeAt(o);if(i===39||i===34){let a=o+1;for(;;){if(a>=t.length||t.charCodeAt(a)===92)return;if(t.charCodeAt(a)===i){if(t.charCodeAt(a+1)!==i)break;a+=2}else a++}o=a+1;continue}if(i===36){let a=o+1,l=0;for(;a<t.length&&t.charCodeAt(a)>=48&&t.charCodeAt(a)<=57&&a-o<=6;)l=l*10+(t.charCodeAt(a++)-48);if(a===o+1||l<1||l>e.length||n[l-1])return;n[l-1]=!0;let c=e[l-1];if(c!==null&&typeof c!="string"||c!==null&&c.includes("\0"))return;s+=t.slice(r,o)+(c===null?"NULL":ne(c)),r=o=a;continue}if(i===59||i===92||i===45&&t.charCodeAt(o+1)===45||i===47&&t.charCodeAt(o+1)===42)return;o++}for(let i of n)if(!i)return;return s+t.slice(r)}function io(t){return Kn(t)?Object.assign(new Error("current transaction is aborted, commands ignored until end of transaction block",{cause:t}),{errno:"25P02",code:"ERR_POSTGRES_SERVER_ERROR"}):t}var Rt=10,bt=2;function po(t,e){let n={unsafe:(s,r)=>n.begin(o=>Promise.resolve(o.unsafe(s,r))),async begin(s,r){if(r?.tag!==void 0&&!uo.test(r.tag))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let o=`${r?.tag===void 0?"":`/* ${r.tag} */ `}BEGIN${r===void 0?"":`; ${r.sql}`}`,i=await t.reserve(),a=!0,l=!1,c=!1,d=null,w,u=!1,m=0,f=p=>(d=(async()=>{for(let S=1;;S++){l=!0;try{let R=await i.unsafe(p===void 0?o:`${o}; ${p}`).simple();if((R.length>0&&Array.isArray(R[0])?R[0]:R).command!=="BEGIN")throw new Error("palgres: the round trip that opens the transaction did not begin one");return r?.opened?.(R[R.length-(p===void 0?1:2)]),c=!0,p===void 0?void 0:R[R.length-1]}catch(R){let E=or(R);E&&(t.discard!==void 0?t.discard(i):Promise.resolve(i.close({timeout:0})).catch(()=>{}),a=!1,l=!1);let $=E?"unusable":Ee(R);if(u||$===void 0||S>=($==="never"?bt:Rt))throw w={error:R},R;E||(await Promise.resolve(i.close()).catch(()=>{}),i.release(),a=!1,l=!1);try{i=await t.reserve()}catch(A){throw w={error:A},A}a=!0}}})(),d.catch(()=>{}),d),h=()=>(d===null&&f(),d.then(()=>{},()=>{throw io(w.error)})),T={unsafe(p,S,R){if(w!==void 0)return Promise.reject(io(w.error));let E=R?.prepared,$=()=>E===void 0?i.unsafe(p,S):lo(E,A=>i.unsafe(A).simple());if(c)return $();if(d===null&&R?.inline===!0&&E===void 0){let A=mo(p,S??[]);if(A!==void 0)return f(A)}return h().then($)},async savepoint(p){await h();let S=`palgres_sp_${++m}`;await i.unsafe(`SAVEPOINT ${S}`).simple();let R;try{R=await p(T)}catch(E){throw await Promise.resolve(i.unsafe(`ROLLBACK TO SAVEPOINT ${S}; RELEASE SAVEPOINT ${S}`).simple()).catch(()=>{}),E}return await i.unsafe(`RELEASE SAVEPOINT ${S}`).simple(),R},abandon(){u||(u=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},g=async p=>{let S=await i.unsafe(p).simple();if(l=!1,p==="COMMIT"&&S.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 a statement of the transaction had failed")};try{let p;try{if(p=await s(T),await d?.catch(()=>{}),w!==void 0)throw w.error}catch(S){throw await d?.catch(()=>{}),l&&!u&&await g("ROLLBACK").catch(()=>{}),S}if(!l)return p;try{await g("COMMIT")}catch(S){throw l&&await g("ROLLBACK").catch(()=>{}),S}return p}finally{a&&(l&&!u&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(e!==void 0){let s=po(e);n.cancelBackend=ms(s),n.cancelOpening=go(s)}return n}var ds=1e3;async function fo(t,e){let n;try{await Promise.race([Promise.resolve(t.close({timeout:e})),new Promise(s=>{n=setTimeout(s,e*1e3+ds)})])}finally{clearTimeout(n)}}function Ta(t){let e=t(),n=0,s=!1,r=new WeakMap,o=new Map;return{get current(){return e},get renewals(){return n},unsafe:(i,a)=>e.unsafe(i,a),async reserve(){let i=e,a=await i.reserve();return r.set(a,i),a},discard(i){let a=r.get(i);if(a===e&&!s){e=t(),n++;let l=Promise.resolve(a.close()).catch(()=>{});o.set(a,l),l.then(()=>o.delete(a))}i.release()},async close(i){s=!0;let a=i?.timeout??0,l;try{await Promise.all([fo(e,a),Promise.race([Promise.all(o.values()),new Promise(c=>{l=setTimeout(c,a*1e3+ds)})])])}finally{clearTimeout(l)}}}}function go(t){return async e=>{if(!uo.test(e))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let n=`/* ${e} */`;return(await t.unsafe(`SELECT pg_cancel_backend(pid) AS cancelled FROM pg_stat_activity
|
|
375
|
+
});`}function ya(t,e,n,s,r,o,i,a,l,c,d){let y=`${F(t)}.${e.name}`,u,m=e.type,f=!1;m.endsWith("[]")&&(ma.has(m.slice(0,-2))||n.has(m.slice(0,-2)))&&(m=m.slice(0,-2),f=!0);let g=n.get(m),T=/^numeric\((\d+),(\d+)\)$/.exec(m);if(io[m]?u=io[m]:g&&g.schema===t.schema?(u=`enumType(${K(g.name)}, [${g.values.map(K).join(", ")}])`,s.add("enumType")):T?u=`numeric({ precision: ${T[1]}, scale: ${T[2]} })`:(u=`sqlType(${K(e.type)})`,s.add("sqlType"),f=!1),s.add(u.slice(0,u.indexOf("("))),f&&(u+=".array()"),o&&(u+=".primaryKey()"),e.identity&&(u+=e.identity==="always"?".identity()":".identity({ always: false })"),e.nullable&&!o&&(u+=".nullable()"),i&&(u+=".unique()"),e.generated&&(u+=`.generated(${K(e.generated.expr)}${e.generated.stored?", { stored: true }":""})`),e.default!==void 0&&(u+=wa(e,f)),a){let h=c.name(a.refSchema,a.refTable),p=[];d?.as!==void 0&&p.push(`as: ${K(d.as)}`),d?.reverseAs!==void 0&&p.push(`reverseAs: ${K(d.reverseAs)}`),a.onDelete!=="no action"&&p.push(`onDelete: ${K(a.onDelete)}`),a.onUpdate!=="no action"&&p.push(`onUpdate: ${K(a.onUpdate)}`),uo(t,e.name)||p.push("index: false"),en(a.onDelete,a.onUpdate)&&!a.deferrable&&p.push("deferrable: false"),u+=`.references(${c.arrow(a.refSchema,a.refTable,"AnyColumn")} ${h}.${lo(a.refColumns[0])}${p.length>0?`, { ${p.join(", ")} }`:""})`}return/^(owner|user_id|created_by|author_id|.*_user_id)$/.test(e.name)&&!a&&r.push(`column ${y} may hold a user's id: mark it ownedByUser() or userRef() so user.deleted reaches it`),u}function uo(t,e){let n=t.indexes.find(r=>r.name===`${t.name}_${e}_idx`);if(n===void 0||n.unique||n.where!==void 0||n.method!==void 0||n.include?.length||n.keys.length!==1)return!1;let s=n.keys[0];return"column"in s&&s.column===e&&!s.desc&&s.nulls===void 0}function wa(t,e){let n=t.default;if(n==="gen_random_uuid()")return".defaultRandom()";if(n==="now()"&&t.type==="timestamp with time zone"||n==="CURRENT_DATE"&&t.type==="date")return".defaultNow()";if(n==="true"||n==="false")return`.default(${n})`;if(/^-?\d+(\.\d+)?$/.test(n)&&(t.type==="integer"||t.type==="bigint"))return`.default(${n})`;if(n==="'{}'::text[]"||/^'\{\}'::/.test(n))return e?".default([])":`.defaultSql(${K(n)})`;let s=pa(n);if(s!==void 0&&(/^'(?:[^']|'')*'::text$/.test(n)||t.type.startsWith("public.")&&!/::(?:text|character varying|character)\b/.test(n)))return`.default(${K(s)})`;if(s!==void 0&&t.type==="jsonb"&&/^'(?:[^']|'')*'::jsonb$/.test(n))try{let r=JSON.stringify(JSON.parse(s));if(r===s&&!/"__proto__"\s*:/.test(s))return`.default(${r})`}catch{}return`.defaultSql(${K(n)})`}function $a(t){if(t.method!==void 0||t.where!==void 0||!t.keys.every(n=>"column"in n))return!1;let e=t.keys[0];return t.keys.every(n=>n.desc===e.desc&&n.nulls===e.nulls)}function Ta(t){let e=t.keys[0],n=[`name: ${K(t.name)}`,`columns: [${t.keys.map(s=>K(s.column)).join(", ")}]`];return t.unique&&n.push("unique: true"),e.desc&&n.push("sort: 'desc'"),e.nulls&&n.push(`nulls: ${K(e.nulls)}`),t.include?.length&&n.push(`include: [${t.include.map(K).join(", ")}]`),`{ ${n.join(", ")} }`}function Sa(t,e){let n=r=>`"${r.replace(/"/g,'""')}"`,s=e.keys.map(r=>`${"column"in r?n(r.column):r.expr}${r.desc?" DESC":""}${r.nulls?` NULLS ${r.nulls.toUpperCase()}`:""}`).join(", ");return`CREATE ${e.unique?"UNIQUE ":""}INDEX ${n(e.name)} ON ${n(t.schema)}.${n(t.name)}${e.method?` USING ${e.method}`:""} (${s})${e.include?.length?` INCLUDE (${e.include.map(n).join(", ")})`:""}${e.where?` WHERE ${e.where}`:""}`}function Ra(t,e,n){let s=`foreignKey(${K(e.name)}).on(${e.columns.map(r=>`c.col(${K(r)})`).join(", ")}).references(${n.arrow(e.refSchema,e.refTable,"TableHandle")} ${n.name(e.refSchema,e.refTable)}, ${e.refColumns.map(K).join(", ")})`;return e.onDelete!=="no action"&&(s+=`.onDelete(${K(e.onDelete)})`),e.onUpdate!=="no action"&&(s+=`.onUpdate(${K(e.onUpdate)})`),e.match==="full"&&(s+=".match('full')"),e.columns.length===1&&!uo(t,e.columns[0])&&(s+=".index(false)"),en(e.onDelete,e.onUpdate)&&!e.deferrable&&(s+=".deferrable(false)"),s}function ba(t,e){let n=`policy(${K(e.name)}).for(${K(e.for)}).to(${e.to.map(K).join(", ")})`;e.restrictive&&(n+=".as('restrictive')"),e.using!==void 0&&(n+=`.using(${K(e.using)})`),e.withCheck!==void 0&&(n+=`.withCheck(${K(e.withCheck)})`);let s=r=>t.primaryKey[0]===r||t.uniques.some(o=>o.columns[0]===r)||t.indexes.some(o=>o.where===void 0&&"column"in(o.keys[0]??{})&&o.keys[0].column===r);return pr(t,e).some(r=>!s(r)&&!t.indexes.some(o=>o.name===`${t.name}_${r}_idx`))&&(n+=".withoutIndexes()"),n}function ho(t,e){let n=t.prepare===void 0?void 0:Promise.resolve(e(t.prepare)),s=Promise.resolve(e(t.execute));s.catch(()=>{});let r=()=>s.catch(o=>{throw t.failed(o,!1),o});return n===void 0?r():n.then(r,o=>{throw t.failed(o,!0),o})}function pn(t){if(t==null)return null;switch(typeof t){case"string":return t;case"number":case"bigint":return String(t);case"boolean":return t?"true":"false";case"symbol":case"function":throw new TypeError(`a ${typeof t} is not a database value`)}return t instanceof Date?Na(t):t instanceof Uint8Array?`\\x${Buffer.from(t).toString("hex")}`:Array.isArray(t)&&go(t)?_n(t):JSON.stringify(t)}function go(t){return t.every(e=>e==null||typeof e!="object"&&typeof e!="function"&&typeof e!="symbol"||e instanceof Date||e instanceof Uint8Array||Array.isArray(e)&&go(e))}function _n(t){let e=n=>n==null?"NULL":Array.isArray(n)?_n(n):`"${String(pn(n)).replace(/(["\\])/g,"\\$1")}"`;return`{${t.map(e).join(",")}}`}function Na(t){if(Number.isNaN(t.getTime()))throw new TypeError("an invalid Date is not a database value");return t.toISOString()}var Aa={json:{to:114,from:[114,3802],serialize:t=>t,parse:t=>JSON.parse(t)},boolean:{to:16,from:[16],serialize:t=>t,parse:t=>t==="t"},date:{to:1184,from:[1082,1114,1184],serialize:t=>t,parse:t=>new Date(t)},bytea:{to:17,from:[17],serialize:t=>t,parse:t=>Buffer.from(t.slice(2),"hex")}};function mo(t){let e=t;return e.length>0&&Array.isArray(e[e.length-1])?e[e.length-1]:e}var Eo=/^[A-Za-z0-9:_-]{1,80}$/;function yo(t,e){let n=new Array(e.length).fill(!1),s="",r=0,o=0;for(;o<t.length;){let i=t.charCodeAt(o);if(i===39||i===34){let a=o+1;for(;;){if(a>=t.length||t.charCodeAt(a)===92)return;if(t.charCodeAt(a)===i){if(t.charCodeAt(a+1)!==i)break;a+=2}else a++}o=a+1;continue}if(i===36){let a=o+1,l=0;for(;a<t.length&&t.charCodeAt(a)>=48&&t.charCodeAt(a)<=57&&a-o<=6;)l=l*10+(t.charCodeAt(a++)-48);if(a===o+1||l<1||l>e.length||n[l-1])return;n[l-1]=!0;let c=e[l-1];if(c!==null&&typeof c!="string"||c!==null&&c.includes("\0"))return;s+=t.slice(r,o)+(c===null?"NULL":ne(c)),r=o=a;continue}if(i===59||i===92||i===45&&t.charCodeAt(o+1)===45||i===47&&t.charCodeAt(o+1)===42)return;o++}for(let i of n)if(!i)return;return s+t.slice(r)}function po(t){return Gn(t)?Object.assign(new Error("current transaction is aborted, commands ignored until end of transaction block",{cause:t}),{errno:"25P02",code:"ERR_POSTGRES_SERVER_ERROR"}):t}var bt=10,Nt=2;function wo(t,e){let n={unsafe:(s,r)=>n.begin(o=>Promise.resolve(o.unsafe(s,r))),async begin(s,r){if(r?.tag!==void 0&&!Eo.test(r.tag))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let o=`${r?.tag===void 0?"":`/* ${r.tag} */ `}BEGIN${r===void 0?"":`; ${r.sql}`}`,i=await t.reserve(),a=!0,l=!1,c=!1,d=null,y,u=!1,m=0,f=p=>(d=(async()=>{for(let S=1;;S++){l=!0;try{let b=await i.unsafe(p===void 0?o:`${o}; ${p}`).simple();if((b.length>0&&Array.isArray(b[0])?b[0]:b).command!=="BEGIN")throw new Error("palgres: the round trip that opens the transaction did not begin one");return r?.opened?.(b[b.length-(p===void 0?1:2)]),c=!0,p===void 0?void 0:b[b.length-1]}catch(b){let E=dr(b);E&&(t.discard!==void 0?t.discard(i):Promise.resolve(i.close({timeout:0})).catch(()=>{}),a=!1,l=!1);let $=E?"unusable":Ee(b);if(u||$===void 0||S>=($==="never"?Nt:bt))throw y={error:b},b;E||(await Promise.resolve(i.close()).catch(()=>{}),i.release(),a=!1,l=!1);try{i=await t.reserve()}catch(A){throw y={error:A},A}a=!0}}})(),d.catch(()=>{}),d),g=()=>(d===null&&f(),d.then(()=>{},()=>{throw po(y.error)})),T={unsafe(p,S,b){if(y!==void 0)return Promise.reject(po(y.error));let E=b?.prepared,$=()=>E===void 0?i.unsafe(p,S):ho(E,A=>i.unsafe(A).simple());if(c)return $();if(d===null&&b?.inline===!0&&E===void 0){let A=yo(p,S??[]);if(A!==void 0)return f(A)}return g().then($)},async savepoint(p){await g();let S=`palgres_sp_${++m}`;await i.unsafe(`SAVEPOINT ${S}`).simple();let b;try{b=await p(T)}catch(E){throw await Promise.resolve(i.unsafe(`ROLLBACK TO SAVEPOINT ${S}; RELEASE SAVEPOINT ${S}`).simple()).catch(()=>{}),E}return await i.unsafe(`RELEASE SAVEPOINT ${S}`).simple(),b},abandon(){u||(u=!0,Promise.resolve(i.close({timeout:0})).catch(()=>{}))}},h=async p=>{let S=await i.unsafe(p).simple();if(l=!1,p==="COMMIT"&&S.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 a statement of the transaction had failed")};try{let p;try{if(p=await s(T),await d?.catch(()=>{}),y!==void 0)throw y.error}catch(S){throw await d?.catch(()=>{}),l&&!u&&await h("ROLLBACK").catch(()=>{}),S}if(!l)return p;try{await h("COMMIT")}catch(S){throw l&&await h("ROLLBACK").catch(()=>{}),S}return p}finally{a&&(l&&!u&&await Promise.resolve(i.close()).catch(()=>{}),i.release())}}};if(e!==void 0){let s=wo(e);n.cancelBackend=fs(s),n.cancelOpening=To(s)}return n}var ps=1e3;async function $o(t,e){let n;try{await Promise.race([Promise.resolve(t.close({timeout:e})),new Promise(s=>{n=setTimeout(s,e*1e3+ps)})])}finally{clearTimeout(n)}}function Oa(t){let e=t(),n=0,s=!1,r=new WeakMap,o=new Map;return{get current(){return e},get renewals(){return n},unsafe:(i,a)=>e.unsafe(i,a),async reserve(){let i=e,a=await i.reserve();return r.set(a,i),a},discard(i){let a=r.get(i);if(a===e&&!s){e=t(),n++;let l=Promise.resolve(a.close()).catch(()=>{});o.set(a,l),l.then(()=>o.delete(a))}i.release()},async close(i){s=!0;let a=i?.timeout??0,l;try{await Promise.all([$o(e,a),Promise.race([Promise.all(o.values()),new Promise(c=>{l=setTimeout(c,a*1e3+ps)})])])}finally{clearTimeout(l)}}}}function To(t){return async e=>{if(!Eo.test(e))throw new Error(`palgres: an opening's tag is letters, digits, ":", "_" and "-"`);let n=`/* ${e} */`;return(await t.unsafe(`SELECT pg_cancel_backend(pid) AS cancelled FROM pg_stat_activity
|
|
376
376
|
WHERE state = 'active' AND left(query, $1::integer) = $2
|
|
377
|
-
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(n.length),n])).length>0}}function
|
|
377
|
+
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(n.length),n])).length>0}}function fs(t){return async(e,n,s)=>{await t.unsafe(`SELECT pg_cancel_backend(pid) FROM pg_stat_activity
|
|
378
378
|
WHERE pid = $1::integer AND backend_start = $2::timestamptz AND xact_start = $3::timestamptz
|
|
379
|
-
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(e),n,s])}}var Ue=class extends Error{constructor(e){super(`palgres: the driver ${e}. The engine sends every parameter as the text Postgres reads, and the driver must send it as it is \u2014 build Bun.SQL with { prepare: false } (Bun 1.4.2 or later) through bunDriver(), postgres.js with { types: POSTGRES_JS_TYPES } through postgresJsDriver()`),this.name="DriverRefused"}};async function
|
|
380
|
-
UPDATE ${fe}.queue q SET next_attempt_at = now() + interval '${
|
|
381
|
-
RETURNING q.id::text AS id, q.table_key, q.gen, q.row_id, q.enqueued_at::text AS enqueued_at`).then(L=>L.map(
|
|
379
|
+
AND usename = session_user AND datname = current_database() AND backend_type = 'client backend'`,[String(e),n,s])}}var Ue=class extends Error{constructor(e){super(`palgres: the driver ${e}. The engine sends every parameter as the text Postgres reads, and the driver must send it as it is \u2014 build Bun.SQL with { prepare: false } (Bun 1.4.2 or later) through bunDriver(), postgres.js with { types: POSTGRES_JS_TYPES } through postgresJsDriver()`),this.name="DriverRefused"}};async function hs(t){let n=(await t.unsafe("SELECT $1::jsonb AS j, $2::boolean AS b, $3::timestamptz = '2026-01-02 03:04:05.123456+00'::timestamptz AS t, array_length($4::int[], 1)::int AS a, $5::bytea = '\\x0102'::bytea AS y",['{"palgres":[1]}',"true","2026-01-02T03:04:05.123456Z","{1,2}","\\x0102"]))[0]??{},s=n.j;if(typeof s=="string"||!Array.isArray(s?.palgres))throw new Ue("re-encodes text bound for a jsonb parameter (JSON text became a JSON string)");if(n.b!==!0)throw new Ue("changes the text bound for a boolean ('true' was not read as true)");if(n.t!==!0)throw new Ue("changes the text bound for a timestamp (its microseconds did not arrive)");if(Number(n.a)!==2)throw new Ue("changes the text bound for an array (the literal {1,2} did not arrive)");if(n.y!==!0)throw new Ue("changes the text bound for a bytea");if((await t.begin(async o=>await o.unsafe("SELECT pg_catalog.current_setting('palgres.driver_opened', true) AS v"),{sql:"SELECT pg_catalog.set_config('palgres.driver_opened', 'yes', true)"}))[0]?.v!=="yes")throw new Ue("does not run the opening of a transaction (its role and its caller) before the work \u2014 every request would run as the login, no one's")}var ka=/\bdeallocate\b/i,Ia="SELECT EXISTS (SELECT FROM pg_catalog.pg_prepared_statements WHERE statement = 'commit' AND NOT from_sql) AS palgres_commit_kept",fo=()=>new Promise(()=>{});function La(t,e){let n=a=>Promise.resolve(a).then(l=>l),s=t.options?.prepare!==!1,r=a=>async(l,c)=>{for(let d=1;;d++){let y=!1,u=!1,m,f=p=>m!==void 0?Promise.reject(m.error):n(p()).catch(S=>{throw Ee(S)==="lost"&&(m??={error:S}),S}),g=(p,S)=>p.then(b=>m===void 0?b:(S(m.error),fo()),b=>m===void 0?Promise.reject(b):(S(b),fo())),T=p=>({unsafe:(S,b,E)=>(s&&ka.test(S)&&(u=!0),E?.prepared===void 0?f(()=>p.unsafe(S,b??[])):ho(E.prepared,$=>f(()=>p.unsafe($).simple()))),savepoint:S=>new Promise((b,E)=>{if(m!==void 0)return E(m.error);p.savepoint($=>g(S(T($)),E)).then(b,E)})}),h=a.begin(p=>g((async()=>{if(c!==void 0)if(s){let b=await f(()=>p.unsafe(`${c.sql}; ${Ia}`).simple());b.at(-1)?.[0]?.palgres_commit_kept!==!0&&(u=!0),c.opened?.(mo(b.slice(0,-1)))}else{let b=mo(await f(()=>p.unsafe(c.sql).simple()));c.opened?.(b)}y=!0;let S=await l(T(p));if(u){let[b]=await f(()=>p.unsafe("COMMIT; BEGIN").simple());if(b?.command==="ROLLBACK")throw new Error("palgres: COMMIT was answered with ROLLBACK \u2014 nothing the transaction did was kept")}return S})(),()=>{}));h.catch(p=>{Ee(p)==="lost"&&(m??={error:p})});try{return await h}catch(p){let S=Ee(p);if(y||S===void 0||d>=(S==="lost"?bt:Nt))throw p}}},o=r(t),i=r(e);return{unsafe:(a,l)=>o(c=>Promise.resolve(c.unsafe(a,l))),begin:o,cancelBackend:fs({unsafe:(a,l)=>i(c=>Promise.resolve(c.unsafe(a,l)))})}}var So=(t,e)=>({embed:t,serving:new Map,said:new Map,log:e}),Es=3e4,ys=`SELECT set_config('hnsw.iterative_scan', 'relaxed_order', true), set_config('hnsw.ef_search', '200', true), set_config('hnsw.max_scan_tuples', '200000', true), g.gen, g.model, g.dimensions, g.metric, (SELECT n.nspname FROM pg_catalog.pg_extension e JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector') AS types FROM (SELECT 1) one LEFT JOIN ${J}.generations g ON g.table_key = $1 AND g.status = 'active' ORDER BY g.gen DESC LIMIT 1`;function ws(t){if(!(t===void 0||t.gen===null||t.gen===void 0||typeof t.types!="string"))return{gen:Number(t.gen),model:String(t.model),dimensions:Number(t.dimensions),metric:t.metric,types:t.types}}var Ca=["hybrid","text","vector"],gs=(t,e)=>De(new Pe({fields:[{field:t,message:e}]},`search: ${t} ${e}`));function Ro(t,e,n){if(n===null||typeof n!="object")throw new TypeError(`search(${t}): its options are { limit, where, mode, minScore }`);if(typeof e!="string")throw new TypeError(`search(${t}): the query is the text searched for, not ${e===null?"null":typeof e}`);let s=e.trim().slice(0,Es);if(s==="")throw gs("query","is empty \u2014 say what to search for");let r=n.mode??"hybrid";if(typeof r!="string"||!Ca.includes(r))throw new TypeError(`search(${t}): mode is "hybrid", "text" or "vector", not ${typeof r=="string"?JSON.stringify(String(r).slice(0,40)):typeof r}`);let o=n.limit??20;if(typeof o!="number"||!Number.isFinite(o))throw gs("limit","must be a number");if(n.minScore!==void 0&&(typeof n.minScore!="number"||!Number.isFinite(n.minScore)))throw gs("minScore","must be a number");return{text:s,mode:r,limit:Math.min(Math.max(1,Math.trunc(o)),100),...n.minScore===void 0?{}:{minScore:n.minScore}}}function $s(t,e){if(!Array.isArray(t)||t.length!==e)throw new Error(`the embedder answered ${Array.isArray(t)?`a vector of ${t.length} dimensions`:"no vector"} where ${e} were asked for`);for(let n of t)if(typeof n!="number"||!Number.isFinite(n))throw new Error("the embedder answered a vector that holds what is not a number");return`[${t.join(",")}]`}async function bo(t,e,n){let s=await t({texts:[e],model:n.model,dimensions:n.dimensions,purpose:"query"});if(s===null||typeof s!="object"||!Array.isArray(s.vectors)||s.vectors.length!==1)throw new Error("the embedder answered no vector for the one text it was given");return $s(s.vectors[0],n.dimensions)}var No=100,va="2 minutes",xa=8,_a=256,Da=25e4,Ao=1e3,Pa=15e3,Fa=3e4,Ma=5e3,fe=J,At=t=>(t instanceof Error?t.message:String(t)).slice(0,500);function qa(t){let{sql:e,embed:n,log:s}=t,r={...mn,...t.roles},o=`SELECT set_config('role', ${ne(r.service)}, true), set_config('search_path', 'pg_catalog, pg_temp', true), set_config('datestyle', 'ISO, YMD', true), set_config('lock_timeout', '5s', true), set_config('statement_timeout', '60s', true)`,i=I=>e.begin(L=>I(async(k,x=[])=>await L.unsafe(k,x.map(pn))),{sql:o}),a=(I,L)=>i(k=>k(I,L)),l=!0,c=I=>a(`WITH due AS (SELECT id FROM ${fe}.queue WHERE next_attempt_at <= now() ORDER BY enqueued_at, id LIMIT ${I} FOR UPDATE SKIP LOCKED)
|
|
380
|
+
UPDATE ${fe}.queue q SET next_attempt_at = now() + interval '${va}' FROM due WHERE q.id = due.id
|
|
381
|
+
RETURNING q.id::text AS id, q.table_key, q.gen, q.row_id, q.enqueued_at::text AS enqueued_at`).then(L=>L.map(k=>({id:String(k.id),table_key:String(k.table_key),gen:Number(k.gen),row_id:String(k.row_id),enqueued_at:String(k.enqueued_at)})));async function d(I,L){let[k]=await a(`SELECT g.model, g.dimensions, g.metric, g.from_columns, t.rel::text AS parent, a.attname AS pk, format_type(a.atttypid, a.atttypmod) AS pk_type,
|
|
382
382
|
(SELECT n.nspname FROM pg_extension e JOIN pg_namespace n ON n.oid = e.extnamespace WHERE e.extname = 'vector') AS types
|
|
383
383
|
FROM ${fe}.generations g
|
|
384
384
|
CROSS JOIN LATERAL (SELECT to_regclass(format('%I.%I', split_part(g.table_key, '.', 1), substr(g.table_key, strpos(g.table_key, '.') + 1))) AS rel) t
|
|
385
385
|
JOIN pg_index i ON i.indrelid = t.rel AND i.indisprimary AND i.indnkeyatts = 1
|
|
386
386
|
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0]
|
|
387
|
-
WHERE g.table_key = $1 AND g.gen = $2::integer AND g.status <> 'retired'`,[
|
|
388
|
-
next_attempt_at = CASE WHEN q.attempts + 1 >= ${
|
|
389
|
-
FROM ${
|
|
390
|
-
there AS (SELECT p.${
|
|
387
|
+
WHERE g.table_key = $1 AND g.gen = $2::integer AND g.status <> 'retired'`,[I,L]);if(k===void 0||typeof k.types!="string")return;let x=Number(k.dimensions),R=k.metric;return{model:String(k.model),dimensions:x,metric:R,from:k.from_columns.map(String),parent:String(k.parent),pk:N(String(k.pk)),pkType:String(k.pk_type),vectors:`${fe}.${N(Be(I,L))}`,vectorType:`${N(k.types)}.${On(x,R).type}`}}let y="unnest($1::bigint[], $2::timestamptz[]) AS c(id, at) WHERE q.id = c.id AND q.enqueued_at = c.at",u=I=>[I.map(L=>L.id),I.map(L=>L.enqueued_at)],m=I=>a(`DELETE FROM ${fe}.queue q USING ${y}`,u(I)),f=async(I,L)=>{I.length!==0&&(s?.(`palgres: search of ${I[0].table_key}: ${I.length} row(s) not embedded, tried again later (${At(L)})`),await a(`UPDATE ${fe}.queue q SET attempts = q.attempts + 1, last_error = $3,
|
|
388
|
+
next_attempt_at = CASE WHEN q.attempts + 1 >= ${xa} THEN 'infinity'::timestamptz ELSE now() + interval '1 minute' * power(4, least(q.attempts, 4)) END
|
|
389
|
+
FROM ${y}`,[...u(I),At(L)]))};async function g(I,L,k,x){let R=[],_=[],P=0;for(let C of L){let W=Math.ceil(C.text.length/4);_.length>0&&(_.length>=_a||P+W>Da)&&(R.push(_),_=[],P=0),_.push(C),P+=W}_.length>0&&R.push(_);let B=(C,W)=>(x.failed+=C.length,f(C.map(M=>M.row),W)),w=async C=>{if(C.length===0)return;let W=Math.ceil(C.length/2);await O(C.slice(0,W)),W<C.length&&await O(C.slice(W))},O=async C=>{if(x.down)return B(C,new Error("the embedder is not answering"));let W,M;try{let j=await n({texts:C.map(U=>U.text),model:I.model,dimensions:I.dimensions,purpose:"document"});if(j===null||typeof j!="object"||!Array.isArray(j.vectors)||j.vectors.length!==C.length)throw new Error(`the embedder answered ${Array.isArray(j?.vectors)?j.vectors.length:"no"} vector(s) for ${C.length} text(s)`);W=j.vectors.map(U=>$s(U,I.dimensions)),M=typeof j.model=="string"&&j.model!==""?j.model:I.model}catch(j){return C.length===1?B(C,j):x.answered?w(C):(await O([C[0]]),await O([C[C.length-1]]),x.answered?w(C.slice(1,-1)):(x.down=!0,B(C.slice(1,-1),j)))}x.answered=!0,await k(C,M,W)};for(let C of R)await O(C)}async function T(I,L){let k=await d(I[0].table_key,I[0].gen);if(k===void 0)return await m(I),0;let x=new Map((await a(`SELECT p.${k.pk}::text AS id, ${it(k.from,"p")} AS text FROM ${k.parent} p WHERE p.${k.pk} = ANY($1::${k.pkType}[])`,[I.map(w=>w.row_id)])).map(w=>[String(w.id),String(w.text??"")])),R=I.filter(w=>!x.has(w.row_id));R.length>0&&await m(R);let _=I.filter(w=>x.has(w.row_id)&&x.get(w.row_id).trim()==="");_.length>0&&await a(`WITH done AS (DELETE FROM ${fe}.queue q USING ${y} RETURNING q.row_id) DELETE FROM ${k.vectors} v USING done d WHERE v.id = d.row_id::${k.pkType}`,u(_));let P=I.filter(w=>(x.get(w.row_id)??"").trim()!=="").map(w=>({row:w,text:x.get(w.row_id).slice(0,Es)})),B=0;return await g(k,P,async(w,O,C)=>{try{let[W]=await a(`WITH done AS (DELETE FROM ${fe}.queue q USING ${y} RETURNING q.row_id),
|
|
390
|
+
there AS (SELECT p.${k.pk}::text AS id FROM ${k.parent} p WHERE p.${k.pk} = ANY($3::${k.pkType}[]) FOR KEY SHARE),
|
|
391
391
|
written AS (
|
|
392
|
-
INSERT INTO ${
|
|
393
|
-
SELECT s.id::${
|
|
392
|
+
INSERT INTO ${k.vectors} (id, embedding, model)
|
|
393
|
+
SELECT s.id::${k.pkType}, s.embedding::${k.vectorType}, $5::text
|
|
394
394
|
FROM unnest($6::text[], $4::text[]) AS s(id, embedding) JOIN done d ON d.row_id = s.id JOIN there ON there.id = s.id
|
|
395
395
|
ON CONFLICT (id) DO UPDATE SET embedding = EXCLUDED.embedding, model = EXCLUDED.model, embedded_at = now()
|
|
396
396
|
RETURNING 1)
|
|
397
|
-
SELECT count(*)::int AS n FROM written`,[...u(
|
|
397
|
+
SELECT count(*)::int AS n FROM written`,[...u(w.map(M=>M.row)),w.map(M=>M.row.row_id),C,O,w.map(M=>M.row.row_id)]);B+=Number(W?.n??0)}catch(W){L.failed+=w.length,await f(w.map(M=>M.row),W)}},L),B}async function h(I){let L=0,k=await a(`SELECT g.table_key, g.gen FROM ${fe}.generations g WHERE g.status = 'filling' AND NOT EXISTS (SELECT 1 FROM ${fe}.queue q WHERE q.table_key = g.table_key AND q.gen = g.gen) ORDER BY 1, 2`);for(let x of k){let R=String(x.table_key),_=Number(x.gen),P=await d(R,_);if(P===void 0)continue;let[B]=await a(`WITH missing AS (
|
|
398
398
|
INSERT INTO ${fe}.queue (table_key, gen, row_id)
|
|
399
|
-
SELECT $1::text, $2::integer, p.${
|
|
400
|
-
WHERE btrim(${
|
|
399
|
+
SELECT $1::text, $2::integer, p.${P.pk}::text FROM ${P.parent} p
|
|
400
|
+
WHERE btrim(${it(P.from,"p")}) <> '' AND NOT EXISTS (SELECT 1 FROM ${P.vectors} v WHERE v.id = p.${P.pk})
|
|
401
401
|
ON CONFLICT ON CONSTRAINT queue_one_pending DO NOTHING RETURNING 1)
|
|
402
|
-
SELECT count(*)::int AS n FROM missing`,[y,k]);if(Number(P?.n??0)>0){L+=Number(P.n);continue}let[C]=await a(`SELECT ${fe}.promote($1) AS gen`,[y]);C?.gen!==null&&C?.gen!==void 0&&(O.push(y),s?.(`palgres: search of ${y}: every row is embedded again \u2014 generation ${String(C.gen)} serves`))}return L}async function p(O={}){let L=O.timeoutMs===void 0?1/0:Date.now()+O.timeoutMs,N=[],_=0,y=()=>Date.now()<L&&(O.max===void 0||_<O.max)&&!(O.whileRunning===!0&&l);for(;;){for(;y();){let k=await c(O.max===void 0?wo:Math.min(wo,O.max-_));if(k.length===0)break;let D=new Map;for(let v of k){let I=`${v.table_key}\0${v.gen}`,B=D.get(I);B?B.push(v):D.set(I,[v])}let P={answered:!1,down:!1,failed:0},C=0;for(let v of D.values())try{C+=await T(v,P)}catch(I){P.failed+=v.length,await f(v,I).catch(()=>{})}if(_+=C,C===0&&P.failed>0)return{embedded:_,promoted:N}}if(!y()||await g(N)===0)break}return{embedded:_,promoted:N}}let S,R,E=!1,$,A=()=>{E=!0,R?.()};return{drain:O=>p(O),kick:A,start(){S===void 0&&(l=!1,$=ut.listen(A),S=(async()=>{await a(`UPDATE ${fe}.queue SET attempts = 0, next_attempt_at = now(), last_error = NULL WHERE next_attempt_at = 'infinity'`).catch(L=>s?.(`palgres: the search worker could not read its queue (${Nt(L)})`));let O=$o;for(;!l;){E=!1;let L=!1;try{let N=await p({timeoutMs:Ca,whileRunning:!0});L=N.embedded>0||N.promoted.length>0}catch(N){s?.(`palgres: the search worker could not embed (${Nt(N)}); it looks again`)}O=L?$o:Math.min(Ia,O*2),!(l||E)&&(await new Promise(N=>{let _=setTimeout(N,O);_.unref?.(),R=()=>{clearTimeout(_),N()}}),R=void 0)}})())},async stop(){if(S===void 0)return;l=!0,$?.(),$=void 0,R?.();let O=S;S=void 0;let L;await Promise.race([O,new Promise(N=>L=setTimeout(N,va))]),clearTimeout(L)}}}var ws=class{options;active=0;queued=0;tenants=new Map;pending=new Map;lastTenant;accepted=0;rejected={full:0,timeout:0,cancelled:0};limit;timeout;nestedLimit;nestedActive=0;nestedPending=new Set;constructor(e){if(this.options=e,this.limit=e.queueLimit??Math.min(512,Math.max(32,e.concurrency*8)),this.timeout=e.queueTimeoutMs??1e3,this.nestedLimit=e.nestedConcurrency??e.concurrency*2,!Number.isSafeInteger(e.concurrency)||e.concurrency<1||!Number.isSafeInteger(this.nestedLimit)||this.nestedLimit<1||!Number.isSafeInteger(this.limit)||this.limit<0||this.limit>1e4||!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>6e4)throw new Error("Invalid database pool or queue deployment settings")}get queueTimeoutMs(){return this.timeout}get snapshot(){return{active:this.active,queued:this.queued,nested:{active:this.nestedActive,queued:this.nestedPending.size},tenants:this.tenants.size,accepted:this.accepted,rejected:{...this.rejected}}}nestedLease(e){this.nestedActive++;let n=!1;return{queueMs:performance.now()-e,release:()=>{if(n)return;n=!0,this.nestedActive--;let s=this.nestedPending.values().next().value;s&&(this.nestedPending.delete(s),s.cleanup(),s.grant(this.nestedLease(s.entered)))}}}acquireNested(e){let n=performance.now();return this.nestedActive<this.nestedLimit?Promise.resolve(this.nestedLease(n)):new Promise((s,r)=>{let o={grant:s,reject:r,entered:n,cleanup(){}},i=(c,d)=>{this.nestedPending.delete(o)&&(o.cleanup(),this.rejection(c),r(d))},a=()=>i("cancelled",e?.reason??new Error("Database admission cancelled")),l=setTimeout(()=>i("timeout",new Me({retryAfter:1},"Database queue deadline exceeded")),this.timeout);o.cleanup=()=>{clearTimeout(l),e?.removeEventListener("abort",a)},this.nestedPending.add(o),e?.addEventListener("abort",a,{once:!0}),e?.aborted&&a()})}rejection(e){this.rejected[e]++;try{this.options.onReject?.({reason:e,active:this.active,queued:this.queued})}catch{}}take(e,n){this.active++,this.accepted++,this.lastTenant=e,this.tenants.set(e,(this.tenants.get(e)??0)+1);let s=!1;return{queueMs:performance.now()-n,release:()=>{if(s)return;s=!0,this.active--;let r=(this.tenants.get(e)??1)-1;r?this.tenants.set(e,r):this.tenants.delete(e),this.drain()}}}drain(){for(;this.active<this.options.concurrency&&this.queued;){let e=this.pending.keys().next().value;if(this.pending.size>1&&e===this.lastTenant){let r=this.pending.get(e);this.pending.delete(e),this.pending.set(e,r),e=this.pending.keys().next().value}let n=this.pending.get(e),s=n.values().next().value;n.delete(s),this.pending.delete(e),n.size&&this.pending.set(e,n),this.queued--,s.cleanup(),s.grant(this.take(e,s.entered))}}async acquire(e,n,s={}){if(n?.aborted)throw this.rejection("cancelled"),n.reason??new Error("Database admission cancelled");if(s.nested)return this.acquireNested(n);let r=this.options.tenantClaim?e[this.options.tenantClaim]:e.sub,o=typeof r=="string"&&r.length?r:"__anonymous__",i=performance.now();if(this.active<this.options.concurrency&&!this.queued)return this.take(o,i);if(!s.returning&&this.queued>=this.limit)throw this.rejection("full"),new Me({retryAfter:1},"Database queue is full");return new Promise((a,l)=>{let c=this.pending.get(o)??new Set;this.pending.has(o)||this.pending.set(o,c);let d={grant:a,reject:l,entered:i,cleanup(){}},w=(f,h)=>{c.delete(d)&&(c.size||this.pending.delete(o),this.queued--,d.cleanup(),this.rejection(f),l(h),this.drain())},u=()=>w("cancelled",n?.reason??new Error("Database admission cancelled")),m=setTimeout(()=>w("timeout",new Me({retryAfter:1},"Database queue deadline exceeded")),this.timeout);if(d.cleanup=()=>{clearTimeout(m),n?.removeEventListener("abort",u)},s.returning){d.returning=!0;let f=[...c];c.clear();for(let h of f)h.returning&&c.add(h);c.add(d);for(let h of f)h.returning||c.add(h)}else c.add(d);this.queued++,n?.addEventListener("abort",u,{once:!0}),n?.aborted?u():this.drain()})}},To=new WeakMap;function So(t,e={concurrency:10}){let n=To.get(t);if(!n)return n=new ws(e),To.set(t,n),n;for(let s of["concurrency","queueLimit","queueTimeoutMs","tenantClaim"])if(e[s]!==n.options[s])throw new Error("Database admission cannot be reconfigured while its pool is shared");return n}function _a(t){return t.endsWith("_id")?t.slice(0,-3):t}function Ro(t){return t.direction==="forward"?`the foreign key "${t.table}.${t.column}"`:`the reverse of "${t.table}.${t.column}"`}function bo(t){return t.direction==="reverse"?'references(() => \u2026, { reverseAs: "\u2026" })':t.def.selfRefColumn!==void 0?'selfReferences("\u2026", { as: "\u2026" })':'references(() => \u2026, { as: "\u2026" })'}function Dn(t){let e=new Map,n=new Map;for(let r of t)for(let o of Object.values(r.tables)){let i=be(r.name,o.name);e.set(i,[]),n.set(i,new Map)}let s=(r,o,i,a)=>{let l=n.get(r);if(l===void 0)return;let c=l.get(o);if(c!==void 0){let d=bo(c),w=bo(i),u=d===w?`rename one of them: ${d}`:`rename one of them \u2014 "${c.table}.${c.column}": ${d}; "${i.table}.${i.column}": ${w}`;throw new Ge([`table "${r}": ${Ro(c)} and ${Ro(i)} both resolve to the relation name "${o}" \u2014 ${u}`])}l.set(o,i),e.get(r)?.push(a)};for(let r of t)for(let o of Object.values(r.tables)){let i=be(r.name,o.name);for(let[a,l]of Object.entries(o.columns)){let c=l._def;if(c.references===void 0)continue;let d=c.references.table,w=c.refAs??_a(a);if(s(i,w,{table:o.name,column:a,direction:"forward",def:c},{name:w,to:d,kind:"one",via:a}),!e.has(d)||d===i)continue;let u=c.reverseAs??o.name;s(d,u,{table:o.name,column:a,direction:"reverse",def:c},{name:u,to:i,kind:"many",via:a})}}return e}function Da(t){let e=t.columns??{},n=[],s=[];for(let[i,a]of Object.entries(e)){let l=a&&typeof a=="object"&&"_def"in a?a._def:a;l?.primaryKey&&n.push(i),l?.unique&&s.push([i])}let r=t.primaryKey??n;r.length&&s.unshift([...r]);for(let i of t.unique??[])s.push([...i.columns]);let o=new Set;return s.filter(i=>{if(!i.length||new Set(i).size!==i.length||i.some(l=>!Object.hasOwn(e,l)))throw new Error("Unique lookup requires a nonempty declared key of distinct, known columns");let a=JSON.stringify([...i].sort());return o.has(a)?!1:(o.add(a),!0)})}function At(t){let e=Object.fromEntries(Object.entries(t.columns).filter(([,n])=>n?._def?.ignored!==!0));return Da({columns:e,primaryKey:t.primaryKey,unique:t.unique})}function No(t,e,n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`findUnique(${t}): where must contain one declared unique key`);let s=Object.keys(n);if(!e.some(r=>r.length===s.length&&r.every(o=>Object.hasOwn(n,o))))throw new Error(`findUnique(${t}): supply exactly one declared unique key (${e.map(r=>r.join(" + ")).join("; ")||"none declared"}); use findMany for other filters`);for(let[r,o]of Object.entries(n))if(o==null||typeof o=="object"&&!(o instanceof Date)||typeof o=="function"||typeof o=="symbol")throw new Error(`findUnique(${t}): ${r} requires a non-null scalar equality value`)}var q=t=>`"${t.replace(/"/g,'""')}"`;function Lo(t){return t.type==="sql"&&typeof t.sqlType=="string"?`sql:${t.sqlType}`:t.type}var Ot=class{version;tables=new Map;ignoredTables=new Set;schemas;deferrals;fields;constructor(e,n,s=null){this.version=n.version,this.schemas=e,this.fields=s;let r=Dn(e);for(let o of e)for(let i of Object.values(o.tables)){let a=be(o.name,i.name);if(i.ignored){this.ignoredTables.add(a);continue}this.tables.set(a,Ma(o.name,i,a,n,r.get(a)??[],s))}}encryptedColumns(){return[...this.tables.values()].flatMap(e=>[...e.encrypted].map(([n,s])=>({table:e,column:n,encrypted:s})))}table(e,n){let s=this.tables.get(e);if(s)return s;throw this.ignoredTables.has(e)?new Error(`${n}(${e}): the table is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${n}(${e}): no such table in this version's schema (a table outside public is "schema.table")`)}deferral(e){return this.deferrals??=Pa(ir([...this.schemas])),this.deferrals.get(`${e.schema}.${e.name}`)??null}};function Pa(t){let e=(o,i)=>`${o}.${i}`,n=new Map,s=new Map;for(let o of t.tables)for(let i of o.foreignKeys){let a=e(i.refSchema,i.refTable);i.onDelete==="cascade"&&n.set(a,[...n.get(a)??[],e(o.schema,o.name)]),i.deferrable&&s.set(a,[...s.get(a)??[],e(o.schema,i.name)])}let r=new Map;for(let o of t.tables){let i=new Set([e(o.schema,o.name)]);for(let c of i)for(let d of n.get(c)??[])i.add(d);let a=[...new Set([...i].flatMap(c=>s.get(c)??[]))].sort();if(a.length===0)continue;let l=`ARRAY[${a.map(x).join(", ")}]::text[]`;r.set(e(o.schema,o.name),{defer:`SELECT palgres.defer_keys(${l}, true)`,check:`SELECT palgres.defer_keys(${l}, false)`})}return r}function Ma(t,e,n,s,r,o){let i=new Map,a=new Set,l=[],c=new Map,d=new Set,w=new Map;for(let[m,f]of Object.entries(e.columns)){let h=f._def;if(h.ignored){a.add(m);continue}i.set(m,h),h.primaryKey&&l.push(m);let T=an(t,e.name,m);if(h.encrypted!==void 0){if(o===null)throw new Error(`${n}.${m} is .encrypted(): the engine needs the project's fields to seal and open it \u2014 createDatabase({ fields }) (palbase/backend gives it)`);w.set(m,{address:T,lookup:h.encrypted.lookup?js(m):null}),c.set(m,{fromDb:g=>Fa(o,T,g)});continue}if(o!==null&&h.type==="text"&&o.sealing.get(T)?.direction==="open"){c.set(m,{fromDb:g=>typeof g=="string"&&o.sealing.get(T)!==void 0&&o.cipher.isEncrypted(g)?o.cipher.decrypt(T,g):g,toDb:g=>(o.sealing.get(T)!==void 0&&tt(T,g),g)});continue}if(typeof h.codec=="string"&&h.codec in sn){let g=sn[h.codec];c.set(m,{fromDb:g.fromDb,toDb:g.toDb})}else h.transform!==void 0&&c.set(m,h.transform);(h.identity==="always"||h.generated!==void 0)&&d.add(m)}let u=e.primaryKey??l;return{key:n,schema:t,name:e.name,sql:t==="public"?q(e.name):`${q(s.schema(t))}.${q(e.name)}`,columns:i,ignored:a,primaryKey:u,singleKey:u.length===1?u[0]:null,uniqueKeys:At(e),transforms:c,databaseOnly:d,relations:r,projections:new Map,...e.search!==void 0?{search:{key:`${t}.${e.name}`,from:[...e.search.from]}}:{},encrypted:w,fields:o}}function Fa(t,e,n){if(typeof n!="string")return n;if(t.sealing.get(e)===void 0)return t.cipher.decrypt(e,n);if(!t.cipher.isEncrypted(n))return n;try{return t.cipher.decrypt(e,n)}catch{return n}}function Ao(t){return`CASE WHEN isfinite(${t}) AND extract(year FROM ${t} AT TIME ZONE 'UTC') BETWEEN 1 AND 9999 THEN to_char(${t} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') ELSE ${t}::text END`}function Oo(t){return`CASE WHEN isfinite(${t}) AND extract(year FROM ${t}) BETWEEN 1 AND 9999 THEN to_char(${t}, 'YYYY-MM-DD') ELSE ${t}::text END`}function ko(t,e){return`CASE WHEN ${t} IS NULL THEN NULL ELSE ARRAY(SELECT ${e("u.e")} FROM unnest(${t}) WITH ORDINALITY AS u(e, i) ORDER BY u.i) END`}function ze(t,e){if(t!==null&&t.startsWith("sql:")){let n=t.slice(4);return Gn.has(n)||Xn.has(n)?null:`CASE WHEN ${e} IS NULL THEN NULL ELSE format('%s', ${e}) END`}switch(t){case"timestamp":return Ao(e);case"date":return Oo(e);case"bigint[]":case"numeric[]":case"uuid[]":case"enum[]":return`${e}::text[]`;case"date[]":return ko(e,Oo);case"timestamp[]":return ko(e,Ao)}return null}function Io(t){return t==="jsonb"||t==="sql:json"}import{createCipheriv as qa,createDecipheriv as Ua,createHash as Co,randomBytes as Ba}from"node:crypto";var Ne=(t,e="page")=>new Pe({fields:[{field:e,message:t}]},t);function vo(t){return Co("sha256").update("palbase:cursor:v1\0").update(t).digest()}function $s(t){let e=n=>typeof n=="bigint"?{$bigint:n.toString()}:n instanceof Date?{$date:n.toISOString()}:Array.isArray(n)?n.map(e):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(s=>[s,e(n[s])])):n;return Co("sha256").update(JSON.stringify(e(t))).digest("base64url")}function xo(t,e){let{iat:n,exp:s,nbf:r,jti:o,...i}=e;return $s({role:t,authorization:i})}function _o(t,e,n){let s=Ba(12),r=qa("aes-256-gcm",t,s);r.setAAD(Buffer.from(e));let o=Buffer.concat([r.update(JSON.stringify(n),"utf8"),r.final()]),i=`p1.${Buffer.concat([s,r.getAuthTag(),o]).toString("base64url")}`;if(i.length>16384)throw Ne("page cursor values are too large; choose shorter ordering columns");return i}function Do(t,e,n,s){try{if(typeof n!="string"||n.length>16384||!/^p1\.[\w-]+$/.test(n))throw new Error;let r=Buffer.from(n.slice(3),"base64url");if(r.length<30||r.toString("base64url")!==n.slice(3))throw new Error;let o=Ua("aes-256-gcm",t,r.subarray(0,12));o.setAAD(Buffer.from(e)),o.setAuthTag(r.subarray(12,28));let i=JSON.parse(Buffer.concat([o.update(r.subarray(28)),o.final()]).toString("utf8"));if(!Array.isArray(i)||i.length!==s||i.some(a=>a!==null&&typeof a!="string"))throw new Error;return i}catch{throw Ne("Invalid cursor for this query or identity; restart from the first page","cursor")}}var Wa=new Set(["uuid","text","integer","bigint","boolean","timestamp","numeric","enum"]);function Po(t,e,n){let s=n;if("limit"in s||"offset"in s)throw Ne("page uses first/after or last/before, not limit/offset");let r=n.last!==void 0||n.before!==void 0;if(r&&(n.first!==void 0||n.after!==void 0))throw Ne("Use first/after or last/before in one page request");let o=(r?n.last:n.first)??50;if(!Number.isInteger(o)||o<1||o>1e3)throw Ne("page size must be an integer between 1 and 1000");if(e.length===0)throw new Error("page requires a declared primary key for a unique, stable ordering");Y(n.orderBy,"orderBy","the order");let i=n.orderBy===void 0?[]:Array.isArray(n.orderBy)?n.orderBy:[n.orderBy];if(i.length>16)throw Ne("page supports at most 16 ordering columns");let a=new Set,l=[],c=d=>{Y(d,"orderBy","the order");let w=t[d?.column];if(!Object.hasOwn(t,d?.column)||!w)throw Ne(`page order column ${d?.column} is not declared`);if(!Wa.has(w.type??""))throw Ne(`page cannot order ${d.column}: ${w.type??"unknown"} is not a supported scalar column`);if(a.has(d.column))throw Ne(`page order column ${d.column} is repeated`);if(d.direction!==void 0&&d.direction!=="asc"&&d.direction!=="desc")throw Ne("page direction must be asc or desc");if(d.nulls!==void 0&&d.nulls!=="first"&&d.nulls!=="last")throw Ne("page nulls must be first or last");let u=d.direction??"asc";a.add(d.column),l.push({column:d.column,direction:u,nulls:d.nulls??(u==="asc"?"last":"first"),nullable:w.nullable!==!1})};for(let d of i)c(d);for(let d of e)a.has(d)||c({column:d,direction:l.at(-1)?.direction??"asc"});return{order:l,size:o,backward:r,token:r?n.before:n.after}}function Ts(t,e,n,s,r,o=!1){let i=e.map(c=>s(c));if(t.every(c=>!c.nullable&&c.direction===t[0].direction)&&e.every(c=>c!==null)){let c=t[0].direction==="asc"!==n;return`(${t.map(d=>r(d.column)).join(", ")}) ${c?">":"<"}${o?"=":""} (${i.join(", ")})`}let a=[],l=[];for(let c=0;c<t.length;c++){let d=t[c],w=r(d.column),u=i[c],m=d.nulls==="last"!==n,f=d.direction==="asc"!==n?">":"<",h=e[c]===null?m?"false":`${w} IS NOT NULL`:`(${w} ${f} ${u}${m?` OR ${w} IS NULL`:""})`;a.push(`(${[...l,h].join(" AND ")})`),l.push(`${w} IS NOT DISTINCT FROM ${u}`)}return o&&a.push(`(${l.join(" AND ")})`),`(${a.join(" OR ")})`}import{randomBytes as ja}from"node:crypto";var Ha=16,Ka=2,Mo="force_custom_plan",Ga=16384,Xa=256,Va=2e3,Ya=256,Ja=/^\s*(?:\(\s*)*(?:select|insert|update|delete|merge|values|with|table)\b/i,za=/\bdeallocate\b/i,Qa=/'\s*(?:now|today|tomorrow|yesterday)\s*'/i;function Fo(t){return za.test(t)}function Za(t,e){if(t.length>Ga||!Ja.test(t)||Qa.test(t))return;let n=e?t:t.replace(/;\s*$/,"");if(!n.includes(";")&&!(!e&&n.includes("*")))return n}function qo(t,e,n){if(!(e.length===0||e.length>Xa)){for(let s of e)if(s!==null&&(typeof s!="string"||s.includes("\0")))return;return Za(t,n)}}var el=0,nl=0,Uo=ja(5).toString("hex"),kt=class{texts=new Map;sessions=new Map;mark(){return`${Uo}_${++nl}`}on(e){let n=this.sessions.get(e);return n!==void 0?this.sessions.delete(e):n=new Ss(this),this.sessions.set(e,n),this.sessions.size>Ya&&this.sessions.delete(this.sessions.keys().next().value),n}count(e,n,s){qo(e,n,s)!==void 0&&this.sent(e)}sent(e){let n=(this.texts.get(e)??0)+1;return this.texts.delete(e),this.texts.set(e,n),this.texts.size>Va&&this.texts.delete(this.texts.keys().next().value),n}},Ss=class{statements=new Map;refused=0;all;constructor(e){this.all=e}get size(){return this.statements.size+this.refused}run(e,n,s){let r=qo(e,n,s);if(r===void 0)return;let o=this.all.sent(e),i=this.statements.get(e),a;if(i===void 0){if(o<Ka||this.size>=Ha)return;i=`palgres_${Uo}_${++el}`,a=`PREPARE ${i} (${n.map(()=>"unknown").join(", ")}) AS ${r}`,this.statements.set(e,i)}let l=i,c=r.includes("/*")||r.includes("*/")?"":`/* ${r} */ `;return{prepare:a,execute:`${c}EXECUTE ${i}(${n.map(d=>d===null?"NULL":ne(d)).join(", ")})`,failed:(d,w)=>this.failed(e,l,d,w)}}forget(){this.statements.clear(),this.refused=0}failed(e,n,s,r){let o=ce(s);if(o==="26000")return this.forget();this.statements.get(e)===n&&(r?this.statements.delete(e):o==="0A000"&&(this.statements.delete(e),this.refused++))}};import{AsyncResource as mi}from"node:async_hooks";var tl=5e3,Lt=()=>new pe(503,"database_deadline_exceeded","Database transaction exceeded its deadline"),pn=class{deadline;controller=new AbortController;active=new Set;cancelBackend;cancellation=Promise.resolve();cancelledAt;timer;unlink;rejection;get signal(){return this.controller.signal}constructor(e,n){this.deadline=e===void 0?void 0:performance.now()+e,this.rejection=new Promise((r,o)=>{this.signal.addEventListener("abort",()=>{o(this.signal.reason),this.active.size&&this.cancelBackend&&this.cancel()},{once:!0})}),this.rejection.catch(()=>{});let s=()=>this.controller.abort(n?.reason??new DOMException("Database transaction cancelled","AbortError"));n?.addEventListener("abort",s,{once:!0}),this.unlink=()=>n?.removeEventListener("abort",s),n?.aborted&&s(),e!==void 0&&(this.timer=setTimeout(()=>this.controller.abort(Lt()),e))}check(){this.deadline!==void 0&&performance.now()>=this.deadline&&!this.signal.aborted&&this.controller.abort(Lt()),this.signal.throwIfAborted()}checkDeadline(){if(!(this.deadline===void 0||performance.now()<this.deadline))throw this.signal.aborted||this.controller.abort(Lt()),Lt()}remainingMs(){return this.check(),this.deadline===void 0?void 0:Math.max(1,Math.ceil(this.deadline-performance.now()))}race(e){return Promise.race([e,this.rejection])}bindBackend(e){this.cancelBackend=e}async drainCancellation(){let e=(async()=>(await this.cancellation,await Promise.allSettled([...this.active]),!0))();if(this.cancelledAt===void 0)return e;let n,s=new Promise(r=>{n=setTimeout(()=>r(!1),Math.max(0,this.cancelledAt+tl-performance.now()))});try{return await Promise.race([e,s])}finally{clearTimeout(n)}}async watch(e){this.active.add(e);try{return this.signal.aborted&&this.cancelBackend&&this.cancel(),await e}finally{this.active.delete(e)}}cancel(){this.cancelledAt??=performance.now(),this.cancellation=this.cancelBackend().catch(()=>{})}dispose(){this.timer!==void 0&&clearTimeout(this.timer),this.unlink()}};import{createHash as sl}from"node:crypto";var It=class{start=performance.now();options;ended;failure;state;constructor(e){this.options=e;for(let n of["maxQueries","maxRows","maxBytes"]){let s=e[n];if(s!==void 0&&(!Number.isSafeInteger(s)||s<0))throw new Error(`database ${n} must be a nonnegative safe integer`)}this.state={endpoint:e.endpoint,requestId:e.requestId,outcome:"active",elapsedMs:0,queries:0,rows:0,bytes:0,queueMs:0,poolMs:0,setupMs:0,sqlMs:0,commitMs:0,rollbackMs:0,connectionMs:0,commits:0,commitFailures:0,rollbackRequests:0,retries:0,statements:[]}}check(){if(this.failure)throw this.failure}time(e,n){this.state[e]=(this.state[e]??0)+performance.now()-n}retry(){this.state.retries++}committed(){this.state.commits++}commitFailed(){this.state.commitFailures++}failed(){this.state.outcome="failed"}rolledBack(){this.state.rollbackRequests++}refuse(e){throw this.failure??=new pe(500,"database_budget_exceeded",`Database ${e} budget exceeded${this.options.endpoint?` in ${this.options.endpoint}`:""}`),this.failure}emit(e,n){try{let s=e?.(n);s&&Promise.resolve(s).catch(()=>{})}catch{}}async query(e,n){this.check(),this.options.maxQueries!==void 0&&this.state.queries>=this.options.maxQueries&&this.refuse("query count");let r={ordinal:++this.state.queries,fingerprint:sl("sha256").update(e).digest("hex").slice(0,24),...this.options.includeSql?{sql:e.slice(0,4096)}:{},durationMs:0,rows:0,bytes:0};this.options.captureSource&&(r.source=new Error().stack?.split(`
|
|
402
|
+
SELECT count(*)::int AS n FROM missing`,[R,_]);if(Number(B?.n??0)>0){L+=Number(B.n);continue}let[w]=await a(`SELECT ${fe}.promote($1) AS gen`,[R]);w?.gen!==null&&w?.gen!==void 0&&(I.push(R),s?.(`palgres: search of ${R}: every row is embedded again \u2014 generation ${String(w.gen)} serves`))}return L}async function p(I={}){let L=I.timeoutMs===void 0?1/0:Date.now()+I.timeoutMs,k=[],x=0,R=()=>Date.now()<L&&(I.max===void 0||x<I.max)&&!(I.whileRunning===!0&&l);for(;;){for(;R();){let _=await c(I.max===void 0?No:Math.min(No,I.max-x));if(_.length===0)break;let P=new Map;for(let O of _){let C=`${O.table_key}\0${O.gen}`,W=P.get(C);W?W.push(O):P.set(C,[O])}let B={answered:!1,down:!1,failed:0},w=0;for(let O of P.values())try{w+=await T(O,B)}catch(C){B.failed+=O.length,await f(O,C).catch(()=>{})}if(x+=w,w===0&&B.failed>0)return{embedded:x,promoted:k}}if(!R()||await h(k)===0)break}return{embedded:x,promoted:k}}let S,b,E=!1,$,A=()=>{E=!0,b?.()};return{drain:I=>p(I),kick:A,start(){S===void 0&&(l=!1,$=dt.listen(A),S=(async()=>{await a(`UPDATE ${fe}.queue SET attempts = 0, next_attempt_at = now(), last_error = NULL WHERE next_attempt_at = 'infinity'`).catch(L=>s?.(`palgres: the search worker could not read its queue (${At(L)})`));let I=Ao;for(;!l;){E=!1;let L=!1;try{let k=await p({timeoutMs:Fa,whileRunning:!0});L=k.embedded>0||k.promoted.length>0}catch(k){s?.(`palgres: the search worker could not embed (${At(k)}); it looks again`)}I=L?Ao:Math.min(Pa,I*2),!(l||E)&&(await new Promise(k=>{let x=setTimeout(k,I);x.unref?.(),b=()=>{clearTimeout(x),k()}}),b=void 0)}})())},async stop(){if(S===void 0)return;l=!0,$?.(),$=void 0,b?.();let I=S;S=void 0;let L;await Promise.race([I,new Promise(k=>L=setTimeout(k,Ma))]),clearTimeout(L)}}}var Ts=class{options;active=0;queued=0;tenants=new Map;pending=new Map;lastTenant;accepted=0;rejected={full:0,timeout:0,cancelled:0};limit;timeout;nestedLimit;nestedActive=0;nestedPending=new Set;constructor(e){if(this.options=e,this.limit=e.queueLimit??Math.min(512,Math.max(32,e.concurrency*8)),this.timeout=e.queueTimeoutMs??1e3,this.nestedLimit=e.nestedConcurrency??e.concurrency*2,!Number.isSafeInteger(e.concurrency)||e.concurrency<1||!Number.isSafeInteger(this.nestedLimit)||this.nestedLimit<1||!Number.isSafeInteger(this.limit)||this.limit<0||this.limit>1e4||!Number.isSafeInteger(this.timeout)||this.timeout<1||this.timeout>6e4)throw new Error("Invalid database pool or queue deployment settings")}get queueTimeoutMs(){return this.timeout}get snapshot(){return{active:this.active,queued:this.queued,nested:{active:this.nestedActive,queued:this.nestedPending.size},tenants:this.tenants.size,accepted:this.accepted,rejected:{...this.rejected}}}nestedLease(e){this.nestedActive++;let n=!1;return{queueMs:performance.now()-e,release:()=>{if(n)return;n=!0,this.nestedActive--;let s=this.nestedPending.values().next().value;s&&(this.nestedPending.delete(s),s.cleanup(),s.grant(this.nestedLease(s.entered)))}}}acquireNested(e){let n=performance.now();return this.nestedActive<this.nestedLimit?Promise.resolve(this.nestedLease(n)):new Promise((s,r)=>{let o={grant:s,reject:r,entered:n,cleanup(){}},i=(c,d)=>{this.nestedPending.delete(o)&&(o.cleanup(),this.rejection(c),r(d))},a=()=>i("cancelled",e?.reason??new Error("Database admission cancelled")),l=setTimeout(()=>i("timeout",new Fe({retryAfter:1},"Database queue deadline exceeded")),this.timeout);o.cleanup=()=>{clearTimeout(l),e?.removeEventListener("abort",a)},this.nestedPending.add(o),e?.addEventListener("abort",a,{once:!0}),e?.aborted&&a()})}rejection(e){this.rejected[e]++;try{this.options.onReject?.({reason:e,active:this.active,queued:this.queued})}catch{}}take(e,n){this.active++,this.accepted++,this.lastTenant=e,this.tenants.set(e,(this.tenants.get(e)??0)+1);let s=!1;return{queueMs:performance.now()-n,release:()=>{if(s)return;s=!0,this.active--;let r=(this.tenants.get(e)??1)-1;r?this.tenants.set(e,r):this.tenants.delete(e),this.drain()}}}drain(){for(;this.active<this.options.concurrency&&this.queued;){let e=this.pending.keys().next().value;if(this.pending.size>1&&e===this.lastTenant){let r=this.pending.get(e);this.pending.delete(e),this.pending.set(e,r),e=this.pending.keys().next().value}let n=this.pending.get(e),s=n.values().next().value;n.delete(s),this.pending.delete(e),n.size&&this.pending.set(e,n),this.queued--,s.cleanup(),s.grant(this.take(e,s.entered))}}async acquire(e,n,s={}){if(n?.aborted)throw this.rejection("cancelled"),n.reason??new Error("Database admission cancelled");if(s.nested)return this.acquireNested(n);let r=this.options.tenantClaim?e[this.options.tenantClaim]:e.sub,o=typeof r=="string"&&r.length?r:"__anonymous__",i=performance.now();if(this.active<this.options.concurrency&&!this.queued)return this.take(o,i);if(!s.returning&&this.queued>=this.limit)throw this.rejection("full"),new Fe({retryAfter:1},"Database queue is full");return new Promise((a,l)=>{let c=this.pending.get(o)??new Set;this.pending.has(o)||this.pending.set(o,c);let d={grant:a,reject:l,entered:i,cleanup(){}},y=(f,g)=>{c.delete(d)&&(c.size||this.pending.delete(o),this.queued--,d.cleanup(),this.rejection(f),l(g),this.drain())},u=()=>y("cancelled",n?.reason??new Error("Database admission cancelled")),m=setTimeout(()=>y("timeout",new Fe({retryAfter:1},"Database queue deadline exceeded")),this.timeout);if(d.cleanup=()=>{clearTimeout(m),n?.removeEventListener("abort",u)},s.returning){d.returning=!0;let f=[...c];c.clear();for(let g of f)g.returning&&c.add(g);c.add(d);for(let g of f)g.returning||c.add(g)}else c.add(d);this.queued++,n?.addEventListener("abort",u,{once:!0}),n?.aborted?u():this.drain()})}},Oo=new WeakMap;function ko(t,e={concurrency:10}){let n=Oo.get(t);if(!n)return n=new Ts(e),Oo.set(t,n),n;for(let s of["concurrency","queueLimit","queueTimeoutMs","tenantClaim"])if(e[s]!==n.options[s])throw new Error("Database admission cannot be reconfigured while its pool is shared");return n}function Ua(t){return t.endsWith("_id")?t.slice(0,-3):t}function Io(t){return t.direction==="forward"?`the foreign key "${t.table}.${t.column}"`:`the reverse of "${t.table}.${t.column}"`}function Lo(t){return t.direction==="reverse"?'references(() => \u2026, { reverseAs: "\u2026" })':t.def.selfRefColumn!==void 0?'selfReferences("\u2026", { as: "\u2026" })':'references(() => \u2026, { as: "\u2026" })'}function Dn(t){let e=new Map,n=new Map;for(let r of t)for(let o of Object.values(r.tables)){let i=be(r.name,o.name);e.set(i,[]),n.set(i,new Map)}let s=(r,o,i,a)=>{let l=n.get(r);if(l===void 0)return;let c=l.get(o);if(c!==void 0){let d=Lo(c),y=Lo(i),u=d===y?`rename one of them: ${d}`:`rename one of them \u2014 "${c.table}.${c.column}": ${d}; "${i.table}.${i.column}": ${y}`;throw new Ge([`table "${r}": ${Io(c)} and ${Io(i)} both resolve to the relation name "${o}" \u2014 ${u}`])}l.set(o,i),e.get(r)?.push(a)};for(let r of t)for(let o of Object.values(r.tables)){let i=be(r.name,o.name);for(let[a,l]of Object.entries(o.columns)){let c=l._def;if(c.references===void 0)continue;let d=c.references.table,y=c.refAs??Ua(a);if(s(i,y,{table:o.name,column:a,direction:"forward",def:c},{name:y,to:d,kind:"one",via:a}),!e.has(d)||d===i)continue;let u=c.reverseAs??o.name;s(d,u,{table:o.name,column:a,direction:"reverse",def:c},{name:u,to:i,kind:"many",via:a})}}return e}function Ba(t){let e=t.columns??{},n=[],s=[];for(let[i,a]of Object.entries(e)){let l=a&&typeof a=="object"&&"_def"in a?a._def:a;l?.primaryKey&&n.push(i),l?.unique&&s.push([i])}let r=t.primaryKey??n;r.length&&s.unshift([...r]);for(let i of t.unique??[])s.push([...i.columns]);let o=new Set;return s.filter(i=>{if(!i.length||new Set(i).size!==i.length||i.some(l=>!Object.hasOwn(e,l)))throw new Error("Unique lookup requires a nonempty declared key of distinct, known columns");let a=JSON.stringify([...i].sort());return o.has(a)?!1:(o.add(a),!0)})}function Ot(t){let e=Object.fromEntries(Object.entries(t.columns).filter(([,n])=>n?._def?.ignored!==!0));return Ba({columns:e,primaryKey:t.primaryKey,unique:t.unique})}function Co(t,e,n){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`findUnique(${t}): where must contain one declared unique key`);let s=Object.keys(n);if(!e.some(r=>r.length===s.length&&r.every(o=>Object.hasOwn(n,o))))throw new Error(`findUnique(${t}): supply exactly one declared unique key (${e.map(r=>r.join(" + ")).join("; ")||"none declared"}); use findMany for other filters`);for(let[r,o]of Object.entries(n))if(o==null||typeof o=="object"&&!(o instanceof Date)||typeof o=="function"||typeof o=="symbol")throw new Error(`findUnique(${t}): ${r} requires a non-null scalar equality value`)}var q=t=>`"${t.replace(/"/g,'""')}"`;function Do(t){return t.type==="sql"&&typeof t.sqlType=="string"?`sql:${t.sqlType}`:t.type}var kt=class{version;tables=new Map;ignoredTables=new Set;schemas;deferrals;fields;constructor(e,n,s=null){this.version=n.version,this.schemas=e,this.fields=s;let r=Dn(e);for(let o of e)for(let i of Object.values(o.tables)){let a=be(o.name,i.name);if(i.ignored){this.ignoredTables.add(a);continue}this.tables.set(a,ja(o.name,i,a,n,r.get(a)??[],s))}}encryptedColumns(){return[...this.tables.values()].flatMap(e=>[...e.encrypted].map(([n,s])=>({table:e,column:n,encrypted:s})))}table(e,n){let s=this.tables.get(e);if(s)return s;throw this.ignoredTables.has(e)?new Error(`${n}(${e}): the table is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${n}(${e}): no such table in this version's schema (a table outside public is "schema.table")`)}deferral(e){return this.deferrals??=Wa(mr([...this.schemas])),this.deferrals.get(`${e.schema}.${e.name}`)??null}};function Wa(t){let e=(o,i)=>`${o}.${i}`,n=new Map,s=new Map;for(let o of t.tables)for(let i of o.foreignKeys){let a=e(i.refSchema,i.refTable);i.onDelete==="cascade"&&n.set(a,[...n.get(a)??[],e(o.schema,o.name)]),i.deferrable&&s.set(a,[...s.get(a)??[],e(o.schema,i.name)])}let r=new Map;for(let o of t.tables){let i=new Set([e(o.schema,o.name)]);for(let c of i)for(let d of n.get(c)??[])i.add(d);let a=[...new Set([...i].flatMap(c=>s.get(c)??[]))].sort();if(a.length===0)continue;let l=`ARRAY[${a.map(v).join(", ")}]::text[]`;r.set(e(o.schema,o.name),{defer:`SELECT palgres.defer_keys(${l}, true)`,check:`SELECT palgres.defer_keys(${l}, false)`})}return r}function ja(t,e,n,s,r,o){let i=new Map,a=new Set,l=[],c=new Map,d=new Set,y=new Map;for(let[m,f]of Object.entries(e.columns)){let g=f._def;if(g.ignored){a.add(m);continue}i.set(m,g),g.primaryKey&&l.push(m);let T=ln(t,e.name,m);if(g.encrypted!==void 0){if(o===null)throw new Error(`${n}.${m} is .encrypted(): the engine needs the project's fields to seal and open it \u2014 createDatabase({ fields }) (palbase/backend gives it)`);y.set(m,{address:T,lookup:g.encrypted.lookup?Ks(m):null}),c.set(m,{fromDb:h=>Ha(o,T,h)});continue}if(o!==null&&g.type==="text"&&o.sealing.get(T)?.direction==="open"){c.set(m,{fromDb:h=>typeof h=="string"&&o.sealing.get(T)!==void 0&&o.cipher.isEncrypted(h)?o.cipher.decrypt(T,h):h,toDb:h=>(o.sealing.get(T)!==void 0&&st(T,h),h)});continue}if(typeof g.codec=="string"&&g.codec in rn){let h=rn[g.codec];c.set(m,{fromDb:h.fromDb,toDb:h.toDb})}else g.transform!==void 0&&c.set(m,g.transform);(g.identity==="always"||g.generated!==void 0)&&d.add(m)}let u=e.primaryKey??l;return{key:n,schema:t,name:e.name,sql:t==="public"?q(e.name):`${q(s.schema(t))}.${q(e.name)}`,columns:i,ignored:a,primaryKey:u,singleKey:u.length===1?u[0]:null,uniqueKeys:Ot(e),transforms:c,databaseOnly:d,relations:r,projections:new Map,...e.search!==void 0?{search:{key:`${t}.${e.name}`,from:[...e.search.from]}}:{},encrypted:y,fields:o}}function Ha(t,e,n){if(typeof n!="string")return n;if(t.sealing.get(e)===void 0)return t.cipher.decrypt(e,n);if(!t.cipher.isEncrypted(n))return n;try{return t.cipher.decrypt(e,n)}catch{return n}}function vo(t){return`CASE WHEN isfinite(${t}) AND extract(year FROM ${t} AT TIME ZONE 'UTC') BETWEEN 1 AND 9999 THEN to_char(${t} AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') ELSE ${t}::text END`}function xo(t){return`CASE WHEN isfinite(${t}) AND extract(year FROM ${t}) BETWEEN 1 AND 9999 THEN to_char(${t}, 'YYYY-MM-DD') ELSE ${t}::text END`}function _o(t,e){return`CASE WHEN ${t} IS NULL THEN NULL ELSE ARRAY(SELECT ${e("u.e")} FROM unnest(${t}) WITH ORDINALITY AS u(e, i) ORDER BY u.i) END`}function Qe(t,e){if(t!==null&&t.startsWith("sql:")){let n=t.slice(4);return Xn.has(n)||Vn.has(n)?null:`CASE WHEN ${e} IS NULL THEN NULL ELSE format('%s', ${e}) END`}switch(t){case"timestamp":return vo(e);case"date":return xo(e);case"bigint[]":case"numeric[]":case"uuid[]":case"enum[]":return`${e}::text[]`;case"date[]":return _o(e,xo);case"timestamp[]":return _o(e,vo)}return null}function Po(t){return t==="jsonb"||t==="sql:json"}import{createCipheriv as Ka,createDecipheriv as Ga,createHash as Fo,randomBytes as Xa}from"node:crypto";var Ne=(t,e="page")=>new Pe({fields:[{field:e,message:t}]},t);function Mo(t){return Fo("sha256").update("palbase:cursor:v1\0").update(t).digest()}function Ss(t){let e=n=>typeof n=="bigint"?{$bigint:n.toString()}:n instanceof Date?{$date:n.toISOString()}:Array.isArray(n)?n.map(e):n&&typeof n=="object"?Object.fromEntries(Object.keys(n).sort().map(s=>[s,e(n[s])])):n;return Fo("sha256").update(JSON.stringify(e(t))).digest("base64url")}function qo(t,e){let{iat:n,exp:s,nbf:r,jti:o,...i}=e;return Ss({role:t,authorization:i})}function Uo(t,e,n){let s=Xa(12),r=Ka("aes-256-gcm",t,s);r.setAAD(Buffer.from(e));let o=Buffer.concat([r.update(JSON.stringify(n),"utf8"),r.final()]),i=`p1.${Buffer.concat([s,r.getAuthTag(),o]).toString("base64url")}`;if(i.length>16384)throw Ne("page cursor values are too large; choose shorter ordering columns");return i}function Bo(t,e,n,s){try{if(typeof n!="string"||n.length>16384||!/^p1\.[\w-]+$/.test(n))throw new Error;let r=Buffer.from(n.slice(3),"base64url");if(r.length<30||r.toString("base64url")!==n.slice(3))throw new Error;let o=Ga("aes-256-gcm",t,r.subarray(0,12));o.setAAD(Buffer.from(e)),o.setAuthTag(r.subarray(12,28));let i=JSON.parse(Buffer.concat([o.update(r.subarray(28)),o.final()]).toString("utf8"));if(!Array.isArray(i)||i.length!==s||i.some(a=>a!==null&&typeof a!="string"))throw new Error;return i}catch{throw Ne("Invalid cursor for this query or identity; restart from the first page","cursor")}}var Va=new Set(["uuid","text","integer","bigint","boolean","timestamp","numeric","enum"]);function Wo(t,e,n){let s=n;if("limit"in s||"offset"in s)throw Ne("page uses first/after or last/before, not limit/offset");let r=n.last!==void 0||n.before!==void 0;if(r&&(n.first!==void 0||n.after!==void 0))throw Ne("Use first/after or last/before in one page request");let o=(r?n.last:n.first)??50;if(!Number.isInteger(o)||o<1||o>1e3)throw Ne("page size must be an integer between 1 and 1000");if(e.length===0)throw new Error("page requires a declared primary key for a unique, stable ordering");Y(n.orderBy,"orderBy","the order");let i=n.orderBy===void 0?[]:Array.isArray(n.orderBy)?n.orderBy:[n.orderBy];if(i.length>16)throw Ne("page supports at most 16 ordering columns");let a=new Set,l=[],c=d=>{Y(d,"orderBy","the order");let y=t[d?.column];if(!Object.hasOwn(t,d?.column)||!y)throw Ne(`page order column ${d?.column} is not declared`);if(!Va.has(y.type??""))throw Ne(`page cannot order ${d.column}: ${y.type??"unknown"} is not a supported scalar column`);if(a.has(d.column))throw Ne(`page order column ${d.column} is repeated`);if(d.direction!==void 0&&d.direction!=="asc"&&d.direction!=="desc")throw Ne("page direction must be asc or desc");if(d.nulls!==void 0&&d.nulls!=="first"&&d.nulls!=="last")throw Ne("page nulls must be first or last");let u=d.direction??"asc";a.add(d.column),l.push({column:d.column,direction:u,nulls:d.nulls??(u==="asc"?"last":"first"),nullable:y.nullable!==!1})};for(let d of i)c(d);for(let d of e)a.has(d)||c({column:d,direction:l.at(-1)?.direction??"asc"});return{order:l,size:o,backward:r,token:r?n.before:n.after}}function Rs(t,e,n,s,r,o=!1){let i=e.map(c=>s(c));if(t.every(c=>!c.nullable&&c.direction===t[0].direction)&&e.every(c=>c!==null)){let c=t[0].direction==="asc"!==n;return`(${t.map(d=>r(d.column)).join(", ")}) ${c?">":"<"}${o?"=":""} (${i.join(", ")})`}let a=[],l=[];for(let c=0;c<t.length;c++){let d=t[c],y=r(d.column),u=i[c],m=d.nulls==="last"!==n,f=d.direction==="asc"!==n?">":"<",g=e[c]===null?m?"false":`${y} IS NOT NULL`:`(${y} ${f} ${u}${m?` OR ${y} IS NULL`:""})`;a.push(`(${[...l,g].join(" AND ")})`),l.push(`${y} IS NOT DISTINCT FROM ${u}`)}return o&&a.push(`(${l.join(" AND ")})`),`(${a.join(" OR ")})`}import{randomBytes as Ya}from"node:crypto";var Ja=16,za=2,jo="force_custom_plan",Qa=16384,Za=256,el=2e3,nl=256,tl=/^\s*(?:\(\s*)*(?:select|insert|update|delete|merge|values|with|table)\b/i,sl=/\bdeallocate\b/i,rl=/'\s*(?:now|today|tomorrow|yesterday)\s*'/i;function Ho(t){return sl.test(t)}function ol(t,e){if(t.length>Qa||!tl.test(t)||rl.test(t))return;let n=e?t:t.replace(/;\s*$/,"");if(!n.includes(";")&&!(!e&&n.includes("*")))return n}function Ko(t,e,n){if(!(e.length===0||e.length>Za)){for(let s of e)if(s!==null&&(typeof s!="string"||s.includes("\0")))return;return ol(t,n)}}var il=0,al=0,Go=Ya(5).toString("hex"),It=class{texts=new Map;sessions=new Map;mark(){return`${Go}_${++al}`}on(e){let n=this.sessions.get(e);return n!==void 0?this.sessions.delete(e):n=new bs(this),this.sessions.set(e,n),this.sessions.size>nl&&this.sessions.delete(this.sessions.keys().next().value),n}count(e,n,s){Ko(e,n,s)!==void 0&&this.sent(e)}sent(e){let n=(this.texts.get(e)??0)+1;return this.texts.delete(e),this.texts.set(e,n),this.texts.size>el&&this.texts.delete(this.texts.keys().next().value),n}},bs=class{statements=new Map;refused=0;all;constructor(e){this.all=e}get size(){return this.statements.size+this.refused}run(e,n,s){let r=Ko(e,n,s);if(r===void 0)return;let o=this.all.sent(e),i=this.statements.get(e),a;if(i===void 0){if(o<za||this.size>=Ja)return;i=`palgres_${Go}_${++il}`,a=`PREPARE ${i} (${n.map(()=>"unknown").join(", ")}) AS ${r}`,this.statements.set(e,i)}let l=i,c=r.includes("/*")||r.includes("*/")?"":`/* ${r} */ `;return{prepare:a,execute:`${c}EXECUTE ${i}(${n.map(d=>d===null?"NULL":ne(d)).join(", ")})`,failed:(d,y)=>this.failed(e,l,d,y)}}forget(){this.statements.clear(),this.refused=0}failed(e,n,s,r){let o=ce(s);if(o==="26000")return this.forget();this.statements.get(e)===n&&(r?this.statements.delete(e):o==="0A000"&&(this.statements.delete(e),this.refused++))}};import{AsyncResource as yi}from"node:async_hooks";var ll=5e3,Lt=()=>new pe(503,"database_deadline_exceeded","Database transaction exceeded its deadline"),fn=class{deadline;controller=new AbortController;active=new Set;cancelBackend;cancellation=Promise.resolve();cancelledAt;timer;unlink;rejection;get signal(){return this.controller.signal}constructor(e,n){this.deadline=e===void 0?void 0:performance.now()+e,this.rejection=new Promise((r,o)=>{this.signal.addEventListener("abort",()=>{o(this.signal.reason),this.active.size&&this.cancelBackend&&this.cancel()},{once:!0})}),this.rejection.catch(()=>{});let s=()=>this.controller.abort(n?.reason??new DOMException("Database transaction cancelled","AbortError"));n?.addEventListener("abort",s,{once:!0}),this.unlink=()=>n?.removeEventListener("abort",s),n?.aborted&&s(),e!==void 0&&(this.timer=setTimeout(()=>this.controller.abort(Lt()),e))}check(){this.deadline!==void 0&&performance.now()>=this.deadline&&!this.signal.aborted&&this.controller.abort(Lt()),this.signal.throwIfAborted()}checkDeadline(){if(!(this.deadline===void 0||performance.now()<this.deadline))throw this.signal.aborted||this.controller.abort(Lt()),Lt()}remainingMs(){return this.check(),this.deadline===void 0?void 0:Math.max(1,Math.ceil(this.deadline-performance.now()))}race(e){return Promise.race([e,this.rejection])}bindBackend(e){this.cancelBackend=e}async drainCancellation(){let e=(async()=>(await this.cancellation,await Promise.allSettled([...this.active]),!0))();if(this.cancelledAt===void 0)return e;let n,s=new Promise(r=>{n=setTimeout(()=>r(!1),Math.max(0,this.cancelledAt+ll-performance.now()))});try{return await Promise.race([e,s])}finally{clearTimeout(n)}}async watch(e){this.active.add(e);try{return this.signal.aborted&&this.cancelBackend&&this.cancel(),await e}finally{this.active.delete(e)}}cancel(){this.cancelledAt??=performance.now(),this.cancellation=this.cancelBackend().catch(()=>{})}dispose(){this.timer!==void 0&&clearTimeout(this.timer),this.unlink()}};import{createHash as cl}from"node:crypto";var Ct=class{start=performance.now();options;ended;failure;state;constructor(e){this.options=e;for(let n of["maxQueries","maxRows","maxBytes"]){let s=e[n];if(s!==void 0&&(!Number.isSafeInteger(s)||s<0))throw new Error(`database ${n} must be a nonnegative safe integer`)}this.state={endpoint:e.endpoint,requestId:e.requestId,outcome:"active",elapsedMs:0,queries:0,rows:0,bytes:0,queueMs:0,poolMs:0,setupMs:0,sqlMs:0,commitMs:0,rollbackMs:0,connectionMs:0,commits:0,commitFailures:0,rollbackRequests:0,retries:0,statements:[]}}check(){if(this.failure)throw this.failure}time(e,n){this.state[e]=(this.state[e]??0)+performance.now()-n}retry(){this.state.retries++}committed(){this.state.commits++}commitFailed(){this.state.commitFailures++}failed(){this.state.outcome="failed"}rolledBack(){this.state.rollbackRequests++}refuse(e){throw this.failure??=new pe(500,"database_budget_exceeded",`Database ${e} budget exceeded${this.options.endpoint?` in ${this.options.endpoint}`:""}`),this.failure}emit(e,n){try{let s=e?.(n);s&&Promise.resolve(s).catch(()=>{})}catch{}}async query(e,n){this.check(),this.options.maxQueries!==void 0&&this.state.queries>=this.options.maxQueries&&this.refuse("query count");let r={ordinal:++this.state.queries,fingerprint:cl("sha256").update(e).digest("hex").slice(0,24),...this.options.includeSql?{sql:e.slice(0,4096)}:{},durationMs:0,rows:0,bytes:0};this.options.captureSource&&(r.source=new Error().stack?.split(`
|
|
403
403
|
`).slice(1,9).join(`
|
|
404
|
-
`).slice(0,2500));let o=performance.now(),i=!1;try{let a=await n();return r.durationMs=performance.now()-o,i=!0,Array.isArray(a)&&(r.rows=a.length,r.bytes=Buffer.byteLength(JSON.stringify(a,(l,c)=>typeof c=="bigint"?c.toString():c))),this.state.rows+=r.rows,this.state.bytes+=r.bytes,this.options.maxRows!==void 0&&this.state.rows>this.options.maxRows&&this.refuse("returned rows"),this.options.maxBytes!==void 0&&this.state.bytes>this.options.maxBytes&&this.refuse("result bytes"),a}catch(a){let l=a;throw r.errorCode=String(l?.errno??l?.code??"query_failed").slice(0,80),a}finally{i||(r.durationMs=performance.now()-o),this.state.sqlMs+=r.durationMs;let a=Object.freeze(r);this.state.statements.length<200&&this.state.statements.push(a),this.emit(this.options.onQuery,a)}}get snapshot(){return Object.freeze({...this.state,elapsedMs:(this.ended??performance.now())-this.start,statements:Object.freeze([...this.state.statements].sort((e,n)=>e.ordinal-n.ordinal))})}complete(e){this.ended===void 0&&(this.ended=performance.now(),this.state.outcome=e,this.emit(this.options.onComplete,this.snapshot))}};var Ho=new WeakMap,Ko=new WeakSet;function se(t){let e=n=>`$${t.push(n)}`;return Ho.set(e,t),e}var Ns=t=>Ko.has(t);var Go=t=>`'${t.replace(/'/g,"''")}'`;function Ie(t,e){let n=t.columns.get(e);return n?Lo(n):null}function ue(t,e,n,s){if(!t.columns.has(e))throw t.ignored.has(e)?new Error(`${n}(${t.key}): ${s} "${e}" is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${n}(${t.key}): ${s} "${e}" is not a column of the table`)}function Ce(t,e,n){if(t.encrypted.has(e))throw new Error(`palgres: ${t.key}.${e} is .encrypted() \u2014 its value is not bound as it is (an engine path that reached it without sealing it)`);if(n==null)return n;let s=t.transforms.get(e)?.toDb,r=s===void 0?n:s(n),o=Ie(t,e);return o===null||r===null||r===void 0?r:o.endsWith("[]")&&Array.isArray(r)?_n(r):Io(o)?JSON.stringify(r):r}function Xo(t,e){return e.flatMap(n=>{let s=t.encrypted.get(n)?.lookup;return s?[n,s]:[n]})}function je(t,e){return Xo(t,e).map(q).join(", ")}function rl(t,e,n){return e.map(s=>{let r=t.encrypted.get(s);if(r===void 0)return s;if(r.lookup===null)throw new Error(`${n}(${t.key}): onConflict names "${s}", which is .encrypted() without { lookup: true } \u2014 no key is kept on it`);return r.lookup})}function Vo(t,e,n,s,r,o){if(Rn(s)!==null)throw new Error(`${o}(${t.key}): "${e}" is .encrypted() \u2014 the database holds no value there to compute with; write the value`);if(s===null)return n.lookup?[r(null),r(null)]:[r(null)];if(typeof s!="string")throw new TypeError(`${o}(${t.key}): "${e}" is .encrypted(), a text column \u2014 got ${typeof s}`);let{cipher:i,sealing:a}=t.fields;a.get(n.address)?.direction==="seal"&&tt(n.address,s);let l=r(i.encrypt(n.address,s)),c=a.get(n.address)?.direction==="seal"?`CASE WHEN EXISTS (SELECT 1 FROM ${ye} WHERE address = ${r(n.address)} AND phase = 'mixed') THEN ${r(s)}::text ELSE ${l}::text END`:l;return n.lookup?[c,r(i.lookup(n.address,s))]:[c]}function Yo(t,e,n,s,r){let o=t.encrypted.get(e);return o===void 0?null:Vo(t,e,o,n,s,r)}function Jo(t,e,n,s,r){let o=t.encrypted.get(n);return o===void 0?[r(As(t,e,n,s))]:(Sn(e,t.key,[n],s),Xt(e,t.key,[n],s),Vo(t,n,o,s[n],r,e))}function vt(t,e,n,s){if(t.encrypted.has(e))throw new Error(`${n}(${t.key}): ${s} names "${e}", which is .encrypted() \u2014 the database holds its ciphertext, not its value, so nothing there orders, ranges, groups or matches it`)}function zo(t,e,n){let s=n.find(r=>t.databaseOnly.has(r));if(s!==void 0)throw new Error(`${e}(${t.key}): "${s}" is written by the database (an ALWAYS .identity()) \u2014 leave it out of the write; Postgres refuses any value for it`)}function hn(t,e,n){for(let s of n)ue(t,s,e,"column");zo(t,e,n)}function As(t,e,n,s){return Sn(e,t.key,[n],s),Xt(e,t.key,[n],s),Ce(t,n,s[n])}function Os(t,e,n){let s=`${n?`${q(n)}.`:""}${q(e)}`;return ze(Ie(t,e),s)??s}function Qo(t,e,n){let s=Os(t,e,n);return ze(Ie(t,e),"x")!==null?`${s} AS ${q(e)}`:s}function Z(t,e){let n=e??"",s=t.projections.get(n);return s===void 0&&(s=[...t.columns.keys()].map(r=>Qo(t,r,e)).join(", "),t.projections.set(n,s)),s}function ks(t,e,n){if(Y(e,"select","which columns a call reads"),e!==void 0&&e.length===0)throw new Error(`${n}(${t.key}): select got an empty list \u2014 that is not "all of them" but "none counted". Leave the key out for every column; name at least one otherwise.`);return e===void 0?Z(t,"t"):e.map(s=>(ue(t,s,n,"select column"),Qo(t,s,"t"))).join(", ")}function Zo(t,e,n,s="t"){if(e==null)return"";Y(e,"orderBy","the order");let r=Array.isArray(e)?e:[e];return r.length===0?"":` ORDER BY ${r.map(i=>{Y(i,"orderBy","the order"),ue(t,i.column,n,"orderBy column"),vt(t,i.column,n,"orderBy");let a=i.direction==="desc"?"DESC":"ASC",l=i.nulls==="first"?" NULLS FIRST":i.nulls==="last"?" NULLS LAST":"";return`${q(s)}.${q(i.column)} ${a}${l}`}).join(", ")}`}function bs(t,e="findMany"){if(t===void 0)return"";if(!Number.isInteger(t)||t<0)throw new Error(`${e}: limit must be a non-negative integer (got ${String(t)})`);return` LIMIT ${t}`}function ol(t,e,n="findMany"){if(t===void 0)return"";if(!Number.isInteger(t)||t<0)throw new Error(`${n}: offset must be a non-negative integer (got ${String(t)})`);if(e===void 0)throw new Error(`${n}: offset is given only with limit \u2014 an offset without one is the shifted tail of an unbounded result, not a page`);return` OFFSET ${t}`}var fn={gt:">",gte:">=",lt:"<",lte:"<=",neq:"<>"},il=[["days","days","int"],["hours","hours","int"],["minutes","mins","int"],["seconds","secs","double precision"]];function gn(t,e){let n=t?.minus;if(n===void 0)return"now()";let s=pr(n);if("refused"in s)throw new TypeError(`palgres: ago() ${s.refused}`);return`(now() - make_interval(${il.filter(([o])=>s.span[o]!==void 0).map(([o,i,a])=>`${i} => ${e(s.span[o])}::${a}`).join(", ")}))`}var Bo=Object.freeze({update:"FOR UPDATE",share:"FOR SHARE",noKeyUpdate:"FOR NO KEY UPDATE"});function Ls(t,e,n,s){if(typeof s=="string"&&Object.hasOwn(Bo,s))return Bo[s];let r=typeof s=="string"?JSON.stringify(s.slice(0,40)):typeof s;throw new TypeError(`${t}(${e}): unknown ${n} ${r} \u2014 "update" (FOR UPDATE), "share" (FOR SHARE) or "noKeyUpdate" (FOR NO KEY UPDATE).`)}var Wo=t=>Rn(t);function jo(t,e,n,s){if(!t.columns.has(e.$col))throw new Error(`${n}(${t.key}): col("${e.$col}") is not a column of the table`);return`${q(s)}.${q(e.$col)}`}function ei(t,e,n,s){let o=(n.kind==="many"?t.table(n.to,s):e).columns.get(n.via)?.references?.column??(n.kind==="many"?e.singleKey:t.table(n.to,s).singleKey);return n.kind==="many"?[o,n.via]:[n.via,o]}function Qe(t,e,n){return De(new Pe({fields:[{field:e,message:n}]},`${t}: ${e} ${n}`))}function al(t,e){if(Y(t,e,"a filter"),!(typeof t!="object"||t===null))for(let[n,s]of Object.entries(t))n==="OR"||n==="AND"||n==="NOT"||n==="has"?Y(s,`${e}.${n}`,`a filter's ${n}`):s!==null&&typeof s=="object"&&!Array.isArray(s)&&Y(s,`${e}.${n}`,"an operator")}function Ct(t,e,n,s,r,o,i,a){let l=[];if(al(n,a),mr(r,e.key,n),on(n)){let{text:c,values:d}=n.$sql,w=Ho.get(s);if(w===void 0)throw new Error("palgres: an sqlFragment was compiled outside binder()");if(Ko.add(w),c.length!==d.length+1)throw new Error(`${r}(${e.key}): the sqlFragment's parts are broken (${c.length} texts, ${d.length} values) \u2014 only the template tag makes one`);let u=c[0]??"";for(let m=0;m<d.length;m++)u+=`${s(d[m])}${c[m+1]??""}`;if(u.trim()==="")throw Qe(r,a,"is an empty sqlFragment \u2014 no condition. Write the condition in it, or leave it out.");return[`(${u})`]}for(let[c,d]of Object.entries(n)){if(c==="OR"||c==="AND"){let h=d;if(h.length===0){if(c==="AND")throw Qe(r,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");l.push("false");continue}let T=h.map((g,p)=>{let S=Ct(t,e,g,s,r,o,i,`${a}.${c}[${p}]`);if(S.length===0)throw Qe(r,`${a}.${c}[${p}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");return`(${S.join(" AND ")})`});l.push(`(${T.join(c==="OR"?" OR ":" AND ")})`);continue}if(c==="NOT"){if(Array.isArray(d))throw Qe(r,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");let h=Ct(t,e,d,s,r,o,i,`${a}.NOT`);if(h.length===0)throw Qe(r,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");l.push(`NOT (${h.join(" AND ")})`);continue}if(c==="has"){let h=Object.entries(d);if(h.length===0)throw Qe(r,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.");for(let[T,g]of h){let p=e.relations.find(L=>L.name===T);if(p===void 0){let L=e.relations.map(N=>N.name).sort();throw new Error(`${r}(${e.key}): there is no relation has.${T}`+(L.length>0?` (known: ${L.join(", ")}). Relations come from foreign keys; to rename one, references(..., { as, reverseAs }).`:". The table declares no foreign key, and relations come from them: references(() => <table>.<column>)."))}let[S,R]=ei(t,e,p,r);if(S===null||R===null)throw new Error(`${r}(${e.key}): has.${T} cannot be built \u2014 "${S===null?e.key:p.to}" has no single-column primary key to correlate on; write the condition as an sqlFragment`);let E=t.table(p.to,r),$=`r${i+1}`,A=Mn(t,E,g??{},s,r,$,i+1,`${a}.has.${T}`),O=`${$}.${q(R)} = ${q(o)}.${q(S)}`;l.push(`EXISTS (SELECT 1 FROM ${E.sql} ${$} WHERE ${O}${A===""?"":` AND ${A}`})`)}continue}ue(e,c,r,"where column");let w=e.encrypted.get(c);if(w!==void 0){l.push(ll(e,c,w,d,s,r,o,a));continue}let u=`${q(o)}.${q(c)}`,m=Ie(e,c)?.endsWith("[]")===!0,f=h=>s(Ce(e,c,h));if(Fe(d)){l.push(`${u} = ${jo(e,d,r,o)}`);continue}if(Jn(d)){l.push(`${u} = ${gn(Wo(d),s)}`);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d))for(let[h,T]of Object.entries(d)){if(m&&(h==="contains"||h==="overlaps")){if(!Array.isArray(T))throw new Error(`${r}(${e.key}): where.${c}.${h} must be an array \u2014 ${c} is an array column`);l.push(`${u} ${h==="contains"?"@>":"&&"} ${f(T)}`);continue}if(!m&&(h==="contains"||h==="icontains"||h==="startsWith"||h==="endsWith")){if(typeof T!="string")throw new Error(`${r}(${e.key}): where.${c}.${h} must be a string`);let p=T.replace(/([\\%_])/g,"\\$1"),S=h==="startsWith"?`${p}%`:h==="endsWith"?`%${p}`:`%${p}%`;l.push(`${u} ${h==="icontains"?"ILIKE":"LIKE"} ${s(S)}`);continue}if(h==="isNull"){if(typeof T!="boolean")throw new Error(`${r}(${e.key}): where.${c}.isNull must be a boolean`);l.push(`${u} IS ${T?"NULL":"NOT NULL"}`);continue}if(h==="in"){if(!Array.isArray(T))throw new Error(`${r}(${e.key}): where.${c}.in must be an array`);if(T.some(Fe))throw new Error(`${r}(${e.key}): where.${c}.in takes values, not col() \u2014 compare with a column bare ({ ${c}: col("\u2026") }) or with gt/gte/lt/lte/neq`);if(T.length===0){l.push("false");continue}l.push(`${u} IN (${T.map(p=>f(p)).join(", ")})`);continue}if(Jn(T)){if(!(h in fn))throw new Error(`${r}(${e.key}): where.${c}.${h} cannot take now() \u2014 for equality write it bare: { ${c}: now() }`);l.push(`${u} ${fn[h]} ${gn(Wo(T),s)}`);continue}if(Yn(T))throw new Error(`${r}(${e.key}): where.${c}.${h} got a WRITE expression (increment/decrement), not a comparison value. For the server's time use now(); for a numeric threshold, the value.`);if(Fe(T)){if(!(h in fn))throw new Error(`${r}(${e.key}): where.${c}.${h} cannot take col() \u2014 for equality write it bare: { ${c}: col("\u2026") }`);l.push(`${u} ${fn[h]} ${jo(e,T,r,o)}`);continue}let g=dr(T);if(g!==null){let p=g==="col"?"col()":g==="sql"?"sqlFragment":"now()";throw new Error(`${r}(${e.key}): where.${c}.${h} got an imitation of ${p} \u2014 this object was not made by ${p} in this process. A filter from a request body cannot carry a handle; build the condition in your code.`)}if(h in fn){if(T===null&&h==="neq"){l.push(`${u} IS NOT NULL`);continue}l.push(`${u} ${fn[h]} ${f(T)}`);continue}throw new Error(`${r}(${e.key}): where.${c} has an unknown operator "${h}" (gt/gte/lt/lte/neq/in)`)}else d===null?l.push(`${u} IS NULL`):l.push(`${u} = ${f(d)}`)}return l}function ll(t,e,n,s,r,o,i,a){let l=`${q(i)}.${q(e)}`;if(s===null)return`${l} IS NULL`;let c=h=>{throw new Error(`${o}(${t.key}): ${a}.${e} ${h} \u2014 "${e}" is .encrypted(): the database holds its ciphertext, so it is asked only isNull`+(n.lookup?", equality and in":" (equality needs .encrypted({ lookup: true }))"))};(Fe(s)||Jn(s)||on(s))&&c("compares with an expression");let{cipher:d,sealing:w}=t.fields,u=w.get(n.address)!==void 0,m=h=>{if(n.lookup===null&&c("asks for equality"),h.some(R=>typeof R!="string")&&c("compares with a value that is not text"),h.length===0)return"false";let T=`${q(i)}.${q(n.lookup)}`,g=h.map(R=>r(d.lookup(n.address,R))),p=h.length===1?`${T} = ${g[0]}`:`${T} IN (${g.join(", ")})`;if(!u)return p;let S=h.map(R=>r(R));return`(${p} OR ${h.length===1?`${l} = ${S[0]}`:`${l} IN (${S.join(", ")})`})`};if(typeof s!="object"||Array.isArray(s))return m([s]);let f=[];for(let[h,T]of Object.entries(s))if(h==="isNull"){if(typeof T!="boolean")throw new Error(`${o}(${t.key}): where.${e}.isNull must be a boolean`);f.push(`${l} IS ${T?"NULL":"NOT NULL"}`)}else if(h==="in"){if(!Array.isArray(T))throw new Error(`${o}(${t.key}): where.${e}.in must be an array`);f.push(m(T))}else h==="neq"?f.push(T===null?`${l} IS NOT NULL`:`(${l} IS NOT NULL AND NOT ${m([T])})`):c(`asks ${h}`);return f.length===0&&c("holds no condition"),f.length===1?f[0]:`(${f.join(" AND ")})`}function Mn(t,e,n,s,r,o="t",i=0,a="where"){return Ct(t,e,n,s,r,o,i,a).join(" AND ")}function ve(t,e,n,s,r){let o=Ct(t,e,n,s,r,"t",0,"where");return{sql:o.length===0?"":` AND ${o.join(" AND ")}`,conditions:o.length}}function En(t,e){if(!(t.conditions>0))throw Qe(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function Fn(t,e,n,s,r){let o=Xo(t,e),i=rl(t,n,r);if(s!=="ignore"&&s!=="update")throw new TypeError(`palgres: a conflict's action is "ignore" or "update", not ${typeof s=="string"?JSON.stringify(String(s).slice(0,40)):typeof s}`);if(i.length===0){if(s==="ignore")return"ON CONFLICT DO NOTHING";throw new Error("palgres: ON CONFLICT DO UPDATE needs the columns a collision is matched on")}let a=`ON CONFLICT (${i.map(q).join(", ")})`;if(s==="ignore")return`${a} DO NOTHING`;let l=new Set(i),c=o.filter(d=>!l.has(d)).map(d=>`${q(d)} = EXCLUDED.${q(d)}`);return c.length?`${a} DO UPDATE SET ${c.join(", ")}`:`${a} DO UPDATE SET ${q(i[0])} = EXCLUDED.${q(i[0])}`}function Is(t,e,n,s,r){return zo(t,r,e),e.map(o=>{let i=t.encrypted.get(o);if(i!==void 0){let[l,c]=Jo(t,r,o,n,s);return`${q(o)} = ${l}${i.lookup?`, ${q(i.lookup)} = ${c}`:""}`}let a=Rn(n[o]);if(a!==null&&a.fn==="now")return`${q(o)} = ${gn(a,s)}`;if(a!==null){let l=t.transforms.get(o)?.toDb,c=l===void 0?a.by:l(a.by);return`${q(o)} = ${q(o)} ${a.fn==="inc"?"+":"-"} ${s(c)}`}return`${q(o)} = ${s(As(t,r,o,n))}`}).join(", ")}function qn(t,e,n,s,r){return e.map(o=>{if(t.encrypted.has(o))return Jo(t,r,o,n,s).join(", ");let i=Rn(n[o]);if(i!==null&&i.fn==="now")return gn(i,s);if(i!==null){let a=i.fn==="inc"?"increment":"decrement";throw new Error(`${r}(${t.key}): "${o}" got ${a}() \u2014 the row does not exist yet, so there is no current value. Write the starting value; to change it once the row exists, updateMany({ where, set: { ${o}: ${a}(n) } }).`)}return s(As(t,r,o,n))}).join(", ")}var cl=new Set(["integer","bigint","numeric"]);function ni(t){return t!==null&&cl.has(t)}function ti(t,e,n,s){vt(t,n,"aggregate",e);let r=`t.${q(n)}`,o=Ie(t,n);if(e==="sum"||e==="avg")return`${e}(${r})::text AS ${q(s)}`;let i=o!==null&&!o.endsWith("[]")?ze(o,`${e}(${r})`):null;return i!==null?`${i} AS ${q(s)}`:o==="bigint"||o==="numeric"?`${e}(${r})::text AS ${q(s)}`:`${e}(${r}) AS ${q(s)}`}function ul(t,e,n,s=[]){return`json_build_object(${[...e.map(o=>{let i=Ie(t,o),a=`${n}.${q(o)}`,l=i==="numeric"||i==="bigint"?`${a}::text`:ze(i,a)??a;return`${Go(o)}, ${l}`}),...s].join(", ")})`}function xt(t,e,n,s,r,o="t",i=0,a={value:0}){if(Y(n,"with","which relations a call reads"),i>=3&&Object.values(n).some(Boolean))throw new Error(`${r}(${e.key}): with supports at most three relation levels`);let l=[],c=[],d=[];for(let[w,u]of Object.entries(n)){if(u===!1||u===void 0)continue;Y(u,`with.${w}`,"which relations a call reads");let m=e.relations.find(C=>C.name===w);if(m===void 0){let C=e.relations.map(v=>v.name).sort();throw new Error(`${r}(${e.key}): there is no relation with.${w}`+(C.length>0?` (known: ${C.join(", ")})`:". The table declares no foreign key, and relations come from them")+". A relation is declared with references(() => <table>.<column>).")}let[f,h]=ei(t,e,m,r);if(f===null||h===null)throw new Error(`${r}(${e.key}): with.${w} needs a single-column primary key at one end of the relation`);let T=t.table(m.to,r),g=typeof u=="object"&&u!==null?u:{},p=++a.value,S=`w${p}`;if(Y(g.select,`with.${w}.select`,"which columns a call reads"),Y(g.orderBy,`with.${w}.orderBy`,"the order"),g.select!==void 0&&(!Array.isArray(g.select)||g.select.length===0))throw new Error(`${r}(${e.key}): with.${w}.select must be a non-empty array of columns`);let R=Array.isArray(g.select)?g.select:[...T.columns.keys()];for(let C of R)ue(T,C,r,`with.${w}.select column`);let E=g.with;if(E!==void 0&&(E===null||typeof E!="object"||Array.isArray(E)))throw new Error(`${r}(${e.key}): with.${w}.with must be a relation object`);let $=E===void 0?{joins:[],jsonPairs:[]}:xt(t,T,E,s,r,S,i+1,a),A=$.joins.length?` ${$.joins.join(" ")}`:"",O=ul(T,R,S,$.jsonPairs),L=g.where!==void 0&&g.where!==null?Mn(t,T,g.where,s,r,S,p,`with.${w}.where`):"",N=`${S}.${q(h)} = ${q(o)}.${q(f)}`,_=L===""?N:`${N} AND ${L}`,y=g.limit;bs(y,r);let k=m.kind==="many"?y:Math.min(1,y??1),D=Zo(T,g.orderBy,r,S)+bs(k,r),P=`wj${p}`;m.kind==="many"?c.push(`LEFT JOIN LATERAL (SELECT coalesce(json_agg(x.o), '[]'::json) AS d FROM (SELECT ${O} AS o FROM ${T.sql} ${S}${A} WHERE ${_}${D}) x) ${q(P)} ON true`):c.push(`LEFT JOIN LATERAL (SELECT ${O} AS d FROM ${T.sql} ${S}${A} WHERE ${_}${D}) ${q(P)} ON true`),l.push(`${q(P)}."d" AS ${q(w)}`),d.push(`${Go(w)}, ${q(P)}."d"`)}return{select:l,joins:c,jsonPairs:d}}function Cs(t,e,n,s){let r=[],o=se(r),i=ve(t,e,n,o,"findMany").sql,a=Zo(e,s.orderBy,"findMany"),l=bs(s.limit),c=ol(s.offset,s.limit),d=ks(e,s.select,"findMany"),w=s.with!==void 0&&Object.keys(s.with).length>0?xt(t,e,s.with,o,"findMany"):{select:[],joins:[]},u=w.select.length>0?`${d}, ${w.select.join(", ")}`:d,m=w.joins.length>0?` ${w.joins.join(" ")}`:"",f=s.lock===void 0?"":` ${Ls("findUnique",e.key,"lock",s.lock)} OF t`;return{sql:`SELECT ${u} FROM ${e.sql} t${m} WHERE true${i}${a}${l}${c}${f}`,params:r}}var Rs=50;function vs(t,e,n,s){if(e.search===void 0||e.singleKey===null)throw new Error(`search(${e.key}): the table declares no search`);if(n.text===void 0&&n.vector===void 0)throw new Error(`search(${e.key}): neither the query's words nor its vector to search by`);let r=[],o=se(r),i=q(e.singleKey),a=ve(t,e,s.where??{},o,"search").sql,l=Math.max(s.limit*3,30),c=[];if(n.vector!==void 0){let w=`v."embedding" ${n.vector.operator} ${o(n.vector.literal)}::${n.vector.type}`;c.push(`sem AS (SELECT s."id", row_number() OVER (ORDER BY s."d", s."id") AS r FROM (SELECT t.${i} AS "id", ${w} AS "d" FROM ${n.vector.table} v JOIN ${e.sql} t ON t.${i} = v."id" WHERE true${a} ORDER BY ${w} LIMIT ${l}) s)`)}if(n.text!==void 0){let w=it(e.search.from,"t"),u=`websearch_to_tsquery('simple', ${o(n.text)})`;c.push(`kw AS (SELECT s."id", row_number() OVER (ORDER BY s."k" DESC, s."id") AS r FROM (SELECT t.${i} AS "id", ts_rank_cd(${w}, ${u}) AS "k" FROM ${e.sql} t WHERE ${w} @@ ${u}${a} ORDER BY "k" DESC LIMIT ${l}) s)`)}c.push(c.length===2?`fused AS (SELECT coalesce(sem."id", kw."id") AS "id", (coalesce(1.0 / (${Rs} + sem.r), 0) + coalesce(1.0 / (${Rs} + kw.r), 0))::float8 AS "score" FROM sem FULL OUTER JOIN kw ON sem."id" = kw."id")`:`fused AS (SELECT x."id", (1.0 / (${Rs} + x.r))::float8 AS "score" FROM ${n.vector!==void 0?"sem":"kw"} x)`);let d=s.minScore===void 0?"":` AND f."score" >= ${o(s.minScore)}`;return{sql:`WITH ${c.join(", ")} SELECT ${Z(e,"t")}, f."score" AS "_score" FROM fused f JOIN ${e.sql} t ON t.${i} = f."id" WHERE true${d} ORDER BY f."score" DESC, t.${i} LIMIT ${dl(s.limit)}`,params:r}}function dl(t){if(!Number.isInteger(t)||t<1)throw new Error(`search: limit must be a positive integer (got ${String(t)})`);return t}function si(t){return t instanceof Date?t.toISOString():Array.isArray(t)?t.map(si):t}function xs(t){if(t===null||typeof t!="object")return t;let e={};for(let[n,s]of Object.entries(t))e[n]=si(s);return e}function ml(t,e){for(let[n,s]of e.transforms){if(s.fromDb===void 0)continue;let r=t[n];r!=null&&(t[n]=s.fromDb(r))}return t}function Pn(t,e,n,s){let r=n.map(o=>ml(xs(o),e));if(s)for(let o of e.relations){let i=s[o.name];if(!i)continue;let a=typeof i=="object"?i.with:void 0,l=t.table(o.to,"with");for(let c of r){let d=c[o.name];Array.isArray(d)?c[o.name]=Pn(t,l,d,a):d&&typeof d=="object"&&(c[o.name]=Pn(t,l,[d],a)[0])}}return rn(r)}var pl={inline:!0},_s={inline:!0,read:!0},fl=t=>ce(t)===le.uniqueViolation||en.is(t);function ri(t,e){if(e===null)return!1;let n=Object.keys(t);if(n.length!==1||n[0]!==e)return!1;let s=t[e];return s!==null&&(typeof s!="object"||Array.isArray(s))}var gl=6e4;function Un(t,e){let{cat:n}=e,s=(u,m)=>n.table(u,m),r=(u,m)=>{let f=n.table(u,m);return f.search!==void 0&&e.searchable?.(),f},o=async(u,m=[],f=!1)=>await(await t()).unsafe(u,m,Ns(m)?void 0:f?_s:pl),i=(u,m=[])=>o(u,m,!0),a=async(u,m=[])=>await(await t()).unsafe(u,m),l=async(u,m)=>{let f=n.deferral(u);if(f===null)return m();await o(f.defer);let h=await m();return await o(f.check),h},c=(u,m,f)=>Pn(n,u,m,f),d=(u,m)=>Pn(n,u,[m])[0],w={diagnostics(){return e.trace?.snapshot??null},async query(u,m=[]){return rn((await a(u,m)).map(f=>xs(f)))},async insert(u,m){let f=r(u,"insert"),h=Object.keys(m);if(h.length===0)throw new Error(`insert into ${u}: no columns given`);hn(f,"insert",h);let T=[],g=qn(f,h,m,se(T),"insert"),p=await o(`INSERT INTO ${f.sql} (${je(f,h)}) VALUES (${g}) RETURNING ${Z(f)}`,T);if(!p[0])throw new Error(`insert into ${u} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return d(f,p[0])},insertMany:(async function(u,m,f){if(Er(f),m.length===0)return f?.returning===!1?0:[];let h=r(u,"insertMany"),T=Object.keys(m[0]);if(T.length===0)throw new Error(`insertMany into ${u}: no columns given`);for(let A=1;A<m.length;A++){let O=T.filter(N=>!(N in m[A])),L=Object.keys(m[A]).filter(N=>!T.includes(N));if(O.length>0||L.length>0)throw new Error(`insertMany(${u}): row ${A} does not have the first row's columns`+(O.length>0?` (missing: ${O.join(", ")})`:"")+(L.length>0?` (extra: ${L.join(", ")})`:"")+". One statement shares the column list: write null for a missing value, or insert differently shaped rows in calls of their own.")}hn(h,"insertMany",T),Y(f?.onConflict,"onConflict","which columns a conflict is on");for(let A of f?.onConflict??[])ue(h,A,"insertMany","onConflict column");let g=[],p=se(g),S=m.map(A=>`(${qn(h,T,A,p,"insertMany")})`),R=f?.onConflict??[],E=R.length>0||f?.action==="ignore"?` ${Fn(h,T,R,f?.action??"ignore","insertMany")}`:"",$=await o(`INSERT INTO ${h.sql} (${je(h,T)}) VALUES ${S.join(", ")}${E}${f?.returning===!1?"":` RETURNING ${Z(h)}`}`,g);if(f?.returning===!1){if(!Number.isSafeInteger($.count)||$.count<0)throw new Error("insertMany returning:false requires a driver with an affected row count");return $.count}return c(h,$)}),async advisoryXactLock(u){await o("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",[u])},async lockRows(u,m){let f=[...new Set(m)].sort();if(f.length===0)return;let h=s(u,"lockRows");if(h.singleKey===null)throw new Error(`lockRows(${u}): no single-column primary key \u2014 the lock order needs one`);let T=q(h.singleKey),g=[],p=se(g),S=f.map(R=>p(Ce(h,h.singleKey,R))).join(", ");await o(`SELECT t.${T} FROM ${h.sql} t WHERE t.${T} IN (${S}) ORDER BY t.${T} FOR NO KEY UPDATE`,g)},async lockRowsWhere(u,m,f){let h=Ls("lockRowsWhere",u,"mode",f?.mode===void 0?"update":f.mode),T=s(u,"lockRowsWhere");if(T.singleKey===null)throw new Error(`lockRowsWhere(${u}): no single-column primary key \u2014 the lock order needs one`);let g=[],p=ve(n,T,m,se(g),"lockRowsWhere");En(p,"lockRowsWhere");let S=q(T.singleKey);await o(`SELECT t.${S} FROM ${T.sql} t WHERE true${p.sql} ORDER BY t.${S} ${h}`,g)},async claim(u,m,f={}){let h=r(u,"claim");Y(m,"unique","which key a claim is on");let T=Object.keys(m);if(T.length===0)throw new Error(`claim(${u}): no unique field given. claim takes ownership of a key; with none there is nothing to own \u2014 use insert(${u}, \u2026).`);Sn("claim",u,T,m);for(let E of T){let $=m[E];if($===null||typeof $=="object"||typeof $=="function")throw new Error(`claim(${u}): the unique field "${E}" is ${$===null?"null":"an object"} \u2014 a key is one value (a string, number, bigint or boolean); NULL never equals a claimed row.`)}let g=Object.keys(f).filter(E=>Object.hasOwn(m,E));if(g.length>0)throw new Error(`claim(${u}): ${g.map(E=>`"${E}"`).join(", ")} is in both the unique fields and extra \u2014 say a key once, in the unique fields.`);let p={...m,...f},S=Object.keys(p);hn(h,"claim",S);let R=await t();try{return await R.savepoint(async E=>{let $=[],A=qn(h,S,p,se($),"claim"),O=await E.unsafe(`INSERT INTO ${h.sql} (${je(h,S)}) VALUES (${A}) RETURNING ${Z(h)}`,$);if(!O[0])throw new Error(`claim(${u}): the INSERT returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return{inserted:!0,row:d(h,O[0])}})}catch(E){if(!fl(E))throw E;let $=[],A=se($),O=Mn(n,h,m,A,"claim"),L=await o(`SELECT ${Z(h,"t")} FROM ${h.sql} t WHERE ${O} LIMIT 1`,$);if(!L[0]){let N=$n(E);throw new Error(`claim(${u}): a unique violation${N?` (${N})`:""} was caught but no row has these ${T.join(", ")}. Either the violation is of ANOTHER unique constraint \u2014 claim() is the wrong tool for this call \u2014 or the row exists and an RLS policy hides it from this caller.`)}return{inserted:!1,row:d(h,L[0])}}},async put(u,m,f){let h=r(u,"put"),T=f.onConflict;if(T.length===0)throw new Error(`put into ${u}: onConflict needs at least one column`);let g=Object.keys(m);if(g.length===0)throw new Error(`put into ${u}: no columns given`);hn(h,"put",g),Y(T,"onConflict","which columns a conflict is on");for(let E of T)ue(h,E,"put","onConflict column");let p=[],S=qn(h,g,m,se(p),"put"),R=await o(`INSERT INTO ${h.sql} (${je(h,g)}) VALUES (${S}) ${Fn(h,g,T,"update","put")} RETURNING ${Z(h)}`,p);if(!R[0])throw new Error(`put into ${u} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return d(h,R[0])},async update(u,m,f){let h=r(u,"update");if(!h.columns.has("id"))throw new Error(`update(${u}): the table has no "id" column \u2014 update a row by its key with updateMany({ where, set })`);let T=Object.keys(f);if(T.length===0)return w.findById(u,m);for(let E of T)ue(h,E,"update","set column");let g=[],p=se(g),S=Is(h,T,f,p,"update"),R=await o(`UPDATE ${h.sql} SET ${S} WHERE "id" = ${p(Ce(h,"id",m))} RETURNING ${Z(h)}`,g);return R[0]?d(h,R[0]):null},async delete(u,m){let f=s(u,"delete");if(!f.columns.has("id"))throw new Error(`delete(${u}): the table has no "id" column \u2014 delete by its key with deleteMany({ where })`);let h=[Ce(f,"id",m)];await l(f,()=>o(`DELETE FROM ${f.sql} WHERE "id" = $1`,h))},async updateMany(u,m,f,h){let T=r(u,"updateMany"),g=Object.keys(f);if(g.length===0)throw new Error(`updateMany(${u}): nothing to set. An update with no columns is not a no-op worth pretending happened \u2014 pass the columns to write.`);for(let P of g)ue(T,P,"updateMany","set column");let p=[],S=se(p),R=Is(T,g,f,S,"updateMany"),E=ve(n,T,m,S,"updateMany");En(E,"updateMany");let $=E.sql,A=T.singleKey,O=h?.returning!==!1,L=A===null||ri(m,A),N=O?`RETURNING ${Z(T,"t")}`:"RETURNING 1",_=L?`UPDATE ${T.sql} AS t SET ${R} WHERE true${$} ${N}`:`UPDATE ${T.sql} AS t SET ${R} FROM locked WHERE t.${q(A)} = locked."__pb_lock" ${N}`,y=L?"":`WITH locked AS (SELECT t.${q(A)} AS "__pb_lock" FROM ${T.sql} t WHERE true${$} ORDER BY t.${q(A)} FOR NO KEY UPDATE)`,k=O?`${y} ${_}`.trim():L?`WITH upd AS (${_}) SELECT count(*)::int AS n FROM upd`:`${y}, upd AS (${_}) SELECT count(*)::int AS n FROM upd`,D=await o(k,p);return O?c(T,D):Number(D[0]?.n??0)},async deleteMany(u,m){let f=s(u,"deleteMany"),h=[],T=ve(n,f,m,se(h),"deleteMany");return En(T,"deleteMany"),(await l(f,()=>o(`DELETE FROM ${f.sql} AS t WHERE true${T.sql} RETURNING 1`,h))).length},async aggregate(u,m={}){let f=s(u,"aggregate");for(let N of["sum","avg","min","max","groupBy"])Y(m[N],N,"which columns an aggregate reads");Y(m.count,"count","which counts an aggregate takes");let h=[],T=se(h),g=[],p=[];for(let N of["sum","avg","min","max"])for(let _ of m[N]??[]){if(ue(f,_,"aggregate",`${N} column`),(N==="sum"||N==="avg")&&!ni(Ie(f,_)))throw new Error(`aggregate(${u}): ${N}("${_}") on a column that is not numeric \u2014 "${_}" is ${Ie(f,_)}. Only integer, bigint and numeric sum; to count rows, count: true.`);let y=`${N}__${_}`;p.push({fn:N,col:_,alias:y}),g.push(ti(f,N,_,y))}m.count===!0&&g.push('count(*) AS "_count"');let S=m.count!==null&&typeof m.count=="object"?Object.entries(m.count):[];if(m.count!==void 0&&typeof m.count!="boolean"&&(m.count===null||typeof m.count!="object"||Array.isArray(m.count)||S.length===0))throw new Error(`aggregate(${u}): count is true, or named filters \u2014 { <name>: <filter> }, at least one`);if(S.forEach(([N,_],y)=>{let k=Mn(n,f,_,T,"aggregate","t",0,`count.${N}`);g.push(`count(*) FILTER (WHERE ${k===""?"true":k}) AS ${q(`count__${y}`)}`)}),g.length===0)throw new Error(`aggregate(${u}): no aggregate asked for \u2014 the result would be an empty object. Name sum/avg/min/max columns or count: true.`);let R=m.groupBy??[];for(let N of R)ue(f,N,"aggregate","groupBy column"),vt(f,N,"aggregate","groupBy");let E=R.map(N=>`${Os(f,N,"t")} AS ${q(`g__${N}`)}`),$=ve(n,f,m.where??{},T,"aggregate").sql,A=R.length>0?` GROUP BY ${R.map(N=>`t.${q(N)}`).join(", ")}`:"",O=await i(`SELECT ${[...E,...g].join(", ")} FROM ${f.sql} t WHERE true${$}${A}`,h),L=N=>{let _={};for(let y of R)_[y]=N[`g__${y}`];for(let y of p){let k=_[y.fn]??={};k[y.col]=N[y.alias]??null}return m.count===!0&&(_.count=Number(N._count??0)),S.length>0&&(_.count=Object.fromEntries(S.map(([y],k)=>[y,Number(N[`count__${k}`]??0)]))),_};return R.length>0?O.map(L):L(O[0]??{})},async count(u,m={}){let f=s(u,"count"),h=[],T=ve(n,f,m,se(h),"count").sql,g=await i(`SELECT count(*) AS n FROM ${f.sql} t WHERE true${T}`,h);return Number(g[0]?.n??0)},async findUnique(u,m,f={}){let h=s(u,"findUnique");No(u,h.uniqueKeys,m);let T={select:f.select===void 0?void 0:Tn(f.select,[...f.select]),with:f.with,limit:2},g;if(f.lock===void 0)g=await w.findMany(u,m,T);else{let p=Cs(n,h,m,{...T,lock:f.lock});g=c(h,await o(p.sql,p.params),f.with)}if(g.length>1)throw new Error(`findUnique(${u}): the database's constraints disagree with the schema; more than one row matched`);return g[0]??null},async findById(u,m){let f=s(u,"findById");if(!f.columns.has("id"))throw new Error(`findById(${u}): the table has no "id" column \u2014 use findUnique({ where: <its key> })`);let h=await i(`SELECT ${Z(f)} FROM ${f.sql} WHERE "id" = $1`,[Ce(f,"id",m)]);return h[0]?d(f,h[0]):null},async findMany(u,m={},f={}){let h=s(u,"findMany"),T=Cs(n,h,m,f),g=f.lock!==void 0;return c(h,await(g?o:i)(T.sql,T.params),f.with)},async search(u,m,f={}){let h=s(u,"search"),T=h.search;if(T===void 0)throw new Error(`search(${u}): the table declares no search \u2014 defineTable(${JSON.stringify(h.name)}, { \u2026, search: { from: [<its text columns>], model } })`);let g=Eo(u,m,f),p=e.search,S=L=>c(h,L),R=async()=>{let L=vs(n,h,{text:g.text},{where:f.where,limit:g.limit,minScore:g.minScore});return S(await i(L.sql,L.params))};if(g.mode==="text")return R();let E=p.embed;if(E===void 0)throw new Error(`search(${u}): no embedder was given, and a search by meaning embeds its query \u2014 createDatabase({ embed }) (the backend's db.embed); mode: "text" searches by word alone`);let $=L=>(L===void 0?p.serving.delete(T.key):p.serving.set(T.key,L),L),A=p.serving.get(T.key)??$(Es((await i(hs,[T.key]))[0])),O;for(let L=1;;L++){if(A===void 0){if(g.mode==="vector")throw new Error(`search(${u}): the database holds no vectors for this table \u2014 its schema is migrated before the app serves`);return R()}if(O===void 0||O.of.model!==A.model||O.of.dimensions!==A.dimensions)try{O={of:A,literal:await yo(E,g.text,A)}}catch(v){if(g.mode==="vector")throw v;let I=Date.now();return I-(p.said.get(T.key)??-1/0)>=gl&&(p.said.set(T.key,I),p.log?.(`palgres: search(${u}) answered by word alone: its query could not be embedded (${v instanceof Error?v.message:String(v)})`)),R()}let N=An(A.dimensions,A.metric),_=q(A.types),y=vs(n,h,{...g.mode==="hybrid"?{text:g.text}:{},vector:{table:`${q(J)}.${q(Be(T.key,A.gen))}`,literal:O.literal,type:`${_}.${N.type}`,operator:`OPERATOR(${_}.${N.operator})`}},{where:f.where,limit:g.limit,minScore:g.minScore}),k=await t(),[D,P]=await Promise.all([k.unsafe(hs,[T.key],_s),k.unsafe(y.sql,y.params,Ns(y.params)?void 0:_s)]),C=$(Es(D[0]));if(C!==void 0&&C.gen===A.gen)return S(P);if(L>=3)throw new Error(`search(${u}): the vectors that serve the table changed while it was searched, three times over`);A=C}},async page(u,m={},f={}){let h=s(u,"page");if(e.cursorKey===null)throw new Error("Database.page needs a cursor secret shared by every replica: createDatabase({ cursorSecret })");let T=e.cursorKey,g=Object.create(null);for(let[H,ie]of h.columns)g[H]={type:ie.type,nullable:ie.nullable&&!h.primaryKey.includes(H)};let{order:p,size:S,backward:R,token:E}=Po(g,h.primaryKey,f),$=[],A=se($),O=ve(n,h,m,A,"page").sql,L=ks(h,f.select===void 0?void 0:Tn(f.select,[...f.select]),"page"),N=$s({table:u,version:n.version,columns:g,order:p,where:O,params:$,select:f.select,with:f.with,identity:e.cursorScope()}),_=E===void 0?void 0:Do(T,N,E,p.length),y=H=>`t.${q(H)}`,k=_?` AND ${Ts(p,_,R,A,y)}`:"",D=_?`EXISTS (SELECT 1 FROM ${h.sql} t WHERE true${O} AND ${Ts(p,_,!R,A,y,!0)})`:"false",P="__pb_page_",C=[...h.columns.keys(),...Object.keys(f.with??{})];for(;C.some(H=>H.startsWith(P));)P+="_";let v=`${P}ordinal`,I=`${P}opposite`,B=p.map((H,ie)=>`${P}${ie}`),U=p.map((H,ie)=>`${Ie(h,H.column)==="timestamp"?ze("timestamp",y(H.column)):`${y(H.column)}::text`} AS ${q(B[ie])}`),W=f.with&&Object.keys(f.with).length?xt(n,h,f.with,A,"page"):{select:[],joins:[]},G=p.map(H=>`${y(H.column)} ${H.direction==="asc"!==R?"ASC":"DESC"} NULLS ${H.nulls==="first"!==R?"FIRST":"LAST"}`).join(", "),K=`SELECT ${[L,...W.select,...U,`row_number() OVER (ORDER BY ${G}) AS ${q(v)}`].join(", ")} FROM ${h.sql} t ${W.joins.join(" ")} WHERE true${O}${k} ORDER BY ${G} LIMIT ${S+1}`,X=`SELECT p.*, b.${q(I)} FROM (SELECT ${D} AS ${q(I)}) b LEFT JOIN LATERAL (${K}) p ON true ORDER BY p.${q(v)}`,ee=await i(X,$),oe=ee[0]?.[I]===!0,Q=ee.filter(H=>H[v]!==null&&H[v]!==void 0),xe=Q.length>S;Q=Q.slice(0,S),R&&Q.reverse();let re=H=>H?_o(T,N,B.map(ie=>H[ie]===null?null:String(H[ie]))):null,Ae={startCursor:re(Q[0]),endCursor:re(Q.at(-1)),hasNextPage:R?oe:xe,hasPreviousPage:R?xe:oe};for(let H of Q)for(let ie of[...B,v,I])delete H[ie];return{rows:c(h,Q,f.with),pageInfo:Ae}},async attempt(u){return(await t()).savepoint(f=>u(Un(()=>Promise.resolve(f),e)))},async txPlan(u){return(await t()).savepoint(async f=>{let h=[];for(let T of u.ops){let g=T.op==="select"||T.op==="delete"?s(T.table,"transaction plan"):r(T.table,"transaction plan"),p=yl(n,g,T,h),S=T.op==="delete"?n.deferral(g):null;p!==null&&S!==null&&await f.unsafe(S.defer,[]);let R=p===null?[]:c(g,await f.unsafe(p.sql,p.params));p!==null&&S!==null&&await f.unsafe(S.check,[]);let E={rows:R,rows_affected:R.length};h.push(E),wl(T,E)}return{results:h}})}};return w}function hl(t,e){let n;return t.op<0||t.op>=e.length?n=`transaction plan: a reference points at operation ${t.op}, but the plan has run ${e.length} (0\u2026${e.length-1}). A reference can only read an EARLIER operation's row.`:e[t.op].rows[0]?n=`transaction plan: operation ${t.op}'s row has no column "${t.field}" (its columns: ${Object.keys(e[t.op].rows[0]).join(", ")}).`:n=`transaction plan: operation ${t.op} returned NO ROW, so "${t.field}" cannot be read. A reference does not guarantee its row exists \u2014 declare the expectation first (\`.expectOne(err)\`).`,Object.assign(new Error(n),{error_code:"tx_ref_unresolved"})}function Ms(t,e){if(ur(t))throw new Error(`${e}: got an imitation of a plan reference ({ $ref: \u2026 }) \u2014 this object was not made by the plan's builder. A reference is built in your code from an earlier operation's row (insert(...).expectOne(err).id); a filter from a request body cannot carry one.`)}function Fs(t,e){let n=e[t.$ref.op]?.rows[0];if(!n||!(t.$ref.field in n))throw hl(t.$ref,e);return n[t.$ref.field]}function _t(t,e,n,s,r,o){return Ms(e,`transaction plan (${n})`),Yo(t,n,Vn(e)?Fs(e,r):e,s,o)??[El(t,e,n,s,r)]}function El(t,e,n,s,r){if(Ms(e,`transaction plan (${n})`),Vn(e))return s(Ce(t,n,Fs(e,r)));if(cr(e)){let o=e.$expr;return o.fn==="now"?gn(o,s):`${q(n)} ${o.fn==="inc"?"+":"-"} ${s(Ce(t,n,o.by))}`}return s(Ce(t,n,e))}function Ps(t,e){if(Ms(t,"transaction plan filter"),Vn(t)){let n=Fs(t,e);if(n==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${t.$ref.op}'s "${t.$ref.field}" is NULL. As a filter value NULL means IS NULL \u2014 every row with no value there, not the one the reference named. Write null in the filter when that is what you mean.`),{error_code:"tx_ref_null"});if(typeof n=="object"&&!Array.isArray(n)&&!lr(n))throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${t.$ref.op}'s "${t.$ref.field}" is an object. A filter compares a column with a value; an object there would be read as operators. Reference a scalar column.`),{error_code:"tx_ref_object"});return n}if(Array.isArray(t))return Tn(t,t.map(n=>Ps(n,e)));if(t!==null&&typeof t=="object"&&!Fe(t)&&!on(t)&&!Yn(t)&&!(t instanceof Date)){let n=Tn(t,{});for(let[s,r]of Object.entries(t))n[s]=Ps(r,e);return n}return t}function Ds(t,e,n,s,r,o){if(n===void 0||Object.keys(n).length===0&&!on(n))return{sql:"",conditions:0,resolved:{}};let i=Ps(n,r);return{...ve(t,e,i,s,o),resolved:i}}function yl(t,e,n,s){let r=[],o=se(r),i=`transaction plan ${n.op}`,a=n.op==="insertMany"?[...new Set((n.rows??[]).flatMap(c=>Object.keys(c)))]:Object.keys(n.values??n.set??{});hn(e,i,a);let l;switch(n.op){case"insert":{let c=n.values??{},d=Object.keys(c),w=d.flatMap(u=>_t(e,c[u],u,o,s,i));l=d.length?`INSERT INTO ${e.sql} (${je(e,d)}) VALUES (${w.join(", ")}) RETURNING ${Z(e)}`:`INSERT INTO ${e.sql} DEFAULT VALUES RETURNING ${Z(e)}`;break}case"upsert":{let c=n.values??{},d=Object.keys(c),w=n.onConflict??[];if(d.length===0||w.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});Y(n.onConflict,"onConflict","which columns a conflict is on");for(let m of w)ue(e,m,i,"onConflict column");let u=d.flatMap(m=>_t(e,c[m],m,o,s,i));l=`INSERT INTO ${e.sql} (${je(e,d)}) VALUES (${u.join(", ")}) ${Fn(e,d,w,"update",i)} RETURNING ${Z(e)}`;break}case"insertMany":{let c=n.rows??[];if(c.length===0)return null;let d=Object.keys(c[0]),w=c.map(f=>`(${d.flatMap(h=>_t(e,f[h],h,o,s,i)).join(", ")})`),u=n.onConflict??[];Y(n.onConflict,"onConflict","which columns a conflict is on");for(let f of u)ue(e,f,i,"onConflict column");if(n.action==="update"&&u.length===0)throw Object.assign(new Error(`insertMany on ${n.table}: an overwrite needs onConflict columns`),{error_code:"tx_bad_upsert"});let m=n.action!==void 0?` ${Fn(e,d,u,n.action,i)}`:"";l=`INSERT INTO ${e.sql} (${je(e,d)}) VALUES ${w.join(", ")}${m} RETURNING ${Z(e)}`;break}case"update":{let c=n.set??{},d=Object.keys(c);if(d.length===0)throw new Error(`update ${n.table}: nothing to set`);let w=d.map(f=>{let[h,T]=_t(e,c[f],f,o,s,i),g=e.encrypted.get(f)?.lookup;return`${q(f)} = ${h}${g?`, ${q(g)} = ${T}`:""}`}),u=Ds(t,e,n.where,o,s,i);En(u,i);let m=e.singleKey;l=m===null||ri(u.resolved,m)?`UPDATE ${e.sql} AS t SET ${w.join(", ")} WHERE true${u.sql} RETURNING ${Z(e,"t")}`:`WITH locked AS (SELECT t.${q(m)} AS "__pb_lock" FROM ${e.sql} t WHERE true${u.sql} ORDER BY t.${q(m)} FOR NO KEY UPDATE) UPDATE ${e.sql} AS t SET ${w.join(", ")} FROM locked WHERE t.${q(m)} = locked."__pb_lock" RETURNING ${Z(e,"t")}`;break}case"delete":{let c=Ds(t,e,n.where,o,s,i);En(c,i),l=`DELETE FROM ${e.sql} AS t WHERE true${c.sql} RETURNING ${Z(e,"t")}`;break}case"select":{let c="";if(n.limit!==void 0){let w=Number(n.limit);if(!Number.isInteger(w)||w<0)throw new Error(`transaction plan (${n.table}): limit must be an integer, got "${String(n.limit)}"`);c=` LIMIT ${w}`}let d=n.lock==="update"?" FOR UPDATE":"";l=`SELECT ${Z(e,"t")} FROM ${e.sql} t WHERE true${Ds(t,e,n.where,o,s,i).sql}${c}${d}`;break}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}return{sql:l,params:r}}function wl(t,e){let n=t.guard;if(!n)return;let s=e.rows.length;if(!(n.kind==="one"?s===1:n.kind==="none"?s===0:n.kind==="atLeast"?s>=n.n:s<=n.n))throw Object.assign(new Error(`transaction expectation failed: ${n.kind} (${s} row(s))`),{error_code:"tx_guard_failed",slot:n.slot})}import{AsyncLocalStorage as ai}from"node:async_hooks";import{randomUUID as $l}from"node:crypto";var Dt=new ai,oi=()=>({running:new Set}),Tl=t=>String(t?.message??t);function Sl(t){return new tn(`The transaction was rolled back, not committed: a statement in it failed (${Tl(t)}) and the code went on. One failed statement aborts the whole transaction \u2014 Postgres refuses every later one and answers COMMIT with ROLLBACK. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row.`,t)}async function ii(t){for(;t.running.size;)await Promise.allSettled([...t.running])}function li(t,e){let n=e.bind;if(e.lockTimeout!==void 0&&(n+=`, set_config('lock_timeout', ${ne(e.lockTimeout)}, true)`),e.statementTimeout!==void 0&&(n+=`, set_config('statement_timeout', ${ne(e.statementTimeout)}, true)`),!/^select /i.test(n))throw new Error("palgres: the binding statement must be a SELECT list");n+=", pg_catalog.current_setting('transaction_isolation') AS palgres_isolation",e.prepared!==void 0&&(n+=`, pg_catalog.current_setting('palgres.session', true) AS palgres_session, CASE WHEN coalesce(pg_catalog.current_setting('palgres.session', true), '') = '' THEN pg_catalog.set_config('palgres.session', ${ne(e.prepared.mark())}, false) END AS palgres_marked, pg_catalog.set_config('plan_cache_mode', ${ne(Mo)}, true) AS palgres_plans`);let s=null,r=null,o=null,i=null,a=!1,l=null,c=oi(),d=!0,w,u=!1,m,f=async()=>!e.control||await e.control.drainCancellation()?!0:(m?.abandon?.(),!1),h,T=!1,g=(k,D,P,C)=>{if(e.prepared===void 0)return P;let v=P?.inline===!0;if(!v&&Fo(k))return h===void 0?T=!0:h.forget(),P;if(h===void 0)return e.prepared.count(k,D,v),P;if(C.refused!==void 0)return P;let I=h.run(k,D,v);return I===void 0?P:{...P,prepared:I}},p=()=>{u=!0},S=()=>{if(a)throw new Error("Database transaction has settled; its handle cannot be used again");if(e.control?.check(),e.trace?.check(),Dt.getStore()!==e.scope)throw new Error("Database.$atomic cannot use a handle from another transaction or identity; use its tx argument")},R,E,$=new Set,A=0,O=!1,L=()=>s!==null&&!a&&u&&c.running.size===0&&$.size===0,N=(k,D,P=S,C,v=new Set)=>{let I=()=>{if(P(),E!==C||R?.getStore()!==C)throw new Error("Database connection belongs to another active savepoint; use its tx argument and await it before using the parent handle")};return{unsafe(B,U,W){try{I()}catch(X){return Promise.reject(X)}W?.read!==!0&&(d=!1);let G=(U??[]).map(mn),K=()=>{let X=k.unsafe(B,G,g(B,G,W,D)),ee=Promise.resolve(e.control?e.control.watch(X):X).catch(oe=>{throw Kn(oe)&&(D.refused??={error:oe}),oe});return D.running.add(ee),A++,ee.catch(()=>{}).finally(()=>{D.running.delete(ee),p(),--A===0&&!a&&e.onIdle?.()}),ee};return e.trace?e.trace.query(B,K):K()},async savepoint(B){I(),d=!1;let U=Symbol("savepoint"),W=new Set,G=oi();R??=new ai,E=U;let K=(async()=>{try{return await k.savepoint(async X=>{let ee=!1,oe=()=>{if(P(),ee)throw new Error("Database savepoint has settled; its handle cannot be used again")};try{let Q=R.run(U,()=>B(N(X,G,oe,U,W))),xe=await(e.control?e.control.race(Q):Q);if(await ii(G),G.refused)throw G.refused.error;return xe}finally{W.size&&await Promise.allSettled([...W]),ee=!0}})}finally{E=C}})();$.add(K),v.add(K);try{return await K}finally{$.delete(K),v.delete(K)}}}},_=async()=>(S(),s||(s=new Promise((k,D)=>{let P=new Promise((C,v)=>{r=C,o=v});P.catch(()=>{}),i=(async()=>{let C=performance.now(),v;try{v=await(e.acquire?e.acquire(e.control?.signal):e.admission.acquire(e.claims,e.control?.signal))}finally{e.trace?.time("queueMs",C)}let I=performance.now(),B,U=e.control!==void 0&&t.cancelBackend!==void 0,W=[];if(e.isolation!==void 0||e.readOnly!==void 0){let de=e.isolation??"read committed";Qn({isolation:de,readOnly:e.readOnly}),W.push(`SET TRANSACTION ISOLATION LEVEL ${de.toUpperCase()}${e.readOnly===void 0?"":e.readOnly?" READ ONLY":" READ WRITE"}`)}W.push(U?`WITH backend AS MATERIALIZED (SELECT pid, backend_start::text AS started, xact_start::text AS xact_started FROM pg_catalog.pg_stat_get_activity(pg_catalog.pg_backend_pid())) ${n}, backend.pid, backend.started, backend.xact_started FROM backend`:n);let G=U&&t.cancelOpening!==void 0?`palgres:${$l()}`:void 0,K=!1,X=de=>{u=!0;let V=de[0];if(typeof V?.palgres_isolation=="string"&&(w=V.palgres_isolation),e.prepared!==void 0&&typeof V?.palgres_session=="string"&&V.palgres_session!==""&&(h=e.prepared.on(V.palgres_session),T&&h.forget()),!U)return;if(!Number.isInteger(V?.pid)||typeof V?.started!="string"||typeof V?.xact_started!="string"){let Ke=new Error("Database cancellation cannot identify its own backend");throw c.refused??={error:Ke},Ke}let ge={pid:V.pid,started:V.started,xactStarted:V.xact_started};K=!0,e.control.bindBackend(()=>t.cancelBackend(ge.pid,ge.started,ge.xactStarted))},ee=async()=>{for(let de=0;de<400&&!u&&!K;de++){if(await t.cancelOpening(G))return;await new Promise(V=>setTimeout(V,5))}},oe=v.openWithin,Q=!1,xe,re,Ae=()=>new Me({retryAfter:1},"Database queue deadline exceeded"),H=oe===void 0?void 0:new Promise((de,V)=>{re=setTimeout(()=>{u||(Q=!0,xe?.abandon?.(),V(Ae()))},oe)});H?.catch(()=>{});let ie=de=>t.begin(async V=>{B=performance.now(),e.trace?.time("poolMs",I);let ge=e.trace?performance.now():0;if(e.control?.check(),a)throw new Error("Database transaction closed while waiting for its connection");if(Q)throw Ae();if(G!==void 0&&!K&&e.control.bindBackend(ee),oe!==void 0&&!u){xe=V;try{await V.unsafe("SELECT 1")}catch(Ke){throw Q?Ae():Ke}}clearTimeout(re),e.trace?.time("setupMs",ge),de(),m=V,k(N(V,c)),await P},{sql:W.join("; "),opened:X,tag:G});try{if(e.control?.check(),a)throw new Error("Database transaction closed while waiting for admission");let de=!1;for(let V=1;;V++)try{let ge=ie(()=>{de=!0});return H===void 0?await ge:(ge.catch(()=>{}),await Promise.race([ge,H]))}catch(ge){let Ke=Ee(ge);if(de||a||Ke===void 0||V>=(Ke==="lost"?Rt:bt))throw ge;e.control?.check()}}finally{clearTimeout(re),B!==void 0&&e.trace?.time("connectionMs",B),v.release()}})().catch(C=>{throw D(C),C}),i.catch(()=>{})}),s.then(void 0,()=>{O=!0,a||e.onIdle?.()}),s)),y=k=>l??=(async()=>{if(a=!0,!s)return;await f(),$.size&&await Promise.allSettled([...$]);let D=e.trace?performance.now():0;o(k),await i?.catch(()=>{}),e.trace?.time("rollbackMs",D),e.trace?.rolledBack()})();return{ensure:_,get opened(){return s!==null},get busy(){return s!==null&&!a&&!O&&(!u||A>0)},get failed(){return O},get releasable(){return L()&&d&&c.refused===void 0&&(w==="read committed"||w==="read uncommitted")},async commit(){if($.size&&await Promise.allSettled([...$]),!s){e.trace?.check(),a=!0;return}await ii(c);try{if(e.trace?.check(),e.control?.checkDeadline(),c.refused)throw Sl(c.refused.error)}catch(D){throw await y(D),D}if(a=!0,!await f()){let D=De(new pe(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:!1},1));throw await y(D),D}let k=e.trace?performance.now():0;if(r(),d&&w!==void 0&&w!=="serializable"){i.then(()=>e.trace?.committed(),()=>e.trace?.commitFailed());return}try{await i,e.trace?.committed()}catch(D){throw e.trace?.commitFailed(),D}finally{e.trace?.time("commitMs",k)}},rollback:y}}var Rl="5s",bl="10s",Nl=new Set(["22P02","22007","22008","22003","22001"]),ci="55s",pi=1,Al=1e3,Wn=new Set,Bn,Ol=new mi("palgres.release");function kl(t){Wn.add(t),Bn===void 0&&(Bn=Ol.runInAsyncScope(()=>setInterval(()=>{let e=performance.now();for(let n of Wn){let s=!0;try{s=n(e)}catch{s=!0}s&&Wn.delete(n)}Wn.size===0&&(clearInterval(Bn),Bn=void 0)},pi)),Bn.unref?.())}function Ll(t,e){let n=[],s=d=>d!==null&&d.opened&&!d.failed,r=new Set,o,i=!1,a=()=>{for(let d of n)if(s(d.tx)&&d.tx.busy)return!0;for(let d of r)if(d.busy)return!0;return!1},l=mi.bind(d=>{if(o===void 0||a())return!0;let w=r.size,u=r.size===0;for(let f of n)s(f.tx)&&(w++,f.tx.releasable||(u=!1));if(w===0)return!0;let m=d-o;if(u){if(m<pi)return!1;for(let f of n){let h=f.tx;s(h)&&(f.tx=null,f.lease?.leave(),f.lease=void 0,h.commit().catch(()=>{}))}return o=void 0,!0}return e===void 0||i?!0:m<Al?!1:(i=!0,e(Math.round(m)),!0)}),c=()=>{a()||(o=performance.now(),kl(l))};return{onIdle:c,surface(d,w){let u={tx:null};n.push(u);let m=()=>{Wn.delete(l);let f=u.tx;return u.tx=null,u.lease=void 0,f};return{ensure(){if(o!==void 0&&(o=performance.now()),u.tx===null){if(t())return Promise.reject(new Error("Database transaction has settled; its handle cannot be used again"));u.tx=d(c,f=>w(f).then(h=>(u.lease=h,h)))}return u.tx.ensure()},commit:()=>m()?.commit()??Promise.resolve(),rollback:f=>m()?.rollback(f)??Promise.resolve()}},atomic(d){return r.add(d),()=>{r.delete(d)&&c()}}}}function Il(t){let e=ce(t),n=t?.code,s=o=>e!==void 0&&o.has(e)||typeof n=="string"&&o.has(n),r;if(s(sr))r=!0;else if(s(rr))r=!1;else return;return He(new pe(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:r},1),t)}var yn=t=>String(t?.message??t);function He(t,e){return t.cause=e,De(t)}function qs(t,e,n){if(typeof t=="object"&&t!==null&&ui.has(t))return t;let s=Cl(t,e,n);return typeof s=="object"&&s!==null&&ui.add(s),s}var ui=new WeakSet,Pt=(t,e,n)=>Object.assign(new Error(t,{cause:e}),{sqlstate:n});function Cl(t,e,n){if(tn.is(t))return t;let s=ce(t);if(s===le.inFailedTransaction||/current transaction is aborted/i.test(yn(t)))return Pt(`This request cannot write any more: an earlier write in it failed, and a request runs in ONE Postgres transaction, so every statement after the failure is refused. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row. (${yn(t)})`,t,le.inFailedTransaction);if(en.is(t))return t;if(s===le.uniqueViolation)return He(new en($n(t)),t);if(s===le.serializationFailure)return He(new Wt(s),t);if(s===le.deadlockDetected)return He(new jt(s),t);if(s===le.queryCancelled)return He(Object.assign(new pe(503,"database_query_cancelled","Database statement was cancelled"),{sqlstate:s}),t);let r=Il(t);if(r)return r;if(e==="service"&&s===le.foreignKeyViolation)return Pt(`Database.$asService() hit a foreign key with nothing to point at. It runs in its OWN transaction on its OWN connection, so a row this request wrote through \`Database.*\` is not visible to it until the request commits \u2014 and the request cannot commit until the handler returns. If the row it needs is one this request just created, do both writes on ONE surface. (${yn(t)})`,t,s);if(/lock timeout/i.test(yn(t))){let o;return e==="service"?o=Pt(`Database.$asService() waited too long for a row lock. It runs in its OWN transaction, so a row this request already wrote through Database.* is locked against it until the request commits \u2014 a wait that cannot end. Do that row's work on one surface or the other. (${yn(t)})`,t,s??le.lockNotAvailable):o=Pt(`Database waited too long for a lock. Another transaction holds it: a concurrent one, or another of this request's own \u2014 Database.*, $asService() and $atomic each run in their OWN transaction, and a row one of them wrote stays locked against the others until it commits, a wait that cannot end while the handler runs. Do that row's work on one surface. (${yn(t)})`,t,s??le.lockNotAvailable),He(Object.assign(new pe(503,"database_busy","The database waited too long for a lock",{retrySafe:!1},1),{sqlstate:s??le.lockNotAvailable}),o)}return s!==void 0&&Nl.has(s)?He(Object.assign(new pe(400,"invalid_value","A value is not one its column can take"),{sqlstate:s}),t):s===le.insufficientPrivilege&&n!==null?He(Object.assign(new pe(n==="anon"?401:403,"permission_denied","The database does not allow this caller to do this"),{sqlstate:s}),t):(s!==void 0&&typeof t=="object"&&t!==null&&!Object.hasOwn(t,"sqlstate")&&Object.defineProperty(t,"sqlstate",{value:s,enumerable:!0,configurable:!0}),t)}function vl(t,e,n){let s=r=>({unsafe(o,i,a){let l;try{l=r.unsafe(o,i,a)}catch(c){return Promise.reject(qs(c,e,n))}return Promise.resolve(l).then(rn,c=>{throw qs(c,e,n)})},savepoint:o=>r.savepoint(i=>o(s(i))),...r.abandon?{abandon:r.abandon.bind(r)}:{}});return{unsafe:(r,o)=>t.unsafe(r,o),begin:(r,o)=>t.begin(i=>r(s(i)),o).catch(i=>{throw qs(i,e,n)}),...t.cancelBackend?{cancelBackend:t.cancelBackend.bind(t)}:{},...t.cancelOpening?{cancelOpening:t.cancelOpening.bind(t)}:{}}}var xl=2,di={anon:"anon",authenticated:"authenticated",service:"service"};function _l(t,e){let n=Object.hasOwn(di,e.role)?di[e.role]:void 0;if(n===void 0)throw new Error(`palgres: a request is anon, authenticated or service, not "${String(e.role)}"`);return t[n]}function Us(t,e,n,s={}){let{signal:r}=s,o=s.diagnostics===void 0?void 0:new It(s.diagnostics),i=r===void 0?void 0:new pn(void 0,r),a=_l(e.roles,n),l=e.roles.service,c=n.role==="anon"||n.role==="authenticated"?n.role:null,d=n.claims,w=!1,u=!1,m=()=>{u&&ut.committed()},f=v=>{let I;return{cat:e.cat,trace:o,cursorKey:e.cursorKey,cursorScope:()=>I??=xo(v,d),search:e.search,searchable:()=>{u=!0}}},h=f(a),T=f(l),g=new Set,p=null,S=!1,R=0,E=new Set,$=v=>new Promise((I,B)=>{let U=X=>{E.delete(W),clearTimeout(K),v?.removeEventListener("abort",G),X===void 0?I():B(X)},W=()=>U(),G=()=>U(v?.reason??new Error("Database admission cancelled")),K=setTimeout(()=>U(new Me({retryAfter:1},"Database queue deadline exceeded")),e.admission.queueTimeoutMs);E.add(W),v?.addEventListener("abort",G,{once:!0}),v?.aborted&&G()}),A=async v=>{let I;for(;;){for(;g.size===0&&p!==null;)await p;let W=g.size>0;if(W){for(;R>=xl;)await $(v);R++}let G;try{let K=e.admission.acquire(d,v,{nested:W,returning:!W&&S}).then(X=>{if(W&&g.size===0)return X.release(),null;let ee={nested:W,turn:X};return g.add(ee),W||(S=!0),ee});if(!W){let X=K.then(()=>{},()=>{});p=X,X.then(()=>{p===X&&(p=null)})}G=await K}catch(K){throw W&&O(),K}if(G!==null){I=G;break}O()}let B=!1,U=()=>{if(!B){if(B=!0,g.delete(I),I.nested){O();return}for(let W of g){[I.turn,W.turn]=[W.turn,I.turn],W.nested=!1,I.nested=!0,O();return}}};return{queueMs:I.turn.queueMs,leave:U,release:()=>{U(),I.turn.release()},...I.nested&&e.binding.pooled===!0?{openWithin:e.admission.queueTimeoutMs}:{}}},O=()=>{R--;let v=E.values().next().value;v?.()},L=Ll(()=>w,s.heldIdle),N=(v,I,B={})=>li(vl(t,I,I==="user"?c:null),{bind:xn(e.binding,v,d),claims:d,admission:e.admission,acquire:A,trace:o,prepared:e.prepared,...B}),_=(v,I)=>async(B,U={})=>{if(Qn(U),w)throw new Error("Database request has settled; it cannot open another transaction");if(Dt.getStore()!==void 0)throw new Error("Nested Database.$atomic is not supported; use tx.$attempt for a savepoint");let W=zn(U.retry),G=U.signal&&r?AbortSignal.any([U.signal,r]):U.signal??r,K=U.timeoutMs!==void 0||G!==void 0?new pn(U.timeoutMs,G):void 0;try{K?.check();for(let X=0;;X++){K?.check();let ee=[U.statementTimeoutMs,K?.remainingMs()].filter(re=>re!==void 0),oe=Symbol("atomic transaction"),Q=N(v,I,{scope:oe,isolation:U.isolation,readOnly:U.readOnly,control:K,lockTimeout:`${U.lockTimeoutMs??5e3}ms`,statementTimeout:ee.length===0?void 0:`${Math.min(...ee)}ms`,onIdle:L.onIdle}),xe=L.atomic(Q);try{let re=Un(()=>Q.ensure(),I==="user"?h:T),Ae=Dt.run(oe,()=>B(re)),H=await(K?K.race(Ae):Ae);return await Q.commit(),m(),H}catch(re){await Q.rollback(re);let Ae=nn(re)||tn.is(re)&&nn(re.cause);if(X>=W||!Ae)throw re;o?.retry();let H=new Promise(ie=>setTimeout(ie,Math.min(100,2**X)));await(K?K.race(H):H)}finally{xe()}}}finally{K?.dispose()}},y=L.surface((v,I)=>N(a,"user",{lockTimeout:bl,statementTimeout:ci,control:i,onIdle:v,acquire:I}),A),k=null,D,P=null,C=()=>{if(P===null){if(w)throw new Error("Database request has settled; it cannot open another transaction");D=r===void 0?void 0:new pn(void 0,r);let v=D,I=L.surface((B,U)=>N(l,"service",{lockTimeout:Rl,statementTimeout:ci,control:v,onIdle:B,acquire:U}),A);k=I,P=Object.assign(Un(()=>I.ensure(),T),{atomic:_(l,"service")})}return P};return{client:Object.assign(Un(()=>y.ensure(),h),{asService:C,atomic:_(a,"user")}),async commit(){w=!0;try{try{o?.check()}catch(v){throw await y.rollback(v),await k?.rollback(v),v}try{await y.commit()}catch(v){throw await k?.rollback(v),v}await k?.commit(),m(),o?.complete("committed"),i?.dispose(),D?.dispose()}catch(v){throw o?.failed(),v}},async rollback(v){w=!0,await y.rollback(v),await k?.rollback(v),i?.dispose(),D?.dispose(),o?.complete("failed")}}}function Dl(t){if(t.codec!==void 0&&t.codec in sn)return sn[t.codec].tsType;switch(t.type){case"uuid":case"text":case"timestamp":case"date":return"string";case"sql":return t.sqlType!==void 0&&Gn.has(t.sqlType)?"number":t.sqlType!==void 0&&Xn.has(t.sqlType)?"Json":"string";case"integer[]":return"number[]";case"boolean[]":return"boolean[]";case"uuid[]":case"text[]":case"bigint[]":case"numeric[]":case"timestamp[]":case"date[]":return"string[]";case"integer":return"number";case"bigint":case"numeric":return"string";case"boolean":return"boolean";case"jsonb":return"Json";case"enum":{let e=t.enumValues??[];return e.length===0?"string":e.map(n=>JSON.stringify(n)).join(" | ")}case"enum[]":{let e=t.enumValues??[];return e.length===0?"string[]":`(${e.map(n=>JSON.stringify(n)).join(" | ")})[]`}default:{let e=t.type;throw new Error(`env-gen: the column type "${String(e)}" has no TypeScript type \u2014 add a case to baseTsType`)}}}function Pl(t){if(t.encrypted!==void 0)return t.encrypted.lookup?"encrypted:lookup":"encrypted";if(t.type==="enum"){let e=[...t.enumValues??[]].sort();return e.length===0?"enum":`enum:${e.join("|")}`}return t.type}function fi(t){let e=`Pg<${Dl(t)}, ${JSON.stringify(Pl(t))}>`;return t.nullable?`${e} | null`:e}function Ml(t){return t.nullable===!0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultValue!==void 0||t.defaultSql!==void 0||t.dbAssigned===!0||t.identity!==void 0}function Fl(t){return t.identity==="always"||t.generated!==void 0}var jn=t=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t);function gi(t,e,n){let s=Object.entries(t.columns).filter(([,a])=>a._def.ignored!==!0),r=s.map(([a,l])=>`${n} ${jn(a)}: ${fi(l._def)};`),o=s.filter(([,a])=>!Fl(a._def)).map(([a,l])=>`${n} ${jn(a)}${Ml(l._def)?"?":""}: ${fi(l._def)};`),i=e.map(a=>`${jn(a.name)}: { to: ${JSON.stringify(a.to)}; kind: ${JSON.stringify(a.kind)}; via: ${JSON.stringify(a.via)} }`).join("; ");return[`${n}${jn(t.name)}: {`,`${n} row: {`,...r,`${n} };`,`${n} insert: {`,...o,`${n} };`,`${n} relations: {${i===""?"":` ${i} `}};`,`${n} uniqueKeys: ${JSON.stringify(At(t))};`,...t.search!==void 0?[`${n} searchable: true;`]:[],`${n}};`].join(`
|
|
405
|
-
`)}function
|
|
404
|
+
`).slice(0,2500));let o=performance.now(),i=!1;try{let a=await n();return r.durationMs=performance.now()-o,i=!0,Array.isArray(a)&&(r.rows=a.length,r.bytes=Buffer.byteLength(JSON.stringify(a,(l,c)=>typeof c=="bigint"?c.toString():c))),this.state.rows+=r.rows,this.state.bytes+=r.bytes,this.options.maxRows!==void 0&&this.state.rows>this.options.maxRows&&this.refuse("returned rows"),this.options.maxBytes!==void 0&&this.state.bytes>this.options.maxBytes&&this.refuse("result bytes"),a}catch(a){let l=a;throw r.errorCode=String(l?.errno??l?.code??"query_failed").slice(0,80),a}finally{i||(r.durationMs=performance.now()-o),this.state.sqlMs+=r.durationMs;let a=Object.freeze(r);this.state.statements.length<200&&this.state.statements.push(a),this.emit(this.options.onQuery,a)}}get snapshot(){return Object.freeze({...this.state,elapsedMs:(this.ended??performance.now())-this.start,statements:Object.freeze([...this.state.statements].sort((e,n)=>e.ordinal-n.ordinal))})}complete(e){this.ended===void 0&&(this.ended=performance.now(),this.state.outcome=e,this.emit(this.options.onComplete,this.snapshot))}};var Jo=new WeakMap,zo=new WeakSet;function se(t){let e=n=>`$${t.push(n)}`;return Jo.set(e,t),e}var Os=t=>zo.has(t);var Qo=t=>`'${t.replace(/'/g,"''")}'`;function Le(t,e){let n=t.columns.get(e);return n?Do(n):null}function ue(t,e,n,s){if(!t.columns.has(e))throw t.ignored.has(e)?new Error(`${n}(${t.key}): ${s} "${e}" is .ignored() in this version \u2014 the version has promised not to name it, so the next one can drop it`):new Error(`${n}(${t.key}): ${s} "${e}" is not a column of the table`)}function Ce(t,e,n){if(t.encrypted.has(e))throw new Error(`palgres: ${t.key}.${e} is .encrypted() \u2014 its value is not bound as it is (an engine path that reached it without sealing it)`);if(n==null)return n;let s=t.transforms.get(e)?.toDb,r=s===void 0?n:s(n),o=Le(t,e);return o===null||r===null||r===void 0?r:o.endsWith("[]")&&Array.isArray(r)?_n(r):Po(o)?JSON.stringify(r):r}function Zo(t,e){return e.flatMap(n=>{let s=t.encrypted.get(n)?.lookup;return s?[n,s]:[n]})}function je(t,e){return Zo(t,e).map(q).join(", ")}function ul(t,e,n){return e.map(s=>{let r=t.encrypted.get(s);if(r===void 0)return s;if(r.lookup===null)throw new Error(`${n}(${t.key}): onConflict names "${s}", which is .encrypted() without { lookup: true } \u2014 no key is kept on it`);return r.lookup})}function ei(t,e,n,s,r,o){if(bn(s)!==null)throw new Error(`${o}(${t.key}): "${e}" is .encrypted() \u2014 the database holds no value there to compute with; write the value`);if(s===null)return n.lookup?[r(null),r(null)]:[r(null)];if(typeof s!="string")throw new TypeError(`${o}(${t.key}): "${e}" is .encrypted(), a text column \u2014 got ${typeof s}`);let{cipher:i,sealing:a}=t.fields;a.get(n.address)?.direction==="seal"&&st(n.address,s);let l=r(i.encrypt(n.address,s)),c=a.get(n.address)?.direction==="seal"?`CASE WHEN EXISTS (SELECT 1 FROM ${ye} WHERE address = ${r(n.address)} AND phase = 'mixed') THEN ${r(s)}::text ELSE ${l}::text END`:l;return n.lookup?[c,r(i.lookup(n.address,s))]:[c]}function ni(t,e,n,s,r){let o=t.encrypted.get(e);return o===void 0?null:ei(t,e,o,n,s,r)}function ti(t,e,n,s,r){let o=t.encrypted.get(n);return o===void 0?[r(ks(t,e,n,s))]:(Rn(e,t.key,[n],s),Yt(e,t.key,[n],s),ei(t,n,o,s[n],r,e))}function xt(t,e,n,s){if(t.encrypted.has(e))throw new Error(`${n}(${t.key}): ${s} names "${e}", which is .encrypted() \u2014 the database holds its ciphertext, not its value, so nothing there orders, ranges, groups or matches it`)}function si(t,e,n){let s=n.find(r=>t.databaseOnly.has(r));if(s!==void 0)throw new Error(`${e}(${t.key}): "${s}" is written by the database (an ALWAYS .identity()) \u2014 leave it out of the write; Postgres refuses any value for it`)}function En(t,e,n){for(let s of n)ue(t,s,e,"column");si(t,e,n)}function ks(t,e,n,s){return Rn(e,t.key,[n],s),Yt(e,t.key,[n],s),Ce(t,n,s[n])}function Is(t,e,n){let s=`${n?`${q(n)}.`:""}${q(e)}`;return Qe(Le(t,e),s)??s}function ri(t,e,n){let s=Is(t,e,n);return Qe(Le(t,e),"x")!==null?`${s} AS ${q(e)}`:s}function ee(t,e){let n=e??"",s=t.projections.get(n);return s===void 0&&(s=[...t.columns.keys()].map(r=>ri(t,r,e)).join(", "),t.projections.set(n,s)),s}function Ls(t,e,n){if(Y(e,"select","which columns a call reads"),e!==void 0&&e.length===0)throw new Error(`${n}(${t.key}): select got an empty list \u2014 that is not "all of them" but "none counted". Leave the key out for every column; name at least one otherwise.`);return e===void 0?ee(t,"t"):e.map(s=>(ue(t,s,n,"select column"),ri(t,s,"t"))).join(", ")}function oi(t,e,n,s="t"){if(e==null)return"";Y(e,"orderBy","the order");let r=Array.isArray(e)?e:[e];return r.length===0?"":` ORDER BY ${r.map(i=>{Y(i,"orderBy","the order"),ue(t,i.column,n,"orderBy column"),xt(t,i.column,n,"orderBy");let a=i.direction==="desc"?"DESC":"ASC",l=i.nulls==="first"?" NULLS FIRST":i.nulls==="last"?" NULLS LAST":"";return`${q(s)}.${q(i.column)} ${a}${l}`}).join(", ")}`}function As(t,e="findMany"){if(t===void 0)return"";if(!Number.isInteger(t)||t<0)throw new Error(`${e}: limit must be a non-negative integer (got ${String(t)})`);return` LIMIT ${t}`}function dl(t,e,n="findMany"){if(t===void 0)return"";if(!Number.isInteger(t)||t<0)throw new Error(`${n}: offset must be a non-negative integer (got ${String(t)})`);if(e===void 0)throw new Error(`${n}: offset is given only with limit \u2014 an offset without one is the shifted tail of an unbounded result, not a page`);return` OFFSET ${t}`}var hn={gt:">",gte:">=",lt:"<",lte:"<=",neq:"<>"},ml=[["days","days","int"],["hours","hours","int"],["minutes","mins","int"],["seconds","secs","double precision"]];function gn(t,e){let n=t?.minus;if(n===void 0)return"now()";let s=wr(n);if("refused"in s)throw new TypeError(`palgres: ago() ${s.refused}`);return`(now() - make_interval(${ml.filter(([o])=>s.span[o]!==void 0).map(([o,i,a])=>`${i} => ${e(s.span[o])}::${a}`).join(", ")}))`}var Xo=Object.freeze({update:"FOR UPDATE",share:"FOR SHARE",noKeyUpdate:"FOR NO KEY UPDATE"});function Cs(t,e,n,s){if(typeof s=="string"&&Object.hasOwn(Xo,s))return Xo[s];let r=typeof s=="string"?JSON.stringify(s.slice(0,40)):typeof s;throw new TypeError(`${t}(${e}): unknown ${n} ${r} \u2014 "update" (FOR UPDATE), "share" (FOR SHARE) or "noKeyUpdate" (FOR NO KEY UPDATE).`)}var Vo=t=>bn(t);function Yo(t,e,n,s){if(!t.columns.has(e.$col))throw new Error(`${n}(${t.key}): col("${e.$col}") is not a column of the table`);return`${q(s)}.${q(e.$col)}`}function ii(t,e,n,s){let o=(n.kind==="many"?t.table(n.to,s):e).columns.get(n.via)?.references?.column??(n.kind==="many"?e.singleKey:t.table(n.to,s).singleKey);return n.kind==="many"?[o,n.via]:[n.via,o]}function Ze(t,e,n){return De(new Pe({fields:[{field:e,message:n}]},`${t}: ${e} ${n}`))}function pl(t,e){if(Y(t,e,"a filter"),!(typeof t!="object"||t===null))for(let[n,s]of Object.entries(t))n==="OR"||n==="AND"||n==="NOT"||n==="has"?Y(s,`${e}.${n}`,`a filter's ${n}`):s!==null&&typeof s=="object"&&!Array.isArray(s)&&Y(s,`${e}.${n}`,"an operator")}function vt(t,e,n,s,r,o,i,a){let l=[];if(pl(n,a),yr(r,e.key,n),an(n)){let{text:c,values:d}=n.$sql,y=Jo.get(s);if(y===void 0)throw new Error("palgres: an sqlFragment was compiled outside binder()");if(zo.add(y),c.length!==d.length+1)throw new Error(`${r}(${e.key}): the sqlFragment's parts are broken (${c.length} texts, ${d.length} values) \u2014 only the template tag makes one`);let u=c[0]??"";for(let m=0;m<d.length;m++)u+=`${s(d[m])}${c[m+1]??""}`;if(u.trim()==="")throw Ze(r,a,"is an empty sqlFragment \u2014 no condition. Write the condition in it, or leave it out.");return[`(${u})`]}for(let[c,d]of Object.entries(n)){if(c==="OR"||c==="AND"){let g=d;if(g.length===0){if(c==="AND")throw Ze(r,`${a}.AND`,"is an empty list \u2014 no condition at all. Leave it out, or name a condition in it.");l.push("false");continue}let T=g.map((h,p)=>{let S=vt(t,e,h,s,r,o,i,`${a}.${c}[${p}]`);if(S.length===0)throw Ze(r,`${a}.${c}[${p}]`,"holds no condition \u2014 a branch that matches every row. Name a condition in it, or leave it out.");return`(${S.join(" AND ")})`});l.push(`(${T.join(c==="OR"?" OR ":" AND ")})`);continue}if(c==="NOT"){if(Array.isArray(d))throw Ze(r,`${a}.NOT`,"is a list \u2014 NOT takes one filter object. For several conditions, NOT: { AND: [...] } or NOT: { OR: [...] }.");let g=vt(t,e,d,s,r,o,i,`${a}.NOT`);if(g.length===0)throw Ze(r,`${a}.NOT`,"holds no condition \u2014 NOT of nothing is not a filter. Name the condition to exclude.");l.push(`NOT (${g.join(" AND ")})`);continue}if(c==="has"){let g=Object.entries(d);if(g.length===0)throw Ze(r,`${a}.has`,"names no relation \u2014 no condition. Name one: has: { <relation>: { \u2026 } }.");for(let[T,h]of g){let p=e.relations.find(L=>L.name===T);if(p===void 0){let L=e.relations.map(k=>k.name).sort();throw new Error(`${r}(${e.key}): there is no relation has.${T}`+(L.length>0?` (known: ${L.join(", ")}). Relations come from foreign keys; to rename one, references(..., { as, reverseAs }).`:". The table declares no foreign key, and relations come from them: references(() => <table>.<column>)."))}let[S,b]=ii(t,e,p,r);if(S===null||b===null)throw new Error(`${r}(${e.key}): has.${T} cannot be built \u2014 "${S===null?e.key:p.to}" has no single-column primary key to correlate on; write the condition as an sqlFragment`);let E=t.table(p.to,r),$=`r${i+1}`,A=Fn(t,E,h??{},s,r,$,i+1,`${a}.has.${T}`),I=`${$}.${q(b)} = ${q(o)}.${q(S)}`;l.push(`EXISTS (SELECT 1 FROM ${E.sql} ${$} WHERE ${I}${A===""?"":` AND ${A}`})`)}continue}ue(e,c,r,"where column");let y=e.encrypted.get(c);if(y!==void 0){l.push(fl(e,c,y,d,s,r,o,a));continue}let u=`${q(o)}.${q(c)}`,m=Le(e,c)?.endsWith("[]")===!0,f=g=>s(Ce(e,c,g));if(Me(d)){l.push(`${u} = ${Yo(e,d,r,o)}`);continue}if(zn(d)){l.push(`${u} = ${gn(Vo(d),s)}`);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d))for(let[g,T]of Object.entries(d)){if(m&&(g==="contains"||g==="overlaps")){if(!Array.isArray(T))throw new Error(`${r}(${e.key}): where.${c}.${g} must be an array \u2014 ${c} is an array column`);l.push(`${u} ${g==="contains"?"@>":"&&"} ${f(T)}`);continue}if(!m&&(g==="contains"||g==="icontains"||g==="startsWith"||g==="endsWith")){if(typeof T!="string")throw new Error(`${r}(${e.key}): where.${c}.${g} must be a string`);let p=T.replace(/([\\%_])/g,"\\$1"),S=g==="startsWith"?`${p}%`:g==="endsWith"?`%${p}`:`%${p}%`;l.push(`${u} ${g==="icontains"?"ILIKE":"LIKE"} ${s(S)}`);continue}if(g==="isNull"){if(typeof T!="boolean")throw new Error(`${r}(${e.key}): where.${c}.isNull must be a boolean`);l.push(`${u} IS ${T?"NULL":"NOT NULL"}`);continue}if(g==="in"){if(!Array.isArray(T))throw new Error(`${r}(${e.key}): where.${c}.in must be an array`);if(T.some(Me))throw new Error(`${r}(${e.key}): where.${c}.in takes values, not col() \u2014 compare with a column bare ({ ${c}: col("\u2026") }) or with gt/gte/lt/lte/neq`);if(T.length===0){l.push("false");continue}l.push(`${u} IN (${T.map(p=>f(p)).join(", ")})`);continue}if(zn(T)){if(!(g in hn))throw new Error(`${r}(${e.key}): where.${c}.${g} cannot take now() \u2014 for equality write it bare: { ${c}: now() }`);l.push(`${u} ${hn[g]} ${gn(Vo(T),s)}`);continue}if(Jn(T))throw new Error(`${r}(${e.key}): where.${c}.${g} got a WRITE expression (increment/decrement), not a comparison value. For the server's time use now(); for a numeric threshold, the value.`);if(Me(T)){if(!(g in hn))throw new Error(`${r}(${e.key}): where.${c}.${g} cannot take col() \u2014 for equality write it bare: { ${c}: col("\u2026") }`);l.push(`${u} ${hn[g]} ${Yo(e,T,r,o)}`);continue}let h=Er(T);if(h!==null){let p=h==="col"?"col()":h==="sql"?"sqlFragment":"now()";throw new Error(`${r}(${e.key}): where.${c}.${g} got an imitation of ${p} \u2014 this object was not made by ${p} in this process. A filter from a request body cannot carry a handle; build the condition in your code.`)}if(g in hn){if(T===null&&g==="neq"){l.push(`${u} IS NOT NULL`);continue}l.push(`${u} ${hn[g]} ${f(T)}`);continue}throw new Error(`${r}(${e.key}): where.${c} has an unknown operator "${g}" (gt/gte/lt/lte/neq/in)`)}else d===null?l.push(`${u} IS NULL`):l.push(`${u} = ${f(d)}`)}return l}function fl(t,e,n,s,r,o,i,a){let l=`${q(i)}.${q(e)}`;if(s===null)return`${l} IS NULL`;let c=g=>{throw new Error(`${o}(${t.key}): ${a}.${e} ${g} \u2014 "${e}" is .encrypted(): the database holds its ciphertext, so it is asked only isNull`+(n.lookup?", equality and in":" (equality needs .encrypted({ lookup: true }))"))};(Me(s)||zn(s)||an(s))&&c("compares with an expression");let{cipher:d,sealing:y}=t.fields,u=y.get(n.address)!==void 0,m=g=>{if(n.lookup===null&&c("asks for equality"),g.some(b=>typeof b!="string")&&c("compares with a value that is not text"),g.length===0)return"false";let T=`${q(i)}.${q(n.lookup)}`,h=g.map(b=>r(d.lookup(n.address,b))),p=g.length===1?`${T} = ${h[0]}`:`${T} IN (${h.join(", ")})`;if(!u)return p;let S=g.map(b=>r(b));return`(${p} OR ${g.length===1?`${l} = ${S[0]}`:`${l} IN (${S.join(", ")})`})`};if(typeof s!="object"||Array.isArray(s))return m([s]);let f=[];for(let[g,T]of Object.entries(s))if(g==="isNull"){if(typeof T!="boolean")throw new Error(`${o}(${t.key}): where.${e}.isNull must be a boolean`);f.push(`${l} IS ${T?"NULL":"NOT NULL"}`)}else if(g==="in"){if(!Array.isArray(T))throw new Error(`${o}(${t.key}): where.${e}.in must be an array`);f.push(m(T))}else g==="neq"?f.push(T===null?`${l} IS NOT NULL`:`(${l} IS NOT NULL AND NOT ${m([T])})`):c(`asks ${g}`);return f.length===0&&c("holds no condition"),f.length===1?f[0]:`(${f.join(" AND ")})`}function Fn(t,e,n,s,r,o="t",i=0,a="where"){return vt(t,e,n,s,r,o,i,a).join(" AND ")}function ve(t,e,n,s,r){let o=vt(t,e,n,s,r,"t",0,"where");return{sql:o.length===0?"":` AND ${o.join(" AND ")}`,conditions:o.length}}function yn(t,e){if(!(t.conditions>0))throw Ze(e,"where",`holds no condition, so ${e} would reach EVERY row of the table. Name a condition.`)}function Mn(t,e,n,s,r){let o=Zo(t,e),i=ul(t,n,r);if(s!=="ignore"&&s!=="update")throw new TypeError(`palgres: a conflict's action is "ignore" or "update", not ${typeof s=="string"?JSON.stringify(String(s).slice(0,40)):typeof s}`);if(i.length===0){if(s==="ignore")return"ON CONFLICT DO NOTHING";throw new Error("palgres: ON CONFLICT DO UPDATE needs the columns a collision is matched on")}let a=`ON CONFLICT (${i.map(q).join(", ")})`;if(s==="ignore")return`${a} DO NOTHING`;let l=new Set(i),c=o.filter(d=>!l.has(d)).map(d=>`${q(d)} = EXCLUDED.${q(d)}`);return c.length?`${a} DO UPDATE SET ${c.join(", ")}`:`${a} DO UPDATE SET ${q(i[0])} = EXCLUDED.${q(i[0])}`}function vs(t,e,n,s,r){return si(t,r,e),e.map(o=>{let i=t.encrypted.get(o);if(i!==void 0){let[l,c]=ti(t,r,o,n,s);return`${q(o)} = ${l}${i.lookup?`, ${q(i.lookup)} = ${c}`:""}`}let a=bn(n[o]);if(a!==null&&a.fn==="now")return`${q(o)} = ${gn(a,s)}`;if(a!==null){let l=t.transforms.get(o)?.toDb,c=l===void 0?a.by:l(a.by);return`${q(o)} = ${q(o)} ${a.fn==="inc"?"+":"-"} ${s(c)}`}return`${q(o)} = ${s(ks(t,r,o,n))}`}).join(", ")}function qn(t,e,n,s,r){return e.map(o=>{if(t.encrypted.has(o))return ti(t,r,o,n,s).join(", ");let i=bn(n[o]);if(i!==null&&i.fn==="now")return gn(i,s);if(i!==null){let a=i.fn==="inc"?"increment":"decrement";throw new Error(`${r}(${t.key}): "${o}" got ${a}() \u2014 the row does not exist yet, so there is no current value. Write the starting value; to change it once the row exists, updateMany({ where, set: { ${o}: ${a}(n) } }).`)}return s(ks(t,r,o,n))}).join(", ")}var hl=new Set(["integer","bigint","numeric"]);function ai(t){return t!==null&&hl.has(t)}function li(t,e,n,s){xt(t,n,"aggregate",e);let r=`t.${q(n)}`,o=Le(t,n);if(e==="sum"||e==="avg")return`${e}(${r})::text AS ${q(s)}`;let i=o!==null&&!o.endsWith("[]")?Qe(o,`${e}(${r})`):null;return i!==null?`${i} AS ${q(s)}`:o==="bigint"||o==="numeric"?`${e}(${r})::text AS ${q(s)}`:`${e}(${r}) AS ${q(s)}`}function gl(t,e,n,s=[]){return`json_build_object(${[...e.map(o=>{let i=Le(t,o),a=`${n}.${q(o)}`,l=i==="numeric"||i==="bigint"?`${a}::text`:Qe(i,a)??a;return`${Qo(o)}, ${l}`}),...s].join(", ")})`}function _t(t,e,n,s,r,o="t",i=0,a={value:0}){if(Y(n,"with","which relations a call reads"),i>=3&&Object.values(n).some(Boolean))throw new Error(`${r}(${e.key}): with supports at most three relation levels`);let l=[],c=[],d=[];for(let[y,u]of Object.entries(n)){if(u===!1||u===void 0)continue;Y(u,`with.${y}`,"which relations a call reads");let m=e.relations.find(w=>w.name===y);if(m===void 0){let w=e.relations.map(O=>O.name).sort();throw new Error(`${r}(${e.key}): there is no relation with.${y}`+(w.length>0?` (known: ${w.join(", ")})`:". The table declares no foreign key, and relations come from them")+". A relation is declared with references(() => <table>.<column>).")}let[f,g]=ii(t,e,m,r);if(f===null||g===null)throw new Error(`${r}(${e.key}): with.${y} needs a single-column primary key at one end of the relation`);let T=t.table(m.to,r),h=typeof u=="object"&&u!==null?u:{},p=++a.value,S=`w${p}`;if(Y(h.select,`with.${y}.select`,"which columns a call reads"),Y(h.orderBy,`with.${y}.orderBy`,"the order"),h.select!==void 0&&(!Array.isArray(h.select)||h.select.length===0))throw new Error(`${r}(${e.key}): with.${y}.select must be a non-empty array of columns`);let b=Array.isArray(h.select)?h.select:[...T.columns.keys()];for(let w of b)ue(T,w,r,`with.${y}.select column`);let E=h.with;if(E!==void 0&&(E===null||typeof E!="object"||Array.isArray(E)))throw new Error(`${r}(${e.key}): with.${y}.with must be a relation object`);let $=E===void 0?{joins:[],jsonPairs:[]}:_t(t,T,E,s,r,S,i+1,a),A=$.joins.length?` ${$.joins.join(" ")}`:"",I=gl(T,b,S,$.jsonPairs),L=h.where!==void 0&&h.where!==null?Fn(t,T,h.where,s,r,S,p,`with.${y}.where`):"",k=`${S}.${q(g)} = ${q(o)}.${q(f)}`,x=L===""?k:`${k} AND ${L}`,R=h.limit;As(R,r);let _=m.kind==="many"?R:Math.min(1,R??1),P=oi(T,h.orderBy,r,S)+As(_,r),B=`wj${p}`;m.kind==="many"?c.push(`LEFT JOIN LATERAL (SELECT coalesce(json_agg(x.o), '[]'::json) AS d FROM (SELECT ${I} AS o FROM ${T.sql} ${S}${A} WHERE ${x}${P}) x) ${q(B)} ON true`):c.push(`LEFT JOIN LATERAL (SELECT ${I} AS d FROM ${T.sql} ${S}${A} WHERE ${x}${P}) ${q(B)} ON true`),l.push(`${q(B)}."d" AS ${q(y)}`),d.push(`${Qo(y)}, ${q(B)}."d"`)}return{select:l,joins:c,jsonPairs:d}}function xs(t,e,n,s){let r=[],o=se(r),i=ve(t,e,n,o,"findMany").sql,a=oi(e,s.orderBy,"findMany"),l=As(s.limit),c=dl(s.offset,s.limit),d=Ls(e,s.select,"findMany"),y=s.with!==void 0&&Object.keys(s.with).length>0?_t(t,e,s.with,o,"findMany"):{select:[],joins:[]},u=y.select.length>0?`${d}, ${y.select.join(", ")}`:d,m=y.joins.length>0?` ${y.joins.join(" ")}`:"",f=s.lock===void 0?"":` ${Cs("findUnique",e.key,"lock",s.lock)} OF t`;return{sql:`SELECT ${u} FROM ${e.sql} t${m} WHERE true${i}${a}${l}${c}${f}`,params:r}}var Ns=50;function _s(t,e,n,s){if(e.search===void 0||e.singleKey===null)throw new Error(`search(${e.key}): the table declares no search`);if(n.text===void 0&&n.vector===void 0)throw new Error(`search(${e.key}): neither the query's words nor its vector to search by`);let r=[],o=se(r),i=q(e.singleKey),a=ve(t,e,s.where??{},o,"search").sql,l=Math.max(s.limit*3,30),c=[];if(n.vector!==void 0){let y=`v."embedding" ${n.vector.operator} ${o(n.vector.literal)}::${n.vector.type}`;c.push(`sem AS (SELECT s."id", row_number() OVER (ORDER BY s."d", s."id") AS r FROM (SELECT t.${i} AS "id", ${y} AS "d" FROM ${n.vector.table} v JOIN ${e.sql} t ON t.${i} = v."id" WHERE true${a} ORDER BY ${y} LIMIT ${l}) s)`)}if(n.text!==void 0){let y=at(e.search.from,"t"),u=`websearch_to_tsquery('simple', ${o(n.text)})`;c.push(`kw AS (SELECT s."id", row_number() OVER (ORDER BY s."k" DESC, s."id") AS r FROM (SELECT t.${i} AS "id", ts_rank_cd(${y}, ${u}) AS "k" FROM ${e.sql} t WHERE ${y} @@ ${u}${a} ORDER BY "k" DESC LIMIT ${l}) s)`)}c.push(c.length===2?`fused AS (SELECT coalesce(sem."id", kw."id") AS "id", (coalesce(1.0 / (${Ns} + sem.r), 0) + coalesce(1.0 / (${Ns} + kw.r), 0))::float8 AS "score" FROM sem FULL OUTER JOIN kw ON sem."id" = kw."id")`:`fused AS (SELECT x."id", (1.0 / (${Ns} + x.r))::float8 AS "score" FROM ${n.vector!==void 0?"sem":"kw"} x)`);let d=s.minScore===void 0?"":` AND f."score" >= ${o(s.minScore)}`;return{sql:`WITH ${c.join(", ")} SELECT ${ee(e,"t")}, f."score" AS "_score" FROM fused f JOIN ${e.sql} t ON t.${i} = f."id" WHERE true${d} ORDER BY f."score" DESC, t.${i} LIMIT ${El(s.limit)}`,params:r}}function El(t){if(!Number.isInteger(t)||t<1)throw new Error(`search: limit must be a positive integer (got ${String(t)})`);return t}function ci(t){return t instanceof Date?t.toISOString():Array.isArray(t)?t.map(ci):t}function Ds(t){if(t===null||typeof t!="object")return t;let e={};for(let[n,s]of Object.entries(t))e[n]=ci(s);return e}function yl(t,e){for(let[n,s]of e.transforms){if(s.fromDb===void 0)continue;let r=t[n];r!=null&&(t[n]=s.fromDb(r))}return t}function Pn(t,e,n,s){let r=n.map(o=>yl(Ds(o),e));if(s)for(let o of e.relations){let i=s[o.name];if(!i)continue;let a=typeof i=="object"?i.with:void 0,l=t.table(o.to,"with");for(let c of r){let d=c[o.name];Array.isArray(d)?c[o.name]=Pn(t,l,d,a):d&&typeof d=="object"&&(c[o.name]=Pn(t,l,[d],a)[0])}}return on(r)}var wl={inline:!0},Ps={inline:!0,read:!0},$l=t=>ce(t)===le.uniqueViolation||nn.is(t);function ui(t,e){if(e===null)return!1;let n=Object.keys(t);if(n.length!==1||n[0]!==e)return!1;let s=t[e];return s!==null&&(typeof s!="object"||Array.isArray(s))}var Tl=6e4;function Un(t,e){let{cat:n}=e,s=(u,m)=>n.table(u,m),r=(u,m)=>{let f=n.table(u,m);return f.search!==void 0&&e.searchable?.(),f},o=async(u,m=[],f=!1)=>await(await t()).unsafe(u,m,Os(m)?void 0:f?Ps:wl),i=(u,m=[])=>o(u,m,!0),a=async(u,m=[])=>await(await t()).unsafe(u,m),l=async(u,m)=>{let f=n.deferral(u);if(f===null)return m();await o(f.defer);let g=await m();return await o(f.check),g},c=(u,m,f)=>Pn(n,u,m,f),d=(u,m)=>Pn(n,u,[m])[0],y={diagnostics(){return e.trace?.snapshot??null},async query(u,m=[]){return on((await a(u,m)).map(f=>Ds(f)))},async insert(u,m){let f=r(u,"insert"),g=Object.keys(m);if(g.length===0)throw new Error(`insert into ${u}: no columns given`);En(f,"insert",g);let T=[],h=qn(f,g,m,se(T),"insert"),p=await o(`INSERT INTO ${f.sql} (${je(f,g)}) VALUES (${h}) RETURNING ${ee(f)}`,T);if(!p[0])throw new Error(`insert into ${u} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return d(f,p[0])},insertMany:(async function(u,m,f){if(Rr(f),m.length===0)return f?.returning===!1?0:[];let g=r(u,"insertMany"),T=Object.keys(m[0]);if(T.length===0)throw new Error(`insertMany into ${u}: no columns given`);for(let A=1;A<m.length;A++){let I=T.filter(k=>!(k in m[A])),L=Object.keys(m[A]).filter(k=>!T.includes(k));if(I.length>0||L.length>0)throw new Error(`insertMany(${u}): row ${A} does not have the first row's columns`+(I.length>0?` (missing: ${I.join(", ")})`:"")+(L.length>0?` (extra: ${L.join(", ")})`:"")+". One statement shares the column list: write null for a missing value, or insert differently shaped rows in calls of their own.")}En(g,"insertMany",T),Y(f?.onConflict,"onConflict","which columns a conflict is on");for(let A of f?.onConflict??[])ue(g,A,"insertMany","onConflict column");let h=[],p=se(h),S=m.map(A=>`(${qn(g,T,A,p,"insertMany")})`),b=f?.onConflict??[],E=b.length>0||f?.action==="ignore"?` ${Mn(g,T,b,f?.action??"ignore","insertMany")}`:"",$=await o(`INSERT INTO ${g.sql} (${je(g,T)}) VALUES ${S.join(", ")}${E}${f?.returning===!1?"":` RETURNING ${ee(g)}`}`,h);if(f?.returning===!1){if(!Number.isSafeInteger($.count)||$.count<0)throw new Error("insertMany returning:false requires a driver with an affected row count");return $.count}return c(g,$)}),async advisoryXactLock(u){await o("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",[u])},async lockRows(u,m){let f=[...new Set(m)].sort();if(f.length===0)return;let g=s(u,"lockRows");if(g.singleKey===null)throw new Error(`lockRows(${u}): no single-column primary key \u2014 the lock order needs one`);let T=q(g.singleKey),h=[],p=se(h),S=f.map(b=>p(Ce(g,g.singleKey,b))).join(", ");await o(`SELECT t.${T} FROM ${g.sql} t WHERE t.${T} IN (${S}) ORDER BY t.${T} FOR NO KEY UPDATE`,h)},async lockRowsWhere(u,m,f){let g=Cs("lockRowsWhere",u,"mode",f?.mode===void 0?"update":f.mode),T=s(u,"lockRowsWhere");if(T.singleKey===null)throw new Error(`lockRowsWhere(${u}): no single-column primary key \u2014 the lock order needs one`);let h=[],p=ve(n,T,m,se(h),"lockRowsWhere");yn(p,"lockRowsWhere");let S=q(T.singleKey);await o(`SELECT t.${S} FROM ${T.sql} t WHERE true${p.sql} ORDER BY t.${S} ${g}`,h)},async claim(u,m,f={}){let g=r(u,"claim");Y(m,"unique","which key a claim is on");let T=Object.keys(m);if(T.length===0)throw new Error(`claim(${u}): no unique field given. claim takes ownership of a key; with none there is nothing to own \u2014 use insert(${u}, \u2026).`);Rn("claim",u,T,m);for(let E of T){let $=m[E];if($===null||typeof $=="object"||typeof $=="function")throw new Error(`claim(${u}): the unique field "${E}" is ${$===null?"null":"an object"} \u2014 a key is one value (a string, number, bigint or boolean); NULL never equals a claimed row.`)}let h=Object.keys(f).filter(E=>Object.hasOwn(m,E));if(h.length>0)throw new Error(`claim(${u}): ${h.map(E=>`"${E}"`).join(", ")} is in both the unique fields and extra \u2014 say a key once, in the unique fields.`);let p={...m,...f},S=Object.keys(p);En(g,"claim",S);let b=await t();try{return await b.savepoint(async E=>{let $=[],A=qn(g,S,p,se($),"claim"),I=await E.unsafe(`INSERT INTO ${g.sql} (${je(g,S)}) VALUES (${A}) RETURNING ${ee(g)}`,$);if(!I[0])throw new Error(`claim(${u}): the INSERT returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return{inserted:!0,row:d(g,I[0])}})}catch(E){if(!$l(E))throw E;let $=[],A=se($),I=Fn(n,g,m,A,"claim"),L=await o(`SELECT ${ee(g,"t")} FROM ${g.sql} t WHERE ${I} LIMIT 1`,$);if(!L[0]){let k=Tn(E);throw new Error(`claim(${u}): a unique violation${k?` (${k})`:""} was caught but no row has these ${T.join(", ")}. Either the violation is of ANOTHER unique constraint \u2014 claim() is the wrong tool for this call \u2014 or the row exists and an RLS policy hides it from this caller.`)}return{inserted:!1,row:d(g,L[0])}}},async put(u,m,f){let g=r(u,"put"),T=f.onConflict;if(T.length===0)throw new Error(`put into ${u}: onConflict needs at least one column`);let h=Object.keys(m);if(h.length===0)throw new Error(`put into ${u}: no columns given`);En(g,"put",h),Y(T,"onConflict","which columns a conflict is on");for(let E of T)ue(g,E,"put","onConflict column");let p=[],S=qn(g,h,m,se(p),"put"),b=await o(`INSERT INTO ${g.sql} (${je(g,h)}) VALUES (${S}) ${Mn(g,h,T,"update","put")} RETURNING ${ee(g)}`,p);if(!b[0])throw new Error(`put into ${u} returned no row \u2014 the write was rejected (an RLS policy, most likely).`);return d(g,b[0])},async update(u,m,f){let g=r(u,"update");if(!g.columns.has("id"))throw new Error(`update(${u}): the table has no "id" column \u2014 update a row by its key with updateMany({ where, set })`);let T=Object.keys(f);if(T.length===0)return y.findById(u,m);for(let E of T)ue(g,E,"update","set column");let h=[],p=se(h),S=vs(g,T,f,p,"update"),b=await o(`UPDATE ${g.sql} SET ${S} WHERE "id" = ${p(Ce(g,"id",m))} RETURNING ${ee(g)}`,h);return b[0]?d(g,b[0]):null},async delete(u,m){let f=s(u,"delete");if(!f.columns.has("id"))throw new Error(`delete(${u}): the table has no "id" column \u2014 delete by its key with deleteMany({ where })`);let g=[Ce(f,"id",m)];await l(f,()=>o(`DELETE FROM ${f.sql} WHERE "id" = $1`,g))},async updateMany(u,m,f,g){let T=r(u,"updateMany"),h=Object.keys(f);if(h.length===0)throw new Error(`updateMany(${u}): nothing to set. An update with no columns is not a no-op worth pretending happened \u2014 pass the columns to write.`);for(let B of h)ue(T,B,"updateMany","set column");let p=[],S=se(p),b=vs(T,h,f,S,"updateMany"),E=ve(n,T,m,S,"updateMany");yn(E,"updateMany");let $=E.sql,A=T.singleKey,I=g?.returning!==!1,L=A===null||ui(m,A),k=I?`RETURNING ${ee(T,"t")}`:"RETURNING 1",x=L?`UPDATE ${T.sql} AS t SET ${b} WHERE true${$} ${k}`:`UPDATE ${T.sql} AS t SET ${b} FROM locked WHERE t.${q(A)} = locked."__pb_lock" ${k}`,R=L?"":`WITH locked AS (SELECT t.${q(A)} AS "__pb_lock" FROM ${T.sql} t WHERE true${$} ORDER BY t.${q(A)} FOR NO KEY UPDATE)`,_=I?`${R} ${x}`.trim():L?`WITH upd AS (${x}) SELECT count(*)::int AS n FROM upd`:`${R}, upd AS (${x}) SELECT count(*)::int AS n FROM upd`,P=await o(_,p);return I?c(T,P):Number(P[0]?.n??0)},async deleteMany(u,m){let f=s(u,"deleteMany"),g=[],T=ve(n,f,m,se(g),"deleteMany");return yn(T,"deleteMany"),(await l(f,()=>o(`DELETE FROM ${f.sql} AS t WHERE true${T.sql} RETURNING 1`,g))).length},async aggregate(u,m={}){let f=s(u,"aggregate");for(let k of["sum","avg","min","max","groupBy"])Y(m[k],k,"which columns an aggregate reads");Y(m.count,"count","which counts an aggregate takes");let g=[],T=se(g),h=[],p=[];for(let k of["sum","avg","min","max"])for(let x of m[k]??[]){if(ue(f,x,"aggregate",`${k} column`),(k==="sum"||k==="avg")&&!ai(Le(f,x)))throw new Error(`aggregate(${u}): ${k}("${x}") on a column that is not numeric \u2014 "${x}" is ${Le(f,x)}. Only integer, bigint and numeric sum; to count rows, count: true.`);let R=`${k}__${x}`;p.push({fn:k,col:x,alias:R}),h.push(li(f,k,x,R))}m.count===!0&&h.push('count(*) AS "_count"');let S=m.count!==null&&typeof m.count=="object"?Object.entries(m.count):[];if(m.count!==void 0&&typeof m.count!="boolean"&&(m.count===null||typeof m.count!="object"||Array.isArray(m.count)||S.length===0))throw new Error(`aggregate(${u}): count is true, or named filters \u2014 { <name>: <filter> }, at least one`);if(S.forEach(([k,x],R)=>{let _=Fn(n,f,x,T,"aggregate","t",0,`count.${k}`);h.push(`count(*) FILTER (WHERE ${_===""?"true":_}) AS ${q(`count__${R}`)}`)}),h.length===0)throw new Error(`aggregate(${u}): no aggregate asked for \u2014 the result would be an empty object. Name sum/avg/min/max columns or count: true.`);let b=m.groupBy??[];for(let k of b)ue(f,k,"aggregate","groupBy column"),xt(f,k,"aggregate","groupBy");let E=b.map(k=>`${Is(f,k,"t")} AS ${q(`g__${k}`)}`),$=ve(n,f,m.where??{},T,"aggregate").sql,A=b.length>0?` GROUP BY ${b.map(k=>`t.${q(k)}`).join(", ")}`:"",I=await i(`SELECT ${[...E,...h].join(", ")} FROM ${f.sql} t WHERE true${$}${A}`,g),L=k=>{let x={};for(let R of b)x[R]=k[`g__${R}`];for(let R of p){let _=x[R.fn]??={};_[R.col]=k[R.alias]??null}return m.count===!0&&(x.count=Number(k._count??0)),S.length>0&&(x.count=Object.fromEntries(S.map(([R],_)=>[R,Number(k[`count__${_}`]??0)]))),x};return b.length>0?I.map(L):L(I[0]??{})},async count(u,m={}){let f=s(u,"count"),g=[],T=ve(n,f,m,se(g),"count").sql,h=await i(`SELECT count(*) AS n FROM ${f.sql} t WHERE true${T}`,g);return Number(h[0]?.n??0)},async findUnique(u,m,f={}){let g=s(u,"findUnique");Co(u,g.uniqueKeys,m);let T={select:f.select===void 0?void 0:Sn(f.select,[...f.select]),with:f.with,limit:2},h;if(f.lock===void 0)h=await y.findMany(u,m,T);else{let p=xs(n,g,m,{...T,lock:f.lock});h=c(g,await o(p.sql,p.params),f.with)}if(h.length>1)throw new Error(`findUnique(${u}): the database's constraints disagree with the schema; more than one row matched`);return h[0]??null},async findById(u,m){let f=s(u,"findById");if(!f.columns.has("id"))throw new Error(`findById(${u}): the table has no "id" column \u2014 use findUnique({ where: <its key> })`);let g=await i(`SELECT ${ee(f)} FROM ${f.sql} WHERE "id" = $1`,[Ce(f,"id",m)]);return g[0]?d(f,g[0]):null},async findMany(u,m={},f={}){let g=s(u,"findMany"),T=xs(n,g,m,f),h=f.lock!==void 0;return c(g,await(h?o:i)(T.sql,T.params),f.with)},async search(u,m,f={}){let g=s(u,"search"),T=g.search;if(T===void 0)throw new Error(`search(${u}): the table declares no search \u2014 defineTable(${JSON.stringify(g.name)}, { \u2026, search: { from: [<its text columns>], model } })`);let h=Ro(u,m,f),p=e.search,S=L=>c(g,L),b=async()=>{let L=_s(n,g,{text:h.text},{where:f.where,limit:h.limit,minScore:h.minScore});return S(await i(L.sql,L.params))};if(h.mode==="text")return b();let E=p.embed;if(E===void 0)throw new Error(`search(${u}): no embedder was given, and a search by meaning embeds its query \u2014 createDatabase({ embed }) (the backend's db.embed); mode: "text" searches by word alone`);let $=L=>(L===void 0?p.serving.delete(T.key):p.serving.set(T.key,L),L),A=p.serving.get(T.key)??$(ws((await i(ys,[T.key]))[0])),I;for(let L=1;;L++){if(A===void 0){if(h.mode==="vector")throw new Error(`search(${u}): the database holds no vectors for this table \u2014 its schema is migrated before the app serves`);return b()}if(I===void 0||I.of.model!==A.model||I.of.dimensions!==A.dimensions)try{I={of:A,literal:await bo(E,h.text,A)}}catch(O){if(h.mode==="vector")throw O;let C=Date.now();return C-(p.said.get(T.key)??-1/0)>=Tl&&(p.said.set(T.key,C),p.log?.(`palgres: search(${u}) answered by word alone: its query could not be embedded (${O instanceof Error?O.message:String(O)})`)),b()}let k=On(A.dimensions,A.metric),x=q(A.types),R=_s(n,g,{...h.mode==="hybrid"?{text:h.text}:{},vector:{table:`${q(J)}.${q(Be(T.key,A.gen))}`,literal:I.literal,type:`${x}.${k.type}`,operator:`OPERATOR(${x}.${k.operator})`}},{where:f.where,limit:h.limit,minScore:h.minScore}),_=await t(),[P,B]=await Promise.all([_.unsafe(ys,[T.key],Ps),_.unsafe(R.sql,R.params,Os(R.params)?void 0:Ps)]),w=$(ws(P[0]));if(w!==void 0&&w.gen===A.gen)return S(B);if(L>=3)throw new Error(`search(${u}): the vectors that serve the table changed while it was searched, three times over`);A=w}},async page(u,m={},f={}){let g=s(u,"page");if(e.cursorKey===null)throw new Error("Database.page needs a cursor secret shared by every replica: createDatabase({ cursorSecret })");let T=e.cursorKey,h=Object.create(null);for(let[X,ie]of g.columns)h[X]={type:ie.type,nullable:ie.nullable&&!g.primaryKey.includes(X)};let{order:p,size:S,backward:b,token:E}=Wo(h,g.primaryKey,f),$=[],A=se($),I=ve(n,g,m,A,"page").sql,L=Ls(g,f.select===void 0?void 0:Sn(f.select,[...f.select]),"page"),k=Ss({table:u,version:n.version,columns:h,order:p,where:I,params:$,select:f.select,with:f.with,identity:e.cursorScope()}),x=E===void 0?void 0:Bo(T,k,E,p.length),R=X=>`t.${q(X)}`,_=x?` AND ${Rs(p,x,b,A,R)}`:"",P=x?`EXISTS (SELECT 1 FROM ${g.sql} t WHERE true${I} AND ${Rs(p,x,!b,A,R,!0)})`:"false",B="__pb_page_",w=[...g.columns.keys(),...Object.keys(f.with??{})];for(;w.some(X=>X.startsWith(B));)B+="_";let O=`${B}ordinal`,C=`${B}opposite`,W=p.map((X,ie)=>`${B}${ie}`),M=p.map((X,ie)=>`${Le(g,X.column)==="timestamp"?Qe("timestamp",R(X.column)):`${R(X.column)}::text`} AS ${q(W[ie])}`),j=f.with&&Object.keys(f.with).length?_t(n,g,f.with,A,"page"):{select:[],joins:[]},U=p.map(X=>`${R(X.column)} ${X.direction==="asc"!==b?"ASC":"DESC"} NULLS ${X.nulls==="first"!==b?"FIRST":"LAST"}`).join(", "),H=`SELECT ${[L,...j.select,...M,`row_number() OVER (ORDER BY ${U}) AS ${q(O)}`].join(", ")} FROM ${g.sql} t ${j.joins.join(" ")} WHERE true${I}${_} ORDER BY ${U} LIMIT ${S+1}`,G=`SELECT p.*, b.${q(C)} FROM (SELECT ${P} AS ${q(C)}) b LEFT JOIN LATERAL (${H}) p ON true ORDER BY p.${q(O)}`,Q=await i(G,$),oe=Q[0]?.[C]===!0,Z=Q.filter(X=>X[O]!==null&&X[O]!==void 0),xe=Z.length>S;Z=Z.slice(0,S),b&&Z.reverse();let re=X=>X?Uo(T,k,W.map(ie=>X[ie]===null?null:String(X[ie]))):null,Ae={startCursor:re(Z[0]),endCursor:re(Z.at(-1)),hasNextPage:b?oe:xe,hasPreviousPage:b?xe:oe};for(let X of Z)for(let ie of[...W,O,C])delete X[ie];return{rows:c(g,Z,f.with),pageInfo:Ae}},async attempt(u){return(await t()).savepoint(f=>u(Un(()=>Promise.resolve(f),e)))},async txPlan(u){return(await t()).savepoint(async f=>{let g=[];for(let T of u.ops){let h=T.op==="select"||T.op==="delete"?s(T.table,"transaction plan"):r(T.table,"transaction plan"),p=bl(n,h,T,g),S=T.op==="delete"?n.deferral(h):null;p!==null&&S!==null&&await f.unsafe(S.defer,[]);let b=p===null?[]:c(h,await f.unsafe(p.sql,p.params));p!==null&&S!==null&&await f.unsafe(S.check,[]);let E={rows:b,rows_affected:b.length};g.push(E),Nl(T,E)}return{results:g}})}};return y}function Sl(t,e){let n;return t.op<0||t.op>=e.length?n=`transaction plan: a reference points at operation ${t.op}, but the plan has run ${e.length} (0\u2026${e.length-1}). A reference can only read an EARLIER operation's row.`:e[t.op].rows[0]?n=`transaction plan: operation ${t.op}'s row has no column "${t.field}" (its columns: ${Object.keys(e[t.op].rows[0]).join(", ")}).`:n=`transaction plan: operation ${t.op} returned NO ROW, so "${t.field}" cannot be read. A reference does not guarantee its row exists \u2014 declare the expectation first (\`.expectOne(err)\`).`,Object.assign(new Error(n),{error_code:"tx_ref_unresolved"})}function qs(t,e){if(gr(t))throw new Error(`${e}: got an imitation of a plan reference ({ $ref: \u2026 }) \u2014 this object was not made by the plan's builder. A reference is built in your code from an earlier operation's row (insert(...).expectOne(err).id); a filter from a request body cannot carry one.`)}function Us(t,e){let n=e[t.$ref.op]?.rows[0];if(!n||!(t.$ref.field in n))throw Sl(t.$ref,e);return n[t.$ref.field]}function Dt(t,e,n,s,r,o){return qs(e,`transaction plan (${n})`),ni(t,n,Yn(e)?Us(e,r):e,s,o)??[Rl(t,e,n,s,r)]}function Rl(t,e,n,s,r){if(qs(e,`transaction plan (${n})`),Yn(e))return s(Ce(t,n,Us(e,r)));if(hr(e)){let o=e.$expr;return o.fn==="now"?gn(o,s):`${q(n)} ${o.fn==="inc"?"+":"-"} ${s(Ce(t,n,o.by))}`}return s(Ce(t,n,e))}function Ms(t,e){if(qs(t,"transaction plan filter"),Yn(t)){let n=Us(t,e);if(n==null)throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${t.$ref.op}'s "${t.$ref.field}" is NULL. As a filter value NULL means IS NULL \u2014 every row with no value there, not the one the reference named. Write null in the filter when that is what you mean.`),{error_code:"tx_ref_null"});if(typeof n=="object"&&!Array.isArray(n)&&!fr(n))throw Object.assign(new Error(`transaction plan: a filter's reference to operation ${t.$ref.op}'s "${t.$ref.field}" is an object. A filter compares a column with a value; an object there would be read as operators. Reference a scalar column.`),{error_code:"tx_ref_object"});return n}if(Array.isArray(t))return Sn(t,t.map(n=>Ms(n,e)));if(t!==null&&typeof t=="object"&&!Me(t)&&!an(t)&&!Jn(t)&&!(t instanceof Date)){let n=Sn(t,{});for(let[s,r]of Object.entries(t))n[s]=Ms(r,e);return n}return t}function Fs(t,e,n,s,r,o){if(n===void 0||Object.keys(n).length===0&&!an(n))return{sql:"",conditions:0,resolved:{}};let i=Ms(n,r);return{...ve(t,e,i,s,o),resolved:i}}function bl(t,e,n,s){let r=[],o=se(r),i=`transaction plan ${n.op}`,a=n.op==="insertMany"?[...new Set((n.rows??[]).flatMap(c=>Object.keys(c)))]:Object.keys(n.values??n.set??{});En(e,i,a);let l;switch(n.op){case"insert":{let c=n.values??{},d=Object.keys(c),y=d.flatMap(u=>Dt(e,c[u],u,o,s,i));l=d.length?`INSERT INTO ${e.sql} (${je(e,d)}) VALUES (${y.join(", ")}) RETURNING ${ee(e)}`:`INSERT INTO ${e.sql} DEFAULT VALUES RETURNING ${ee(e)}`;break}case"upsert":{let c=n.values??{},d=Object.keys(c),y=n.onConflict??[];if(d.length===0||y.length===0)throw Object.assign(new Error(`put on ${n.table} needs columns and onConflict`),{error_code:"tx_bad_upsert"});Y(n.onConflict,"onConflict","which columns a conflict is on");for(let m of y)ue(e,m,i,"onConflict column");let u=d.flatMap(m=>Dt(e,c[m],m,o,s,i));l=`INSERT INTO ${e.sql} (${je(e,d)}) VALUES (${u.join(", ")}) ${Mn(e,d,y,"update",i)} RETURNING ${ee(e)}`;break}case"insertMany":{let c=n.rows??[];if(c.length===0)return null;let d=Object.keys(c[0]),y=c.map(f=>`(${d.flatMap(g=>Dt(e,f[g],g,o,s,i)).join(", ")})`),u=n.onConflict??[];Y(n.onConflict,"onConflict","which columns a conflict is on");for(let f of u)ue(e,f,i,"onConflict column");if(n.action==="update"&&u.length===0)throw Object.assign(new Error(`insertMany on ${n.table}: an overwrite needs onConflict columns`),{error_code:"tx_bad_upsert"});let m=n.action!==void 0?` ${Mn(e,d,u,n.action,i)}`:"";l=`INSERT INTO ${e.sql} (${je(e,d)}) VALUES ${y.join(", ")}${m} RETURNING ${ee(e)}`;break}case"update":{let c=n.set??{},d=Object.keys(c);if(d.length===0)throw new Error(`update ${n.table}: nothing to set`);let y=d.map(f=>{let[g,T]=Dt(e,c[f],f,o,s,i),h=e.encrypted.get(f)?.lookup;return`${q(f)} = ${g}${h?`, ${q(h)} = ${T}`:""}`}),u=Fs(t,e,n.where,o,s,i);yn(u,i);let m=e.singleKey;l=m===null||ui(u.resolved,m)?`UPDATE ${e.sql} AS t SET ${y.join(", ")} WHERE true${u.sql} RETURNING ${ee(e,"t")}`:`WITH locked AS (SELECT t.${q(m)} AS "__pb_lock" FROM ${e.sql} t WHERE true${u.sql} ORDER BY t.${q(m)} FOR NO KEY UPDATE) UPDATE ${e.sql} AS t SET ${y.join(", ")} FROM locked WHERE t.${q(m)} = locked."__pb_lock" RETURNING ${ee(e,"t")}`;break}case"delete":{let c=Fs(t,e,n.where,o,s,i);yn(c,i),l=`DELETE FROM ${e.sql} AS t WHERE true${c.sql} RETURNING ${ee(e,"t")}`;break}case"select":{let c="";if(n.limit!==void 0){let y=Number(n.limit);if(!Number.isInteger(y)||y<0)throw new Error(`transaction plan (${n.table}): limit must be an integer, got "${String(n.limit)}"`);c=` LIMIT ${y}`}let d=n.lock==="update"?" FOR UPDATE":"";l=`SELECT ${ee(e,"t")} FROM ${e.sql} t WHERE true${Fs(t,e,n.where,o,s,i).sql}${c}${d}`;break}default:throw new Error(`unknown operation "${String(n.op)}" in a transaction plan`)}return{sql:l,params:r}}function Nl(t,e){let n=t.guard;if(!n)return;let s=e.rows.length;if(!(n.kind==="one"?s===1:n.kind==="none"?s===0:n.kind==="atLeast"?s>=n.n:s<=n.n))throw Object.assign(new Error(`transaction expectation failed: ${n.kind} (${s} row(s))`),{error_code:"tx_guard_failed",slot:n.slot})}import{AsyncLocalStorage as pi}from"node:async_hooks";import{randomUUID as Al}from"node:crypto";var Pt=new pi,di=()=>({running:new Set}),Ol=t=>String(t?.message??t);function kl(t){return new sn(`The transaction was rolled back, not committed: a statement in it failed (${Ol(t)}) and the code went on. One failed statement aborts the whole transaction \u2014 Postgres refuses every later one and answers COMMIT with ROLLBACK. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row.`,t)}async function mi(t){for(;t.running.size;)await Promise.allSettled([...t.running])}function fi(t,e){let n=e.bind;if(e.lockTimeout!==void 0&&(n+=`, set_config('lock_timeout', ${ne(e.lockTimeout)}, true)`),e.statementTimeout!==void 0&&(n+=`, set_config('statement_timeout', ${ne(e.statementTimeout)}, true)`),!/^select /i.test(n))throw new Error("palgres: the binding statement must be a SELECT list");n+=", pg_catalog.current_setting('transaction_isolation') AS palgres_isolation",e.prepared!==void 0&&(n+=`, pg_catalog.current_setting('palgres.session', true) AS palgres_session, CASE WHEN coalesce(pg_catalog.current_setting('palgres.session', true), '') = '' THEN pg_catalog.set_config('palgres.session', ${ne(e.prepared.mark())}, false) END AS palgres_marked, pg_catalog.set_config('plan_cache_mode', ${ne(jo)}, true) AS palgres_plans`);let s=null,r=null,o=null,i=null,a=!1,l=null,c=di(),d=!0,y,u=!1,m,f=async()=>!e.control||await e.control.drainCancellation()?!0:(m?.abandon?.(),!1),g,T=!1,h=(_,P,B,w)=>{if(e.prepared===void 0)return B;let O=B?.inline===!0;if(!O&&Ho(_))return g===void 0?T=!0:g.forget(),B;if(g===void 0)return e.prepared.count(_,P,O),B;if(w.refused!==void 0)return B;let C=g.run(_,P,O);return C===void 0?B:{...B,prepared:C}},p=()=>{u=!0},S=()=>{if(a)throw new Error("Database transaction has settled; its handle cannot be used again");if(e.control?.check(),e.trace?.check(),Pt.getStore()!==e.scope)throw new Error("Database.$atomic cannot use a handle from another transaction or identity; use its tx argument")},b,E,$=new Set,A=0,I=!1,L=()=>s!==null&&!a&&u&&c.running.size===0&&$.size===0,k=(_,P,B=S,w,O=new Set)=>{let C=()=>{if(B(),E!==w||b?.getStore()!==w)throw new Error("Database connection belongs to another active savepoint; use its tx argument and await it before using the parent handle")};return{unsafe(W,M,j){try{C()}catch(G){return Promise.reject(G)}j?.read!==!0&&(d=!1);let U=(M??[]).map(pn),H=()=>{let G=_.unsafe(W,U,h(W,U,j,P)),Q=Promise.resolve(e.control?e.control.watch(G):G).catch(oe=>{throw Gn(oe)&&(P.refused??={error:oe}),oe});return P.running.add(Q),A++,Q.catch(()=>{}).finally(()=>{P.running.delete(Q),p(),--A===0&&!a&&e.onIdle?.()}),Q};return e.trace?e.trace.query(W,H):H()},async savepoint(W){C(),d=!1;let M=Symbol("savepoint"),j=new Set,U=di();b??=new pi,E=M;let H=(async()=>{try{return await _.savepoint(async G=>{let Q=!1,oe=()=>{if(B(),Q)throw new Error("Database savepoint has settled; its handle cannot be used again")};try{let Z=b.run(M,()=>W(k(G,U,oe,M,j))),xe=await(e.control?e.control.race(Z):Z);if(await mi(U),U.refused)throw U.refused.error;return xe}finally{j.size&&await Promise.allSettled([...j]),Q=!0}})}finally{E=w}})();$.add(H),O.add(H);try{return await H}finally{$.delete(H),O.delete(H)}}}},x=async()=>(S(),s||(s=new Promise((_,P)=>{let B=new Promise((w,O)=>{r=w,o=O});B.catch(()=>{}),i=(async()=>{let w=performance.now(),O;try{O=await(e.acquire?e.acquire(e.control?.signal):e.admission.acquire(e.claims,e.control?.signal))}finally{e.trace?.time("queueMs",w)}let C=performance.now(),W,M=e.control!==void 0&&t.cancelBackend!==void 0,j=[];if(e.isolation!==void 0||e.readOnly!==void 0){let de=e.isolation??"read committed";Zn({isolation:de,readOnly:e.readOnly}),j.push(`SET TRANSACTION ISOLATION LEVEL ${de.toUpperCase()}${e.readOnly===void 0?"":e.readOnly?" READ ONLY":" READ WRITE"}`)}j.push(M?`WITH backend AS MATERIALIZED (SELECT pid, backend_start::text AS started, xact_start::text AS xact_started FROM pg_catalog.pg_stat_get_activity(pg_catalog.pg_backend_pid())) ${n}, backend.pid, backend.started, backend.xact_started FROM backend`:n);let U=M&&t.cancelOpening!==void 0?`palgres:${Al()}`:void 0,H=!1,G=de=>{u=!0;let V=de[0];if(typeof V?.palgres_isolation=="string"&&(y=V.palgres_isolation),e.prepared!==void 0&&typeof V?.palgres_session=="string"&&V.palgres_session!==""&&(g=e.prepared.on(V.palgres_session),T&&g.forget()),!M)return;if(!Number.isInteger(V?.pid)||typeof V?.started!="string"||typeof V?.xact_started!="string"){let Ke=new Error("Database cancellation cannot identify its own backend");throw c.refused??={error:Ke},Ke}let he={pid:V.pid,started:V.started,xactStarted:V.xact_started};H=!0,e.control.bindBackend(()=>t.cancelBackend(he.pid,he.started,he.xactStarted))},Q=async()=>{for(let de=0;de<400&&!u&&!H;de++){if(await t.cancelOpening(U))return;await new Promise(V=>setTimeout(V,5))}},oe=O.openWithin,Z=!1,xe,re,Ae=()=>new Fe({retryAfter:1},"Database queue deadline exceeded"),X=oe===void 0?void 0:new Promise((de,V)=>{re=setTimeout(()=>{u||(Z=!0,xe?.abandon?.(),V(Ae()))},oe)});X?.catch(()=>{});let ie=de=>t.begin(async V=>{W=performance.now(),e.trace?.time("poolMs",C);let he=e.trace?performance.now():0;if(e.control?.check(),a)throw new Error("Database transaction closed while waiting for its connection");if(Z)throw Ae();if(U!==void 0&&!H&&e.control.bindBackend(Q),oe!==void 0&&!u){xe=V;try{await V.unsafe("SELECT 1")}catch(Ke){throw Z?Ae():Ke}}clearTimeout(re),e.trace?.time("setupMs",he),de(),m=V,_(k(V,c)),await B},{sql:j.join("; "),opened:G,tag:U});try{if(e.control?.check(),a)throw new Error("Database transaction closed while waiting for admission");let de=!1;for(let V=1;;V++)try{let he=ie(()=>{de=!0});return X===void 0?await he:(he.catch(()=>{}),await Promise.race([he,X]))}catch(he){let Ke=Ee(he);if(de||a||Ke===void 0||V>=(Ke==="lost"?bt:Nt))throw he;e.control?.check()}}finally{clearTimeout(re),W!==void 0&&e.trace?.time("connectionMs",W),O.release()}})().catch(w=>{throw P(w),w}),i.catch(()=>{})}),s.then(void 0,()=>{I=!0,a||e.onIdle?.()}),s)),R=_=>l??=(async()=>{if(a=!0,!s)return;await f(),$.size&&await Promise.allSettled([...$]);let P=e.trace?performance.now():0;o(_),await i?.catch(()=>{}),e.trace?.time("rollbackMs",P),e.trace?.rolledBack()})();return{ensure:x,get opened(){return s!==null},get busy(){return s!==null&&!a&&!I&&(!u||A>0)},get failed(){return I},get releasable(){return L()&&d&&c.refused===void 0&&(y==="read committed"||y==="read uncommitted")},async commit(){if($.size&&await Promise.allSettled([...$]),!s){e.trace?.check(),a=!0;return}await mi(c);try{if(e.trace?.check(),e.control?.checkDeadline(),c.refused)throw kl(c.refused.error)}catch(P){throw await R(P),P}if(a=!0,!await f()){let P=De(new pe(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:!1},1));throw await R(P),P}let _=e.trace?performance.now():0;if(r(),d&&y!==void 0&&y!=="serializable"){i.then(()=>e.trace?.committed(),()=>e.trace?.commitFailed());return}try{await i,e.trace?.committed()}catch(P){throw e.trace?.commitFailed(),P}finally{e.trace?.time("commitMs",_)}},rollback:R}}var Il="5s",Ll="10s",Cl=new Set(["22P02","22007","22008","22003","22001"]),hi="55s",wi=1,vl=1e3,Wn=new Set,Bn,xl=new yi("palgres.release");function _l(t){Wn.add(t),Bn===void 0&&(Bn=xl.runInAsyncScope(()=>setInterval(()=>{let e=performance.now();for(let n of Wn){let s=!0;try{s=n(e)}catch{s=!0}s&&Wn.delete(n)}Wn.size===0&&(clearInterval(Bn),Bn=void 0)},wi)),Bn.unref?.())}function Dl(t,e){let n=[],s=d=>d!==null&&d.opened&&!d.failed,r=new Set,o,i=!1,a=()=>{for(let d of n)if(s(d.tx)&&d.tx.busy)return!0;for(let d of r)if(d.busy)return!0;return!1},l=yi.bind(d=>{if(o===void 0||a())return!0;let y=r.size,u=r.size===0;for(let f of n)s(f.tx)&&(y++,f.tx.releasable||(u=!1));if(y===0)return!0;let m=d-o;if(u){if(m<wi)return!1;for(let f of n){let g=f.tx;s(g)&&(f.tx=null,f.lease?.leave(),f.lease=void 0,g.commit().catch(()=>{}))}return o=void 0,!0}return e===void 0||i?!0:m<vl?!1:(i=!0,e(Math.round(m)),!0)}),c=()=>{a()||(o=performance.now(),_l(l))};return{onIdle:c,surface(d,y){let u={tx:null};n.push(u);let m=()=>{Wn.delete(l);let f=u.tx;return u.tx=null,u.lease=void 0,f};return{ensure(){if(o!==void 0&&(o=performance.now()),u.tx===null){if(t())return Promise.reject(new Error("Database transaction has settled; its handle cannot be used again"));u.tx=d(c,f=>y(f).then(g=>(u.lease=g,g)))}return u.tx.ensure()},commit:()=>m()?.commit()??Promise.resolve(),rollback:f=>m()?.rollback(f)??Promise.resolve()}},atomic(d){return r.add(d),()=>{r.delete(d)&&c()}}}}function Pl(t){let e=ce(t),n=t?.code,s=o=>e!==void 0&&o.has(e)||typeof n=="string"&&o.has(n),r;if(s(cr))r=!0;else if(s(ur))r=!1;else return;return He(new pe(503,"database_unavailable","The database is temporarily unavailable",{retrySafe:r},1),t)}var wn=t=>String(t?.message??t);function He(t,e){return t.cause=e,De(t)}function Bs(t,e,n){if(typeof t=="object"&&t!==null&&gi.has(t))return t;let s=Fl(t,e,n);return typeof s=="object"&&s!==null&&gi.add(s),s}var gi=new WeakSet,Ft=(t,e,n)=>Object.assign(new Error(t,{cause:e}),{sqlstate:n});function Fl(t,e,n){if(sn.is(t))return t;let s=ce(t);if(s===le.inFailedTransaction||/current transaction is aborted/i.test(wn(t)))return Ft(`This request cannot write any more: an earlier write in it failed, and a request runs in ONE Postgres transaction, so every statement after the failure is refused. Wrap a write you expect to fail in \`Database.$attempt(async (tx) => \u2026)\` \u2014 it takes a SAVEPOINT, so only that write rolls back \u2014 or use \`Database.public.<t>.put({ data, onConflict: [...] })\` when what you brace for is a duplicate row. (${wn(t)})`,t,le.inFailedTransaction);if(nn.is(t))return t;if(s===le.uniqueViolation)return He(new nn(Tn(t)),t);if(s===le.serializationFailure)return He(new Ht(s),t);if(s===le.deadlockDetected)return He(new Kt(s),t);if(s===le.queryCancelled)return He(Object.assign(new pe(503,"database_query_cancelled","Database statement was cancelled"),{sqlstate:s}),t);let r=Pl(t);if(r)return r;if(e==="service"&&s===le.foreignKeyViolation)return Ft(`Database.$asService() hit a foreign key with nothing to point at. It runs in its OWN transaction on its OWN connection, so a row this request wrote through \`Database.*\` is not visible to it until the request commits \u2014 and the request cannot commit until the handler returns. If the row it needs is one this request just created, do both writes on ONE surface. (${wn(t)})`,t,s);if(/lock timeout/i.test(wn(t))){let o;return e==="service"?o=Ft(`Database.$asService() waited too long for a row lock. It runs in its OWN transaction, so a row this request already wrote through Database.* is locked against it until the request commits \u2014 a wait that cannot end. Do that row's work on one surface or the other. (${wn(t)})`,t,s??le.lockNotAvailable):o=Ft(`Database waited too long for a lock. Another transaction holds it: a concurrent one, or another of this request's own \u2014 Database.*, $asService() and $atomic each run in their OWN transaction, and a row one of them wrote stays locked against the others until it commits, a wait that cannot end while the handler runs. Do that row's work on one surface. (${wn(t)})`,t,s??le.lockNotAvailable),He(Object.assign(new pe(503,"database_busy","The database waited too long for a lock",{retrySafe:!1},1),{sqlstate:s??le.lockNotAvailable}),o)}return s!==void 0&&Cl.has(s)?He(Object.assign(new pe(400,"invalid_value","A value is not one its column can take"),{sqlstate:s}),t):s===le.insufficientPrivilege&&n!==null?He(Object.assign(new pe(n==="anon"?401:403,"permission_denied","The database does not allow this caller to do this"),{sqlstate:s}),t):(s!==void 0&&typeof t=="object"&&t!==null&&!Object.hasOwn(t,"sqlstate")&&Object.defineProperty(t,"sqlstate",{value:s,enumerable:!0,configurable:!0}),t)}function Ml(t,e,n){let s=r=>({unsafe(o,i,a){let l;try{l=r.unsafe(o,i,a)}catch(c){return Promise.reject(Bs(c,e,n))}return Promise.resolve(l).then(on,c=>{throw Bs(c,e,n)})},savepoint:o=>r.savepoint(i=>o(s(i))),...r.abandon?{abandon:r.abandon.bind(r)}:{}});return{unsafe:(r,o)=>t.unsafe(r,o),begin:(r,o)=>t.begin(i=>r(s(i)),o).catch(i=>{throw Bs(i,e,n)}),...t.cancelBackend?{cancelBackend:t.cancelBackend.bind(t)}:{},...t.cancelOpening?{cancelOpening:t.cancelOpening.bind(t)}:{}}}var ql=2,Ei={anon:"anon",authenticated:"authenticated",service:"service"};function Ul(t,e){let n=Object.hasOwn(Ei,e.role)?Ei[e.role]:void 0;if(n===void 0)throw new Error(`palgres: a request is anon, authenticated or service, not "${String(e.role)}"`);return t[n]}function Ws(t,e,n,s={}){let{signal:r}=s,o=s.diagnostics===void 0?void 0:new Ct(s.diagnostics),i=r===void 0?void 0:new fn(void 0,r),a=Ul(e.roles,n),l=e.roles.service,c=n.role==="anon"||n.role==="authenticated"?n.role:null,d=n.claims,y=!1,u=!1,m=()=>{u&&dt.committed()},f=O=>{let C;return{cat:e.cat,trace:o,cursorKey:e.cursorKey,cursorScope:()=>C??=qo(O,d),search:e.search,searchable:()=>{u=!0}}},g=f(a),T=f(l),h=new Set,p=null,S=!1,b=0,E=new Set,$=O=>new Promise((C,W)=>{let M=G=>{E.delete(j),clearTimeout(H),O?.removeEventListener("abort",U),G===void 0?C():W(G)},j=()=>M(),U=()=>M(O?.reason??new Error("Database admission cancelled")),H=setTimeout(()=>M(new Fe({retryAfter:1},"Database queue deadline exceeded")),e.admission.queueTimeoutMs);E.add(j),O?.addEventListener("abort",U,{once:!0}),O?.aborted&&U()}),A=async O=>{let C;for(;;){for(;h.size===0&&p!==null;)await p;let j=h.size>0;if(j){for(;b>=ql;)await $(O);b++}let U;try{let H=e.admission.acquire(d,O,{nested:j,returning:!j&&S}).then(G=>{if(j&&h.size===0)return G.release(),null;let Q={nested:j,turn:G};return h.add(Q),j||(S=!0),Q});if(!j){let G=H.then(()=>{},()=>{});p=G,G.then(()=>{p===G&&(p=null)})}U=await H}catch(H){throw j&&I(),H}if(U!==null){C=U;break}I()}let W=!1,M=()=>{if(!W){if(W=!0,h.delete(C),C.nested){I();return}for(let j of h){[C.turn,j.turn]=[j.turn,C.turn],j.nested=!1,C.nested=!0,I();return}}};return{queueMs:C.turn.queueMs,leave:M,release:()=>{M(),C.turn.release()},...C.nested&&e.binding.pooled===!0?{openWithin:e.admission.queueTimeoutMs}:{}}},I=()=>{b--;let O=E.values().next().value;O?.()},L=Dl(()=>y,s.heldIdle),k=(O,C,W={})=>fi(Ml(t,C,C==="user"?c:null),{bind:xn(e.binding,O,d),claims:d,admission:e.admission,acquire:A,trace:o,prepared:e.prepared,...W}),x=(O,C)=>async(W,M={})=>{if(Zn(M),y)throw new Error("Database request has settled; it cannot open another transaction");if(Pt.getStore()!==void 0)throw new Error("Nested Database.$atomic is not supported; use tx.$attempt for a savepoint");let j=Qn(M.retry),U=M.signal&&r?AbortSignal.any([M.signal,r]):M.signal??r,H=M.timeoutMs!==void 0||U!==void 0?new fn(M.timeoutMs,U):void 0;try{H?.check();for(let G=0;;G++){H?.check();let Q=[M.statementTimeoutMs,H?.remainingMs()].filter(re=>re!==void 0),oe=Symbol("atomic transaction"),Z=k(O,C,{scope:oe,isolation:M.isolation,readOnly:M.readOnly,control:H,lockTimeout:`${M.lockTimeoutMs??5e3}ms`,statementTimeout:Q.length===0?void 0:`${Math.min(...Q)}ms`,onIdle:L.onIdle}),xe=L.atomic(Z);try{let re=Un(()=>Z.ensure(),C==="user"?g:T),Ae=Pt.run(oe,()=>W(re)),X=await(H?H.race(Ae):Ae);return await Z.commit(),m(),X}catch(re){await Z.rollback(re);let Ae=tn(re)||sn.is(re)&&tn(re.cause);if(G>=j||!Ae)throw re;o?.retry();let X=new Promise(ie=>setTimeout(ie,Math.min(100,2**G)));await(H?H.race(X):X)}finally{xe()}}}finally{H?.dispose()}},R=L.surface((O,C)=>k(a,"user",{lockTimeout:Ll,statementTimeout:hi,control:i,onIdle:O,acquire:C}),A),_=null,P,B=null,w=()=>{if(B===null){if(y)throw new Error("Database request has settled; it cannot open another transaction");P=r===void 0?void 0:new fn(void 0,r);let O=P,C=L.surface((W,M)=>k(l,"service",{lockTimeout:Il,statementTimeout:hi,control:O,onIdle:W,acquire:M}),A);_=C,B=Object.assign(Un(()=>C.ensure(),T),{atomic:x(l,"service")})}return B};return{client:Object.assign(Un(()=>R.ensure(),g),{asService:w,atomic:x(a,"user")}),async commit(){y=!0;try{try{o?.check()}catch(O){throw await R.rollback(O),await _?.rollback(O),O}try{await R.commit()}catch(O){throw await _?.rollback(O),O}await _?.commit(),m(),o?.complete("committed"),i?.dispose(),P?.dispose()}catch(O){throw o?.failed(),O}},async rollback(O){y=!0,await R.rollback(O),await _?.rollback(O),i?.dispose(),P?.dispose(),o?.complete("failed")}}}function Bl(t){if(t.codec!==void 0&&t.codec in rn)return rn[t.codec].tsType;switch(t.type){case"uuid":case"text":case"timestamp":case"date":return"string";case"sql":return t.sqlType!==void 0&&Xn.has(t.sqlType)?"number":t.sqlType!==void 0&&Vn.has(t.sqlType)?"Json":"string";case"integer[]":return"number[]";case"boolean[]":return"boolean[]";case"uuid[]":case"text[]":case"bigint[]":case"numeric[]":case"timestamp[]":case"date[]":return"string[]";case"integer":return"number";case"bigint":case"numeric":return"string";case"boolean":return"boolean";case"jsonb":return"Json";case"enum":{let e=t.enumValues??[];return e.length===0?"string":e.map(n=>JSON.stringify(n)).join(" | ")}case"enum[]":{let e=t.enumValues??[];return e.length===0?"string[]":`(${e.map(n=>JSON.stringify(n)).join(" | ")})[]`}default:{let e=t.type;throw new Error(`env-gen: the column type "${String(e)}" has no TypeScript type \u2014 add a case to baseTsType`)}}}function Wl(t){if(t.encrypted!==void 0)return t.encrypted.lookup?"encrypted:lookup":"encrypted";if(t.type==="enum"){let e=[...t.enumValues??[]].sort();return e.length===0?"enum":`enum:${e.join("|")}`}return t.type}function $i(t){let e=`Pg<${Bl(t)}, ${JSON.stringify(Wl(t))}>`;return t.nullable?`${e} | null`:e}function jl(t){return t.nullable===!0||t.defaultRandom===!0||t.defaultNow===!0||t.defaultValue!==void 0||t.defaultSql!==void 0||t.dbAssigned===!0||t.identity!==void 0}function Hl(t){return t.identity==="always"||t.generated!==void 0}var jn=t=>/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t);function Ti(t,e,n){let s=Object.entries(t.columns).filter(([,a])=>a._def.ignored!==!0),r=s.map(([a,l])=>`${n} ${jn(a)}: ${$i(l._def)};`),o=s.filter(([,a])=>!Hl(a._def)).map(([a,l])=>`${n} ${jn(a)}${jl(l._def)?"?":""}: ${$i(l._def)};`),i=e.map(a=>`${jn(a.name)}: { to: ${JSON.stringify(a.to)}; kind: ${JSON.stringify(a.kind)}; via: ${JSON.stringify(a.via)} }`).join("; ");return[`${n}${jn(t.name)}: {`,`${n} row: {`,...r,`${n} };`,`${n} insert: {`,...o,`${n} };`,`${n} relations: {${i===""?"":` ${i} `}};`,`${n} uniqueKeys: ${JSON.stringify(Ot(t))};`,...t.search!==void 0?[`${n} searchable: true;`]:[],`${n}};`].join(`
|
|
405
|
+
`)}function Kl(t){for(let e of t)for(let n of Object.values(e.tables))for(let[s,r]of Object.entries(n.columns)){let o=r._def;if(!(o.transform===void 0||o.codec!==void 0))throw new Ge([`table "${be(e.name,n.name)}" column "${s}" declares .transform<T>(): its target type does not exist at runtime, so the generated types would say something the engine contradicts. Declare a named codec instead \u2014 .asNumber() for a JS number, .asDecimal() for the exact string.`])}}var js="// palbase:env:begin",Hs="// palbase:env:end",Si=`/**
|
|
406
406
|
* A column's Postgres type, carried in its TypeScript type.
|
|
407
407
|
*
|
|
408
408
|
* __pg is optional, so a row still reads as a plain string or number and is
|
|
@@ -419,39 +419,39 @@ type Pg<T, N extends string> = T & { readonly __pg?: N };
|
|
|
419
419
|
* undefined included: JSON.stringify drops undefined fields, and code that
|
|
420
420
|
* writes { a: undefined } is everywhere \u2014 refusing it would be wrong.
|
|
421
421
|
*/
|
|
422
|
-
type Json = string | number | boolean | null | undefined | Json[] | { [k: string]: Json };`;function
|
|
422
|
+
type Json = string | number | boolean | null | undefined | Json[] | { [k: string]: Json };`;function Ri(t,e,n){Kl(t);let s=Dn(t),r=m=>Object.values(m.tables).filter(f=>f.ignored!==!0),o=t.find(m=>m.name==="public"),i=t.filter(m=>m.name!=="public"),a=(o?r(o):[]).map(m=>Ti(m,s.get(m.name)??[]," ")),l=a.length>0?`
|
|
423
423
|
${a.join(`
|
|
424
424
|
`)}
|
|
425
|
-
`:"",c=i.map(m=>{let f=r(m).map(
|
|
425
|
+
`:"",c=i.map(m=>{let f=r(m).map(g=>Ti(g,s.get(be(m.name,g.name))??[]," "));return` ${jn(m.name)}: {
|
|
426
426
|
${f.join(`
|
|
427
427
|
`)}
|
|
428
428
|
};`}),d=c.length>0?`
|
|
429
429
|
${c.join(`
|
|
430
430
|
`)}
|
|
431
|
-
`:"",
|
|
432
|
-
interface Access {${
|
|
433
|
-
${
|
|
431
|
+
`:"",y=n===void 0?void 0:Xt(n," "),u=y===void 0?"":`
|
|
432
|
+
interface Access {${y===""?"":`
|
|
433
|
+
${y}
|
|
434
434
|
`}}`;return`declare module ${JSON.stringify(e)} {
|
|
435
435
|
interface Tables {${l}}
|
|
436
436
|
interface Schemas {${d}}${u}
|
|
437
|
-
}`}function
|
|
437
|
+
}`}function Gl(t,e={}){let n=e.module??"palbase/backend/env",s=Ri(t,n,e.access);return`// AUTO-GENERATED by Palgres' makeEnvDts from the app's schema files \u2014 DO NOT EDIT.
|
|
438
438
|
// Nothing writes it again on its own: run makeEnvDts again when a schema changes.
|
|
439
439
|
// Augments the ${n} \`Tables\` interface so \`Database.public.*\`
|
|
440
440
|
// is typed with no import and no generic. Schemas other than \`public\` land
|
|
441
441
|
// under \`Schemas\` and are reached by name the same way:
|
|
442
442
|
// \`Database.<schema>.<table>\`.
|
|
443
443
|
|
|
444
|
-
${
|
|
444
|
+
${Si}
|
|
445
445
|
|
|
446
|
-
${
|
|
446
|
+
${js}
|
|
447
447
|
${s}
|
|
448
|
-
${
|
|
448
|
+
${Hs}
|
|
449
449
|
|
|
450
450
|
export {};
|
|
451
|
-
`}function
|
|
451
|
+
`}function Xl(t,e={}){let n=e.module??"palbase/backend/env";return`${js}
|
|
452
452
|
// The app's tables, from its schema files: rows, inserts, unique keys and relations (with, has). Written by
|
|
453
453
|
// palbase db:types \u2014 run it again when a schema changes.
|
|
454
|
-
${
|
|
454
|
+
${Si}
|
|
455
455
|
|
|
456
|
-
${
|
|
457
|
-
${
|
|
456
|
+
${Ri(t,n,e.access)}
|
|
457
|
+
${Hs}`}function Vl(t,e){let n=e.tenant,s=e.key??"id",r=(d,y)=>{if(y==null||typeof y!="string"&&typeof y!="number"&&typeof y!="bigint"&&typeof y!="boolean")throw new TypeError(`defineRepository: the ${d} is a string, number, bigint or boolean, not ${y===null?"null":typeof y}`);return y},o=d=>({[n]:r("tenant",d)}),i=(d,y)=>({[n]:r("tenant",d),[s]:r(s,y)}),a=(d,y)=>({...d,[n]:r("tenant",y)}),l=d=>{let y=[n,s].filter(u=>Object.hasOwn(d,u));if(y.length>0)throw new Pe({fields:y.map(u=>({field:u,message:"cannot be changed through this update"}))},`defineRepository: the patch carries ${y.join(" and ")}, which an update does not change`);return d};class c{async list(y){return t.findMany({where:o(y)})}async find(y,u){return(await t.findMany({where:i(y,u),limit:1}))[0]??null}async insert(y,u){return t.insert(a(u,y))}async update(y,u,m){let f=await this.updateScoped(y,u,m);if(f===null)throw new jt(`no row ${s}=${String(u)} where ${String(n)}=${String(y)}`);return f}async updateScoped(y,u,m){return(await t.updateMany({where:i(y,u),set:l(m)}))[0]??null}async delete(y,u){await t.deleteMany({where:i(y,u)})}}return c}function Yl(t){return Vt({$col:t},"col")}function Jl(t,...e){return Vt({$sql:{text:[...t],values:e}},"sql")}async function zl(t,e={}){let n=Qn(e.retry),s=0;for(;;)try{return await t()}catch(r){if(s>=n||!tn(r))throw r;s+=1}}function Ql(t,e){return{search:(n,s)=>e.search(t,n,s),insert:n=>e.insert(t,n),aggregate:(n=>e.aggregate(t,n)),insertMany:((n,s)=>e.insertMany(t,n,s)),put:n=>e.put(t,n.data,{onConflict:n.onConflict}),update:n=>e.update(t,$r(t,n.where),n.set),delete:n=>e.delete(t,n),findUnique:(n=>e.findUnique(t,n.where,{select:n.select,lock:n.lock})),findById:n=>e.findById(t,n),page:(n=>{let{where:s,...r}=n??{};return e.page(t,s,r)}),findMany:(n=>{let{where:s,...r}=n??{};return e.findMany(t,s,r)}),updateMany:(n=>e.updateMany(t,n.where,n.set,n.returning===void 0?void 0:{returning:n.returning})),deleteMany:n=>e.deleteMany(t,n.where),count:n=>e.count(t,n?.where)}}function Zl(t,e){let n={},s=r=>Object.fromEntries(Object.values(t.tables).map(o=>[o.name,r.table(be(t.name,o.name))]));for(let[r,o]of Object.entries(t.tables))n[r]=Ql(be(t.name,o.name),e);return{tables:n,diagnostics:()=>e.diagnostics(),transaction(r){let o=new Tr;return Sr(e,{tables:s(o)},o,r)}}}async function Gd(t){if(t.prepare===!0&&t.binding.pooled===!0)throw new Error("palgres: a pooled binding's connections are a transaction-mode pooler's, another client's each transaction \u2014 nothing stays prepared on them: createDatabase({ prepare: false })");await hs(t.sql);let e=new Nn;await e.read(i=>t.sql.unsafe(i));let n=t.schemas.some(i=>Object.values(i.tables).some(a=>!a.ignored&&Object.values(a.columns).some(l=>l._def.encrypted!==void 0&&!l._def.ignored))),s=null;if(n||e.size>0){if(t.fields===void 0)throw new Error(`palgres: ${n?"the schema has an .encrypted() column":"a migration is taking a column's encryption on or off"}: the engine needs the project's fields to seal and open it \u2014 createDatabase({ fields })`);s=await et(t.fields),setInterval(()=>{e.read(a=>t.sql.unsafe(a)).catch(a=>t.log?.(`palgres: which columns are going over could not be read (${a instanceof Error?a.message:String(a)}); kept as last read`))},nt).unref?.()}let r={cat:new kt(t.schemas,t.binding,s!==null?{cipher:s,sealing:e}:null),binding:t.binding,roles:{...mn,...t.roles},admission:ko(t.sql,t.admission),cursorKey:t.cursorSecret?Mo(t.cursorSecret):null,search:So(t.embed,t.log),prepared:t.prepare===!1||t.binding.pooled===!0?void 0:new It},o=t.binding.access!==void 0&&t.binding.accessText!==void 0?Gt(t.binding.accessText,t.binding.access):void 0;return{binding:t.binding,request(i,a){let l=Ws(t.sql,r,i,a);return{database:br(l.client,{...o?{access:o}:{},as:i.role}),client:l.client,commit:()=>l.commit(),rollback:c=>l.rollback(c)}},async reseal(i={}){let a=r.cat.fields;if(a===null||!t.binding.direct)return[];let l=[];for(let{table:c,column:d,encrypted:y}of r.cat.encryptedColumns()){if(a.sealing.get(y.address)!==void 0)continue;let u={table:c.sql,column:d,lookup:y.lookup,address:y.address,direction:"seal"},m=null,f=0;do{let g=Ws(t.sql,r,{role:"service",claims:{}});try{let T=await tt((h,p)=>g.client.query(h,p),u,a.cipher,m,i.batchSize??500);await g.commit(),f+=T.done,m=T.last}catch(T){throw await g.rollback(T),T}}while(m!==null);l.push({address:y.address,resealed:f})}return l}}}export{ki as AccessRefused,ps as BUN_CLOSE_GRACE_MS,Pe as BadRequest,Oi as Conflict,mn as DEFAULT_ROLES,Kt as DeadlockDetected,Ue as DriverRefused,Ni as ENGINE_RAISED,Hs as ENV_BLOCK_END,js as ENV_BLOCK_START,bi as HTTP_ERROR_BRAND,pe as HttpError,Cn as MigrationOpen,Se as MigrationRefused,cs as Migrator,jt as NotFound,Aa as POSTGRES_JS_TYPES,dn as RowsHeld,ye as SEALING,nt as SEALING_REFRESH_MS,J as SEARCH_SCHEMA,Jt as SETTLE_MS,le as SQLSTATE,Ge as SchemaError,Nn as Sealing,Ht as SerializationFailure,Fe as TooManyRequests,sn as TransactionAborted,vi as TxPlanError,Ci as TxRefError,nn as UniqueViolation,Rt as VersionNotMigrated,vn as VersionStillConnected,Gt as accessNames,Xt as accessTypesBlock,is as adoptionBaseline,_i as ago,St as applicationName,ia as bind,xn as bindStatement,to as binding,Dn as buildRelations,wo as bunDriver,fs as cancelBackendThrough,To as cancelOpeningThrough,ae as canonicalType,$o as closeBunPool,Yl as col,Ee as connectionFailure,Tn as constraintOf,Gd as createDatabase,qa as createSearchWorker,ea as cutOff,Pi as decrement,Vl as defineRepository,Xe as digest,Hi as drift,Mt as emptySchema,pn as encodeParam,_n as encodePgArray,Xl as envBlock,ln as fieldAddress,aa as forgetUser,la as forgetUserIn,Di as increment,yo as inlineParams,yt as introspect,Me as isColRef,Li as isData,eo as isDirect,Ai as isEngineRaised,tn as isRetryable,Gl as makeEnvDts,Zl as makeTypedDB,Ii as markData,De as markEngineRaised,ge as normalize,xi as now,rs as plan,ra as pooledBinding,La as postgresJsDriver,fa as pullSchema,Oa as renewingBunPool,oa as sayRunning,us as searchPath,Jl as sqlFragment,ce as sqlstateOf,qt as validate,Be as vectorTable,hs as verifyDriver,Ie as versionSchema,zl as withRetry};
|