palgres 0.64.0 → 0.66.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.
@@ -0,0 +1,375 @@
1
+ /*! palgres 0.66.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as Lt}from"./2VBY4HRX.js";import{C as It,a as T,b as L,c as A,e as ee,f as wt,g as ne,h as J,i as we,y as $e}from"./RN23MOOY.js";import{A as $t,C as Tt,D as Nt,E as Xe,F as St,L as ae,M as yt,O as Rt,P as At,Q as Ot,b as ue,c as rt,d as ct,e as b,f as Y,g as Ee,h as lt,i as mt,j as dt,k as re,l as pt,m as Ae,n as ht,q as ut,u as gt,v as ft,w as Be,x as Oe,y as Et,z as Ge}from"./NDFZTRRI.js";function kt(a){return typeof a=="function"?a():Promise.resolve(a)}var bt="pbe1.";function je(a,e,t){return a==="public"?`${e}.${t}`:`${a}.${e}.${t}`}var ie="palgres.sealing",Nn=5e3,_t=3*Nn,Ct=class{going=new Map;get(e){return this.going.get(e)}get size(){return this.going.size}async read(e){let t;try{t=await e(`SELECT address, direction, phase FROM ${ie}`)}catch(n){let s=n.code??n.errno;if(s!=="42P01"&&s!=="3F000")throw n;t=[]}this.going=new Map(t.map(n=>[n.address,{direction:n.direction,phase:n.phase}]))}},Te=a=>`"${a.replace(/"/g,'""')}"`;function Dt(a,e){let t=Te(a.column);return a.direction==="open"?{sql:`${t} LIKE 'pbe1.%'`,params:[]}:{sql:`(${t} NOT LIKE $1${a.lookup?` OR ${Te(a.lookup)} IS NULL`:""})`,params:[`pbe1.${e.currentKey()}.%`]}}async function Ft(a,e,t,n,s){let i=Dt(e,t),o=Te(e.column),c=n===null?"":` AND ctid > $${i.params.length+1}::tid`,r=await a(`SELECT ctid::text AS at, ${o} AS value FROM ${e.table} WHERE ${o} IS NOT NULL AND ${i.sql}${c} ORDER BY ctid LIMIT ${s}`,n===null?i.params:[...i.params,n]);if(r.length===0)return{done:0,last:null};let l=[],h=r.map(g=>{let f=Sn(t,e.address,g.value),R=[g.at,g.value,e.direction==="seal"?t.encrypt(e.address,f):f,...e.lookup?[t.lookup(e.address,f)]:[]],I=l.length+1;return l.push(...R),`(${R.map((p,m)=>`$${I+m}::text`).join(", ")})`}),N=[`${o} = v.next`,...e.lookup?[`${Te(e.lookup)} = v.lookup`]:[]],u=await a(`WITH done AS (UPDATE ${e.table} AS t SET ${N.join(", ")} FROM (VALUES ${h.join(", ")}) AS v(at, old, next${e.lookup?", lookup":""}) WHERE t.ctid = v.at::tid AND t.${o} = v.old RETURNING 1) SELECT count(*)::int AS n FROM done`,l);return{done:Number(u[0]?.n??0),last:r.length<s?null:r[r.length-1].at}}function Sn(a,e,t){if(!a.isEncrypted(t))return t;try{return a.decrypt(e,t)}catch{return t}}function os(a,e){if(typeof e=="string"&&e.startsWith(bt))throw new TypeError(`${a} is going over between plain and encrypted: a value beginning ${bt} would read as an encrypted one \u2014 it is written once the migration completes`)}async function xt(a,e,t){let n=Dt(e,t);return(await a(`SELECT 1 FROM ${e.table} WHERE ${Te(e.column)} IS NOT NULL AND ${n.sql} LIMIT 1`,n.params)).length>0}import{createHash as Ke}from"node:crypto";var K="palgres_search",Ie=(a,e)=>a.model===e.model&&a.dimensions===e.dimensions&&a.metric===e.metric&&a.from.length===e.from.length&&a.from.every((t,n)=>t===e.from[n]),vt=48;function Ve(a,e){let t=a.replaceAll(".","__");return`${t.length<=vt?t:`${t.slice(0,32)}_${Ke("md5").update(t).digest("hex").slice(0,12)}`}__g${e}`}var Ut=a=>({insert:`_palgres_search_g${a}_ins`,update:`_palgres_search_g${a}_upd`});function Le(a,e){let t=Ke("sha256").update(JSON.stringify([a.schema,a.name,e])).digest("hex").slice(0,8),n=`_palgres_search_${a.name}_${t}`;return Buffer.byteLength(n)<=63?n:`_palgres_search_${Ke("sha256").update(`${a.schema}.${a.name}`).digest("hex").slice(0,16)}_${t}`}function yn(a,e){let t=e===void 0?"":`${T(e)}.`;return a.map(n=>`coalesce(${t}${T(n)}::text, '')`).join(" || ' ' || ")}var Mt=(a,e)=>`to_tsvector('simple', ${yn(a,e)})`;function Rn(a,e){let t=a>lt?"halfvec":"vector",n={cosine:["cosine","<=>"],euclidean:["l2","<->"],inner_product:["ip","<#>"]}[e];return{type:t,opclass:`${t}_${n[0]}_ops`,operator:n[1]}}function Pt(a){let e=`${a.table.schema}.${a.table.name}`,t=L(a.table.schema,a.table.name),n=Ve(e,a.gen),s=L(K,n),i=Rn(a.search.dimensions,a.search.metric),o=T(a.pk.name),c=[a.roles.anon,a.roles.authenticated].map(T).join(", ");return[`INSERT INTO ${K}.generations (table_key, gen, model, dimensions, metric, from_columns, status, promoted_at) VALUES (${A(e)}, ${a.gen}, ${A(a.search.model)}, ${a.search.dimensions}, ${A(a.search.metric)}, ARRAY[${a.search.from.map(A).join(", ")}]::text[], ${A(a.status)}, ${a.status==="active"?"now()":"NULL"})`,`CREATE TABLE ${s} (
3
+ id ${a.pk.type} PRIMARY KEY REFERENCES ${t} (${o}) ON DELETE CASCADE,
4
+ embedding ${T(a.types)}.${i.type}(${a.search.dimensions}) NOT NULL,
5
+ model text NOT NULL,
6
+ embedded_at timestamptz NOT NULL DEFAULT now()
7
+ )`,`CREATE INDEX ON ${s} USING hnsw (embedding ${T(a.types)}.${i.opclass})`,`ALTER TABLE ${s} ENABLE ROW LEVEL SECURITY`,`CREATE POLICY ${T("_palgres_search_parent")} ON ${s} FOR SELECT TO ${c} USING (EXISTS (SELECT 1 FROM ${t} p WHERE p.${o} = ${T(n)}.id))`,`GRANT SELECT ON TABLE ${s} TO ${c}`,`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${s} TO ${T(a.roles.service)}`,`CREATE FUNCTION ${s}() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $palgres$
8
+ BEGIN
9
+ -- A generation left behind keeps its triggers until the next migration takes them: they do nothing.
10
+ IF NOT EXISTS (SELECT 1 FROM ${K}.generations g WHERE g.table_key = ${A(e)} AND g.gen = ${a.gen} AND g.status <> 'retired') THEN
11
+ RETURN NULL;
12
+ END IF;
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 ${K}.queue (table_key, gen, row_id) VALUES (${A(e)}, ${a.gen}, NEW.${o}::text)
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
+ -- 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
+ IF TG_OP = 'UPDATE' AND TG_ARGV[0] = 'null' THEN
18
+ DELETE FROM ${s} WHERE id = NEW.${o};
19
+ END IF;
20
+ RETURN NULL;
21
+ END $palgres$`,`REVOKE ALL ON FUNCTION ${s}() FROM PUBLIC`,...be({table:a.table,gen:a.gen,from:a.search.from,staleness:a.search.staleness},!1)]}function be(a,e){let t=L(a.table.schema,a.table.name),n=`${L(K,Ve(`${a.table.schema}.${a.table.name}`,a.gen))}(${A(a.staleness)})`,s=Ut(a.gen),i=e?"CREATE OR REPLACE TRIGGER":"CREATE TRIGGER",o=a.from.map(c=>`OLD.${T(c)} IS DISTINCT FROM NEW.${T(c)}`).join(" OR ");return[`${i} ${T(s.insert)} AFTER INSERT ON ${t} FOR EACH ROW EXECUTE FUNCTION ${n}`,`${i} ${T(s.update)} AFTER UPDATE OF ${a.from.map(T).join(", ")} ON ${t} FOR EACH ROW WHEN (${o}) EXECUTE FUNCTION ${n}`]}function qt(a,e,t){return`INSERT INTO ${K}.queue (table_key, gen, row_id) SELECT ${A(`${a.schema}.${a.name}`)}, ${e}, ${T(t)}::text FROM ${L(a.schema,a.name)} ON CONFLICT ON CONSTRAINT queue_one_pending DO NOTHING`}function Ce(a,e){let t=`${a.schema}.${a.name}`,n=L(a.schema,a.name),s=L(K,Ve(t,e)),i=Ut(e);return[`DROP TRIGGER IF EXISTS ${T(i.insert)} ON ${n}`,`DROP TRIGGER IF EXISTS ${T(i.update)} ON ${n}`,`DROP TABLE IF EXISTS ${s}`,`DROP FUNCTION IF EXISTS ${s}()`,`DELETE FROM ${K}.queue WHERE table_key = ${A(t)} AND gen = ${e}`,`DELETE FROM ${K}.generations WHERE table_key = ${A(t)} AND gen = ${e}`]}var ke=a=>`palgres search 1 (${a.anon}, ${a.authenticated}, ${a.service})`;function Ht(a){let e=[a.anon,a.authenticated,a.service].map(T).join(", "),t=T(a.service),n=K;return[`CREATE SCHEMA IF NOT EXISTS ${n}`,`CREATE TABLE IF NOT EXISTS ${n}.generations (
22
+ table_key text NOT NULL,
23
+ gen integer NOT NULL,
24
+ model text NOT NULL,
25
+ dimensions integer NOT NULL,
26
+ metric text NOT NULL,
27
+ from_columns text[] NOT NULL,
28
+ status text NOT NULL CHECK (status IN ('filling', 'active', 'retired')),
29
+ created_at timestamptz NOT NULL DEFAULT now(),
30
+ promoted_at timestamptz,
31
+ PRIMARY KEY (table_key, gen)
32
+ )`,`CREATE TABLE IF NOT EXISTS ${n}.queue (
33
+ id bigserial PRIMARY KEY,
34
+ table_key text NOT NULL,
35
+ gen integer NOT NULL,
36
+ row_id text NOT NULL,
37
+ enqueued_at timestamptz NOT NULL DEFAULT clock_timestamp(),
38
+ attempts integer NOT NULL DEFAULT 0,
39
+ next_attempt_at timestamptz NOT NULL DEFAULT now(),
40
+ last_error text,
41
+ CONSTRAINT queue_one_pending UNIQUE (table_key, gen, row_id),
42
+ CONSTRAINT queue_due UNIQUE (next_attempt_at, enqueued_at, id)
43
+ )`,`GRANT USAGE ON SCHEMA ${n} TO ${e}`,`GRANT SELECT ON TABLE ${n}.generations TO ${e}`,`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${n}.queue TO ${t}`,`GRANT USAGE, SELECT ON SEQUENCE ${n}.queue_id_seq TO ${t}`,`CREATE OR REPLACE FUNCTION ${n}.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) <= ${vt} THEN b ELSE left(b, 32) || '_' || left(md5(b), 12) END || '__g' || gen FROM (SELECT replace(of_table, '.', '__') AS b) x
45
+ $palgres$`,`CREATE OR REPLACE FUNCTION ${n}.promote(of_table text) RETURNS integer LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $palgres$
46
+ DECLARE
47
+ g ${n}.generations%ROWTYPE;
48
+ parent regclass;
49
+ pk name;
50
+ source text;
51
+ missing boolean;
52
+ BEGIN
53
+ -- Never beside a migration: one that is open may be rolled back onto the generation that serves, and one being planned reads the generations as they are.
54
+ IF NOT pg_try_advisory_xact_lock(hashtextextended('palgres.migrate', 0)) THEN RETURN NULL; END IF;
55
+ IF EXISTS (SELECT 1 FROM palgres.migration) THEN RETURN NULL; END IF;
56
+ SELECT * INTO g FROM ${n}.generations WHERE table_key = of_table AND status = 'filling' ORDER BY gen DESC LIMIT 1 FOR UPDATE;
57
+ IF NOT FOUND THEN RETURN NULL; END IF;
58
+ IF EXISTS (SELECT 1 FROM ${n}.queue q WHERE q.table_key = of_table AND q.gen = g.gen) THEN RETURN NULL; END IF;
59
+ parent := to_regclass(format('%I.%I', split_part(of_table, '.', 1), substr(of_table, strpos(of_table, '.') + 1)));
60
+ IF parent IS NULL THEN RETURN NULL; END IF;
61
+ SELECT a.attname INTO pk FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = i.indkey[0] WHERE i.indrelid = parent AND i.indisprimary AND i.indnkeyatts = 1;
62
+ IF pk IS NULL THEN RETURN NULL; END IF;
63
+ SELECT string_agg(format('coalesce(p.%I::text, '''')', f.c), ' || '' '' || ' ORDER BY f.o) INTO source FROM unnest(g.from_columns) WITH ORDINALITY AS f(c, o);
64
+ -- A row with no text has no vector; every other has one, or the generation is not full.
65
+ EXECUTE format('SELECT EXISTS (SELECT 1 FROM %s p WHERE btrim(%s) <> '''' AND NOT EXISTS (SELECT 1 FROM ${n}.%I v WHERE v.id = p.%I))', parent, source, ${n}.vectors(of_table, g.gen), pk) INTO missing;
66
+ IF missing THEN RETURN NULL; END IF;
67
+ UPDATE ${n}.generations SET status = 'retired' WHERE table_key = of_table AND status = 'active';
68
+ UPDATE ${n}.generations SET status = 'active', promoted_at = now() WHERE table_key = of_table AND gen = g.gen;
69
+ RETURN g.gen;
70
+ END $palgres$`,`REVOKE ALL ON FUNCTION ${n}.promote(text) FROM PUBLIC`,`GRANT EXECUTE ON FUNCTION ${n}.promote(text) TO ${t}`,`COMMENT ON SCHEMA ${n} IS ${A(ke(a))}`]}var Ye=new Set,ds={listen(a){return Ye.add(a),()=>{Ye.delete(a)}},committed(){for(let a of Ye)a()}};import{createHash as Yt}from"node:crypto";var Kt=new Set(["tx","statement","backfill","seal","settle"]),Ze=2;function An(...a){return a.some(e=>e.some(t=>t.kind==="seal"||t.kind==="settle"))?2:1}var de=(a,e)=>`palgres_${a}_${e}`,et=a=>Yt("sha256").update(a).digest("hex").slice(0,8),_e=(a,e)=>`${a.name}_${e}_${et(JSON.stringify([a.schema,a.name,e])).slice(0,6)}`,X=(a,e,t)=>{let n=`_palgres_${a}_${e}_${t}`;return Buffer.byteLength(n)<=63?n:`_palgres_${a}_${e}_${et(t)}`},le={anon:"anon",backend_anon:"anon",authenticated:"authenticated",backend_authenticated:"authenticated",service_role:"service",backend_service_role:"service",public:"public"},xe=a=>!a.nullable&&a.default===void 0&&!a.identity&&!a.generated,me=a=>a.ignored===!0&&a.fill!==void 0&&xe(a),On=a=>{if(a.generated||a.identity)return;let e=T(a.name);return a.default===void 0?`${e} IS NOT NULL`:`${e}::text IS DISTINCT FROM (${a.default})::text`},Wt="the version serving now reads that value in the rows the new version writes",wn={smallint:["integer","bigint","numeric"],integer:["bigint","numeric"],bigint:["numeric"],real:["double precision"],"character varying":["text"],text:["character varying"]};function ze(a,e){let t=Y(a),n=Y(e);if(wn[t]?.includes(n))return!0;let s=c=>/^character varying\((\d+)\)$/.exec(c)?.[1],i=s(t);if(i===void 0)return!1;let o=s(n);return n==="text"||n==="character varying"||o!==void 0&&Number(o)>=Number(i)}var Ne=a=>{let e=Y(a);if(["smallint","integer","bigint"].includes(e))return"integer";if(e==="text"||/^character varying(\(\d+\))?$/.test(e))return"text"},In=(a,e)=>Ne(a)!==void 0&&Ne(a)===Ne(e)&&ze(a,e),Ln="data_exception OR integrity_constraint_violation",Bt="palgres: every value converted";function Vt(a){return new Qe(a).run()}var Qe=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=re(e.from?.schema??ct());let t=new Map((e.from?.schema.raw??[]).map((s,i)=>[s.name,i]));this.from.raw.sort((s,i)=>(t.get(s.name)??0)-(t.get(i.name)??0)),this.to=re(e.to);let n=new Map(e.to.raw.map((s,i)=>[s.name,i]));this.to.raw.sort((s,i)=>(n.get(s.name)??0)-(n.get(i.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 i of this.to.tables){let o=this.matches.get(b(i));o?(this.alterTable(o),this.encryption(o)):this.createTable(i),this.search(i,o)}for(let i of this.from.tables)this.fromMatched.has(i)||this.dropTable(i);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`}],t=[...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(i=>i.kind==="tx"?i.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"}]:[]],n=[...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"}]:[]],s=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:An(e,t,n),from:this.fromN,to:this.n,changes:this.changes,refusals:this.refusals,start:e,complete:t,rollback:n,layout:this.layout,...s}}dropTables(){let e=`DROP TABLE IF EXISTS ${this.completeDrops.join(", ")}`;if(this.completeDropsFoundEmpty.length===0)return e;let t=this.completeDropsFoundEmpty.map(s=>`EXISTS (SELECT 1 FROM ${s})`).join(" OR "),n=A("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 ${t} THEN RAISE WARNING 'palgres: %', ${n}; ELSE ${e}; END IF; END $palgres$`}refuse(e,t){this.refusals.push(`${e}: ${t}`)}encryption(e){let t=b(e.to),n=this.input.hasRows(b(e.from)),s=new Map(e.from.columns.map(o=>[o.name,o])),i=new Map([...e.renamed].map(([o,c])=>[c,o]));for(let o of e.to.columns){if(o.lookupOf!==void 0)continue;let c=s.get(i.get(o.name)??o.name);if(c===void 0||e.parked.has(o.name))continue;let r=o.encrypted!==void 0,l=c.encrypted!==void 0;if(!r&&!l)continue;if(n&&(c.name!==o.name||e.from.name!==e.to.name)){this.refuse(`column ${t}.${o.name} is encrypted and is renamed (or its table is) while the table holds rows: its values are bound to ${je(e.from.schema,e.from.name,c.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(r===l)continue;if(e.retyped.has(o.name)){this.refuse(`column ${t}.${o.name} changes its type and its encryption in one deploy`,"change one, deploy, then the other");continue}if(!n)continue;let h=je(e.to.schema,e.to.name,o.name);if(r&&o.encrypted?.lookup){let f=o.encrypted.lookup,R=e.to.uniques.some(p=>p.columns.includes(f))||e.to.indexes.some(p=>p.unique&&p.keys.some(m=>"column"in m&&m.column===f)),I=e.from.uniques.some(p=>p.columns.length===1&&p.columns[0]===c.name)||e.from.indexes.some(p=>p.unique&&p.keys.length===1&&"column"in p.keys[0]&&p.keys[0].column===c.name);if(R&&!I){this.refuse(`column ${t}.${o.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 N=r?"seal":"open",u=A(h);this.changes.push(`column ${t}.${o.name} ${r?"becomes encrypted: its rows are sealed":"stops being encrypted: its rows are opened"} at complete`),this.sealingStart.push({kind:"tx",sql:[`INSERT INTO ${ie} (address, direction, phase) VALUES (${u}, ${A(N)}, 'mixed') ON CONFLICT (address) DO UPDATE SET direction = EXCLUDED.direction, phase = 'mixed'`],why:`${h} goes over: the old version's form kept while it serves`}),N==="open"&&this.sealingStart.push({kind:"settle",ms:_t,why:`the version serving reads that ${h} goes over`});let g=r&&o.encrypted?.lookup?e.cols.get(o.encrypted.lookup)??o.encrypted.lookup:null;if(this.sealingComplete.push({kind:"tx",sql:[`UPDATE ${ie} SET phase = 'final' WHERE address = ${u}`],why:`${h}: the old version is gone, the new form is written`},{kind:"seal",table:L(e.from.schema,e.physical),column:c.name,lookup:g,address:h,direction:N,why:`${h}'s rows ${r?"sealed":"opened"}`},{kind:"tx",sql:[`DELETE FROM ${ie} WHERE address = ${u}`],why:`${h} has gone over`}),N==="open"){let f=c.encrypted?.lookup??null;this.sealingUndo.push({kind:"seal",table:L(e.from.schema,e.physical),column:c.name,lookup:f,address:h,direction:"seal",why:`${h}'s rows the abandoned version wrote plain, sealed again`})}this.sealingUndo.push({kind:"tx",sql:[`DELETE FROM ${ie} WHERE address = ${u}`],why:`${h} 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 ${T(e)}`,why:`extension ${e}`}))}schemas(){let e=new Set([...this.from.tables.map(o=>o.schema),...this.from.enums.map(o=>o.schema),...this.from.raw.flatMap(o=>o.schema?[o.schema]:[]),"public"]),t=[...new Set([...this.to.tables.map(o=>o.schema),...this.to.enums.map(o=>o.schema),...this.to.raw.flatMap(o=>o.schema?[o.schema]:[])])].filter(o=>!e.has(o)),{anon:n,authenticated:s,service:i}=this.input.roles;for(let o of t)this.changes.push(`schema ${o}`),this.creates.push(`CREATE SCHEMA IF NOT EXISTS ${T(o)}`,`GRANT USAGE ON SCHEMA ${T(o)} TO ${[n,s,i].map(T).join(", ")}`)}enums(){for(let e of this.to.enums){let t=this.from.enums.find(i=>i.schema===e.schema&&i.name===e.name),n=L(e.schema,e.name);if(!t){this.changes.push(`type ${e.schema}.${e.name}`),this.creates.push(`CREATE TYPE ${n} AS ENUM (${e.values.map(A).join(", ")})`),this.undoCreates.push(`DROP TYPE IF EXISTS ${n}`);continue}let s=t.values.filter(i=>!e.values.includes(i));s.length>0&&this.refuse(`type ${e.schema}.${e.name} loses ${s.join(", ")}`,"Postgres cannot take a value out of an enum; add a new type and move the column to it");for(let i of e.values)t.values.includes(i)||(this.changes.push(`type ${e.schema}.${e.name} gains '${i}'`),this.prelude.push({kind:"statement",sql:`ALTER TYPE ${n} ADD VALUE IF NOT EXISTS ${A(i)}`,why:`${e.name} gains ${i}`}))}}enumDrops(){for(let e of this.from.enums)this.to.enums.some(t=>t.schema===e.schema&&t.name===e.name)||(this.changes.push(`type ${e.schema}.${e.name} goes (at complete)`),this.completeTypes.push(`DROP TYPE IF EXISTS ${L(e.schema,e.name)}`))}matchTables(){let e=new Map(this.from.tables.map(t=>[b(t),t]));for(let t of this.to.tables)t.renamedFrom===void 0||t.renamedFrom===t.name||!e.has(`${t.schema}.${t.renamedFrom}`)||this.to.tables.some(n=>n!==t&&n.schema===t.schema&&n.name===t.renamedFrom)&&this.refuse(`table ${t.schema}.${t.renamedFrom} is renamed ${t.name}, and a new table takes the name ${t.renamedFrom} in the same deploy`,`rename it in this deploy, and make the new ${t.renamedFrom} in the next`);for(let t of this.to.tables){let n=e.get(b(t));if(t.renamedFrom!==void 0&&t.renamedFrom!==t.name){let s=e.get(`${t.schema}.${t.renamedFrom}`);n&&s&&this.refuse(`table ${b(t)} is renamed from ${t.renamedFrom}, but ${b(t)} is there already`,"remove renamedFrom, or rename to a free name"),!n&&s&&(n=s)}!n||this.fromMatched.has(n)||(this.fromMatched.add(n),this.matches.set(b(t),this.matchColumns(t,n)))}}matchColumns(e,t){let n=b(e),s=new Map(t.columns.map(r=>[r.name,r])),i={to:e,from:t,physical:t.name,renamed:new Map,cols:new Map,retyped:new Map,parked:new Map},o=new Set,c=new Set(e.columns.filter(r=>r.renamedFrom!==void 0&&r.renamedFrom!==r.name&&s.has(r.renamedFrom)&&!s.has(r.name)).map(r=>r.renamedFrom));for(let r of e.columns){let l=c.has(r.name)?void 0:s.get(r.name);if(r.renamedFrom!==void 0&&r.renamedFrom!==r.name&&s.has(r.renamedFrom)&&(s.has(r.name)?this.refuse(`column ${n}.${r.name} is renamed from ${r.renamedFrom}, but ${r.name} is there already`,"remove renamedFrom, or rename to a free name"):l=s.get(r.renamedFrom)),!l&&c.has(r.name)){let h=X(this.n,"add",r.name);i.parked.set(r.name,h),i.cols.set(r.name,h);continue}if(!l||o.has(l.name)){i.cols.set(r.name,r.name);continue}if(o.add(l.name),l.name!==r.name&&i.renamed.set(l.name,r.name),Y(l.type)!==Y(r.type)){let h=X(this.n,"new",r.name);i.retyped.set(r.name,{shadow:h,from:l,to:r}),i.cols.set(r.name,h)}else i.cols.set(r.name,l.name)}return i}inNewNames(e){let n=[...this.matches.values()].find(o=>o.from===e)?.renamed??new Map,s=o=>n.get(o)??o,i=o=>J(o,n);return{...e,uniques:e.uniques.map(o=>({...o,columns:o.columns.map(s)})),indexes:e.indexes.map(o=>({...o,keys:o.keys.map(c=>"column"in c?{...c,column:s(c.column)}:{...c,expr:i(c.expr)}),include:o.include?.map(s),where:o.where===void 0?void 0:i(o.where)})),checks:e.checks.map(o=>({...o,expr:i(o.expr)})),foreignKeys:e.foreignKeys.map(o=>this.fkInNewNames(o,s)),policies:e.policies.map(o=>({...o,using:o.using===void 0?void 0:i(o.using),withCheck:o.withCheck===void 0?void 0:i(o.withCheck)})),primaryKey:e.primaryKey.map(s)}}fkInNewNames(e,t){let n=this.from.tables.find(i=>i.schema===e.refSchema&&i.name===e.refTable),s=n&&[...this.matches.values()].find(i=>i.from===n);return{...e,columns:e.columns.map(t),refTable:s?s.to.name:e.refTable,refColumns:e.refColumns.map(i=>s?.renamed.get(i)??i)}}where(e){let t=this.matches.get(b(e));return t?{table:t.physical,cols:t.cols}:{table:e.name,cols:new Map(e.columns.map(n=>[n.name,n.name]))}}grants(e){let{anon:t,authenticated:n,service:s}=this.input.roles;return[`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${e} TO ${[t,n,s].map(T).join(", ")}`]}typeSql(e){let t=/^([a-z_][a-z0-9_]*)\.([a-z_][a-z0-9_]*)((?:\[\])*)$/i.exec(e);return t?`${L(t[1],t[2])}${t[3]}`:e}columnSql(e){let t=`${T(e.name)} ${this.typeSql(e.type)}`;return e.identity&&(t+=` GENERATED ${e.identity==="always"?"ALWAYS":"BY DEFAULT"} AS IDENTITY`),e.generated&&(t+=` GENERATED ALWAYS AS (${e.generated.expr}) ${e.generated.stored?"STORED":"VIRTUAL"}`),e.default!==void 0&&(t+=` DEFAULT ${e.default}`),e.nullable||(t+=" NOT NULL"),t}sequences(e,t,n,s){let{anon:i,authenticated:o,service:c}=this.input.roles;for(let r of Xt(t.default)){let l=new RegExp(String.raw`\bCREATE\s+SEQUENCE\s+(?:IF\s+NOT\s+EXISTS\s+)?${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\w$"])`,"i");if(this.to.raw.some(h=>l.test(h.sql))){s.push(`GRANT USAGE, SELECT ON SEQUENCE ${r} TO ${[i,o,c].map(T).join(", ")}`);continue}n.push(`CREATE SEQUENCE IF NOT EXISTS ${r}`),s.push(`ALTER SEQUENCE ${r} OWNED BY ${L(e.schema,e.name)}.${T(t.name)}`,`GRANT USAGE, SELECT ON SEQUENCE ${r} TO ${[i,o,c].map(T).join(", ")}`)}}createTable(e){let t=L(e.schema,e.name),n=new Map(e.columns.map(r=>[r.name,r.name]));this.changes.push(`table ${b(e)}`);let s=[];for(let r of e.columns)this.sequences(e,r,this.creates,s);let i=e.columns.map(r=>this.columnSql(r)),o=new Set,c=[];e.primaryKey.length>0&&(i.push(`PRIMARY KEY (${ee(e.primaryKey)})`),o.add(e.primaryKey.join("\0")));for(let r of e.uniques){let l=r.columns.join("\0");o.has(l)?c.push(`ALTER TABLE ${t} ADD CONSTRAINT ${T(r.name)} UNIQUE (${ee(r.columns)})`):i.push(`CONSTRAINT ${T(r.name)} UNIQUE (${ee(r.columns)})`),o.add(l)}for(let r of e.checks)i.push(`CONSTRAINT ${T(r.name)} CHECK (${r.expr})`);this.creates.push(`CREATE TABLE ${t} (
71
+ ${i.join(`,
72
+ `)}
73
+ )`,...c,...s);for(let r of e.indexes)this.creates.push(this.indexSql(e.schema,e.name,r,n,!1));for(let r of e.foreignKeys){let l=`${r.refSchema}.${r.refTable}`;this.from.tables.some(h=>b(h)===l)&&l!==b(e)?(this.lateFks.push({kind:"tx",sql:[`ALTER TABLE ${t} ADD ${this.fkSql(r,n)} NOT VALID`],why:`foreign key ${r.name}`}),this.lateFks.push({kind:"statement",sql:`ALTER TABLE ${t} VALIDATE CONSTRAINT ${T(r.name)}`,why:`foreign key ${r.name}`}),this.undoFksGone.push({kind:"tx",sql:[`ALTER TABLE IF EXISTS ${t} DROP CONSTRAINT IF EXISTS ${T(r.name)}`],why:`foreign key ${r.name}`})):this.createFks.push(`ALTER TABLE ${t} ADD ${this.fkSql(r,n)}`)}for(let r of e.columns.filter(me)){let l=this.ignoredFillNames(e,r.name);this.creates.push(this.ignoredFillFunction(l.fn,r.name,r.fill,e.name),`CREATE TRIGGER ${T(l.trigger)} BEFORE INSERT ON ${t} FOR EACH ROW EXECUTE FUNCTION ${l.fn}()`,`SELECT (
74
+ ${r.fill}
75
+ ) FROM ${t} AS ${T(e.name)} LIMIT 0`),this.undoCreates.push(`DROP FUNCTION IF EXISTS ${l.fn}()`)}this.creates.push(...ge(t,e.rls,!1));for(let r of e.policies)ae(r.using)||ae(r.withCheck)?this.accessPolicies.push({q:t,table:e,to:r}):this.readsOthersRenamed(e,r,b(e))||this.createFks.push(this.policySql(t,r,n));this.creates.push(...this.grants(t)),this.undoNewTables.push(t),this.addLayout(e,e.name,n)}dropTable(e){if(!e.ignored&&this.input.hasRows(b(e))){this.refuse(`table ${b(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 ${b(e)} goes (at complete)`),this.searchGone(e,e.name),this.completeDrops.push(L(e.schema,e.name));for(let t of e.foreignKeys){let n=[...this.matches.values()].find(s=>s.from.schema===t.refSchema&&s.from.name===t.refTable);n&&[...n.retyped.values()].some(s=>t.refColumns.includes(s.from.name))&&this.completeFks.push({kind:"tx",sql:[`ALTER TABLE IF EXISTS ${L(e.schema,e.name)} DROP CONSTRAINT IF EXISTS ${T(t.name)}`],why:`foreign key ${t.name}, onto the old column`})}for(let t of e.columns.filter(me))this.completeTypes.push(`DO $palgres$ BEGIN IF to_regclass(${A(L(e.schema,e.name))}) IS NULL THEN DROP FUNCTION IF EXISTS ${this.ignoredFillNames(e,t.name).fn}(); END IF; END $palgres$`);e.ignored||(this.completeDropsFoundEmpty.push(L(e.schema,e.name)),this.guarded.tables.push([e.schema,e.name]))}addLayout(e,t,n){e.ignored||this.layout.tables.push({schema:e.schema,name:e.name,physical:t,columns:e.columns.filter(s=>!s.ignored).map(s=>({name:s.name,physical:n.get(s.name)}))})}alterTable(e){let{to:t,from:n}=e,s=L(t.schema,e.physical),i=b(t),o={tx:[],undo:[],undoColumns:[],complete:[]},c=this.input.hasRows(b(n));t.name!==n.name&&this.changes.push(`table ${t.schema}.${n.name} is renamed ${t.name} (at complete)`);let r=new Map(n.columns.map(u=>[u.name,u])),l=new Set,h=[];for(let u of t.columns){let g=e.cols.get(u.name),f=e.retyped.get(u.name),R=f?.from??(e.parked.has(u.name)?void 0:r.get(g));if(u.nullable&&u.fill!==void 0&&u.fill!==R?.fill&&!(f&&!ze(f.from.type,u.type))&&this.refuse(`column ${i}.${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"),!R){this.addColumn(t,s,g===u.name?u:{...u,name:g},o),me(u)&&this.ignoredFill(e,s,void 0,u,o,h);continue}if(l.add(R.name),f){this.retype(e,s,u.name,f,o);continue}R.name!==u.name&&(this.changes.push(`column ${i}.${R.name} is renamed ${u.name} (at complete)`),o.complete.push(`ALTER TABLE ${s} RENAME COLUMN ${T(R.name)} TO ${T(u.name)}`),o.names=!0),u.ignored&&!R.ignored&&this.insertsWithout(i,u),this.alterColumn(t,s,R,u,o),this.ignoredFill(e,s,R,u,o,h)}for(let u of n.columns){if(l.has(u.name))continue;if(me(u)&&o.complete.unshift(...this.ignoredFillDrop(e.from,s,u.name)),!u.ignored&&c&&u.lookupOf===void 0){let R=xe(u)?` \u2014 and, being NOT NULL with no default, with one (.default(\u2026)) or the value computed from the row (.fillWith(sql)): ${Wt}`:"";this.refuse(`column ${b(n)}.${u.name} is gone from the schema and the table has rows`,`mark it ignored first (.ignored())${R}, and deploy; remove it in the deploy after that, when its data may go`);continue}u.ignored||this.insertsWithout(i,u),this.changes.push(`column ${b(n)}.${u.name} goes (at complete)`);let g=`ALTER TABLE ${s} DROP COLUMN IF EXISTS ${T(u.name)}`,f=u.ignored||u.lookupOf!==void 0?void 0:On(u);if(f===void 0)o.complete.push(g);else{let R=A(`column ${b(n)}.${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`);o.complete.push(`DO $palgres$ BEGIN IF EXISTS (SELECT 1 FROM ${s} WHERE ${f}) THEN RAISE WARNING 'palgres: %', ${R}; ELSE ${g}; END IF; END $palgres$`),this.guarded.columns.push([t.schema,t.name,u.name])}o.names=!0,o.dropsColumns=!0}if(this.constraints(e,s,o),this.policies(e,s,o),n.rls!==t.rls){this.changes.push(`table ${i}: row-level security ${t.rls?"on":"off"}`);let u=g=>ae(g.using)||ae(g.withCheck);if(e.from.policies.some(u)||t.policies.some(u)){let g=`(SELECT coalesce(pg_catalog.current_setting('palgres.version', true), '') = ${A(String(this.input.next))})`,f=T("palgres_was_open");t.rls?(o.tx.push(`DROP POLICY IF EXISTS ${f} ON ${s}`,`CREATE POLICY ${f} ON ${s} AS PERMISSIVE FOR ALL TO PUBLIC USING (NOT ${g}) WITH CHECK (NOT ${g})`,...ge(s,!0,!0)),o.complete.push(`DROP POLICY IF EXISTS ${f} ON ${s}`),o.undo.push(`DROP POLICY IF EXISTS ${f} ON ${s}`,...ge(s,!1,!0))):(o.tx.push(`DROP POLICY IF EXISTS ${f} ON ${s}`,`CREATE POLICY ${f} ON ${s} AS PERMISSIVE FOR ALL TO PUBLIC USING (${g}) WITH CHECK (${g})`),o.complete.push(`DROP POLICY IF EXISTS ${f} ON ${s}`,...ge(s,!1,!0)),o.undo.push(`DROP POLICY IF EXISTS ${f} ON ${s}`))}else o.tx.push(...ge(s,t.rls,!0)),o.undo.push(...ge(s,n.rls,!0))}this.inNewNames(n).primaryKey.join()!==t.primaryKey.join()&&this.refuse(`the primary key of ${i} changes`,"a primary key cannot change while both versions write the table; add a unique constraint instead"),o.tx.length>0&&this.alters.push({kind:"tx",sql:o.tx,why:`table ${i}`});let N=[...o.undo,...o.undoColumns];N.length>0&&this.undoTables.push({kind:"tx",sql:N,why:`table ${i}`});for(let[u,g]of e.parked)this.changes.push(`column ${i}.${u} is made as ${g}, and takes its name at complete`),o.complete.push(`ALTER TABLE ${s} RENAME COLUMN ${T(g)} TO ${T(u)}`),o.names=!0;t.name!==n.name&&(o.complete.push(`ALTER TABLE ${s} RENAME TO ${T(t.name)}`),o.names=!0),o.complete.push(...h),o.names&&(this.namesAtComplete=!0),o.dropsColumns&&(this.dropsColumnsAtComplete=!0),o.complete.length>0&&this.completeTables.push({kind:"tx",sql:o.complete,why:`table ${i}`}),this.addLayout(t,e.physical,e.cols)}sequenceRenamed(e,t){let[n,s]=ve(e.default),[i,o]=ve(t.default);if(n===void 0||i===void 0||s!==void 0||o!==void 0||(n.schema??null)!==(i.schema??null)||n.name===i.name)return;let c=g=>g.replace(zt,"nextval()");if(c(e.default)!==c(t.default))return;let r=g=>f=>f.name===g.name&&(f.schema??null)===(g.schema??null),l=g=>this.from.tables.flatMap(f=>f.columns).filter(f=>ve(f.default).some(r(g))).length;if(l(n)!==1||l(i)!==0)return;let h=g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),N=i.schema===void 0?String.raw`[^".\s]+`:h(i.schema),u=new RegExp(String.raw`\bSEQUENCE\s+(?:IF\s+NOT\s+EXISTS\s+)?(?:"?${N}"?\.)?"?${h(i.name)}"?(?![\w$"])`,"i");if(!this.from.raw.some(g=>u.test(g.sql)))return{from:n.schema===void 0?T(n.name):L(n.schema,n.name),to:i.name}}insertsWithout(e,t){xe(t)&&!me(t)&&this.refuse(`column ${e}.${t.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)): ${Wt} \u2014 or make it nullable in this deploy, if that version can read it empty`)}ignoredFillNames(e,t){let n=i=>{let o=`_palgres_keep_${i}`;return Buffer.byteLength(o)<=63?o:`_palgres_keep_${et(i)}`},s=n(_e(e,t));return{fn:L(e.schema,s),name:s,trigger:n(t)}}ignoredFillFunction(e,t,n,s){let i=T(t);return`CREATE OR REPLACE FUNCTION ${e}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
76
+ BEGIN
77
+ IF NEW.${i} IS NULL THEN
78
+ NEW.${i} := (SELECT (
79
+ ${n}
80
+ ) FROM (SELECT (NEW).*) AS ${T(s)});
81
+ END IF;
82
+ RETURN NEW;
83
+ END $palgres$`}ignoredFillDrop(e,t,n){let s=this.ignoredFillNames(e,n);return[`DROP TRIGGER IF EXISTS ${T(s.trigger)} ON ${t}`,`DROP FUNCTION IF EXISTS ${s.fn}()`]}ignoredFill(e,t,n,s,i,o){let c=n!==void 0&&me(n),r=me(s);if(!c&&!r)return;let l=b(e.to),h=L(e.to.schema,e.to.name),N=e.cols.get(s.name),u=n===void 0?void 0:this.ignoredFillNames(e.from,n.name),g=this.ignoredFillNames(e.to,s.name);if(!r){if(s.ignored&&xe(s)){this.refuse(`column ${l}.${s.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}i.complete.unshift(...this.ignoredFillDrop(e.from,t,n.name));return}let f=e.from.columns.map(p=>p.name).filter(p=>!e.to.columns.some(m=>m.name===p)&&ne(s.fill,p));if(f.length>0){this.refuse(`column ${l}.${s.name}'s .fillWith reads ${f.join(", ")}, which this deploy renames or drops`,"say it by the names of the new version");return}let R=J(s.fill,se(e.cols)),I=`SELECT (
84
+ ${R}
85
+ ) FROM ${t} AS ${T(e.physical)} LIMIT 0`;c?(n.fill!==s.fill&&(this.changes.push(`column ${l}.${s.name}: its .fillWith changes`),i.tx.push(this.ignoredFillFunction(u.fn,N,R,e.physical),I),i.undo.push(this.ignoredFillFunction(u.fn,n.name,n.fill,e.from.name))),u.fn!==g.fn&&o.push(`ALTER FUNCTION ${u.fn}() RENAME TO ${T(g.name)}`),u.trigger!==g.trigger&&o.push(`ALTER TRIGGER ${T(u.trigger)} ON ${h} RENAME TO ${T(g.trigger)}`)):(this.changes.push(`column ${l}.${s.name}: a row inserted without it gets the value of its .fillWith (while it is ignored)`),i.tx.push(this.ignoredFillFunction(g.fn,N,R,e.physical),`CREATE TRIGGER ${T(g.trigger)} BEFORE INSERT ON ${t} FOR EACH ROW EXECUTE FUNCTION ${g.fn}()`,I),i.undo.push(`DROP TRIGGER IF EXISTS ${T(g.trigger)} ON ${t}`,`DROP FUNCTION IF EXISTS ${g.fn}()`)),(R!==s.fill||e.physical!==e.to.name||N!==s.name)&&o.push(this.ignoredFillFunction(g.fn,s.name,s.fill,e.to.name))}addColumn(e,t,n,s){let i=[];this.sequences(e,n,s.tx,i),this.addColumnItself(e,t,n,s),s.tx.push(...i)}addColumnItself(e,t,n,s){let i=b(e),o=T(n.name);if(this.changes.push(`column ${i}.${n.name}`),s.undoColumns.push(`ALTER TABLE ${t} DROP COLUMN IF EXISTS ${o}`),n.identity){this.input.hasRows(b(this.matches.get(i).from))?this.refuse(`column ${i}.${n.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"):s.tx.push(`ALTER TABLE ${t} ADD COLUMN ${this.columnSql(n)}`);return}if(n.generated){n.generated.stored&&this.input.hasRows(b(this.matches.get(i).from))?this.refuse(`column ${i}.${n.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"):s.tx.push(`ALTER TABLE ${t} ADD COLUMN ${this.columnSql(n)}`);return}if(this.input.hasRows(b(this.matches.get(i).from))&&this.checkedDomain(n.type)){this.refuse(`column ${i}.${n.name} is of ${n.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(!(n.default!==void 0&&wt(n.default))&&(n.nullable||n.default!==void 0)){s.tx.push(`ALTER TABLE ${t} ADD COLUMN ${this.columnSql(n)}`);return}if(!n.nullable&&n.default===void 0&&n.fill===void 0){this.refuse(`column ${i}.${n.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}s.tx.push(`ALTER TABLE ${t} ADD COLUMN ${o} ${this.typeSql(n.type)}`),n.default!==void 0?(s.tx.push(`ALTER TABLE ${t} ALTER COLUMN ${o} SET DEFAULT ${n.default}`),this.backfills.push({kind:"backfill",table:t,key:this.keyOf(e),set:`${o} = ${n.default}`,where:`${o} IS NULL`,why:`${i}.${n.name} takes its default`})):this.fill(e,t,n.name,n.fill,s),n.nullable||this.notNull(e,t,n.name,s)}fill(e,t,n,s,i){let o=b(e),c=L(e.schema,X(this.n,"fill",_e(e,n))),r=T(X(this.n,"fill",n)),l=T(n),h=this.where(e),N=J(s,se(h.cols));i.tx.push(`CREATE OR REPLACE FUNCTION ${c}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
86
+ BEGIN
87
+ IF NEW.${l} IS NULL THEN
88
+ NEW.${l} := (SELECT (
89
+ ${N}
90
+ ) FROM (SELECT (NEW).*) AS ${T(h.table)});
91
+ END IF;
92
+ RETURN NEW;
93
+ END $palgres$`,`CREATE TRIGGER ${r} BEFORE INSERT OR UPDATE ON ${t} FOR EACH ROW EXECUTE FUNCTION ${c}()`);let u=[`DROP TRIGGER IF EXISTS ${r} ON ${t}`,`DROP FUNCTION IF EXISTS ${c}()`];i.undo.push(...u),i.complete.unshift(...u),this.backfills.push({kind:"backfill",table:t,key:this.keyOf(e),set:`${l} = (
94
+ ${N}
95
+ )`,where:`${l} IS NULL`,why:`${o}.${n} is filled`})}relaxNotNull(e,t,n,s){let i=T(n);s.tx.push(`ALTER TABLE ${t} ALTER COLUMN ${i} DROP NOT NULL`);let o=T(X(this.n,"nn",n)),c=`EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${A(o.slice(1,-1))} AND conrelid = ${A(t)}::regclass`;this.undoOnline.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF NOT ${c}) THEN ALTER TABLE ${t} ADD CONSTRAINT ${o} CHECK (${i} IS NOT NULL) NOT VALID; END IF; END $palgres$`],why:`${e}.${n} NOT NULL again`},{kind:"statement",sql:`DO $palgres$ BEGIN IF ${c}) THEN ALTER TABLE ${t} VALIDATE CONSTRAINT ${o}; END IF; EXCEPTION WHEN check_violation THEN ALTER TABLE ${t} DROP CONSTRAINT ${o}; RAISE WARNING 'palgres: % stays nullable: NULL was written since', ${A(`${e}.${n}`)}; END $palgres$`,why:`${e}.${n} has no NULL`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF ${c} AND convalidated) THEN ALTER TABLE ${t} ALTER COLUMN ${i} SET NOT NULL; END IF; END $palgres$`,`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${o}`],why:`${e}.${n} is NOT NULL`})}notNull(e,t,n,s){let i=T(X(this.n,"nn",n)),o=T(n);this.online.push({kind:"tx",sql:[`ALTER TABLE ${t} ADD CONSTRAINT ${i} CHECK (${o} IS NOT NULL) NOT VALID`],why:`${b(e)}.${n} is held NOT NULL`}),s.undo.push(`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${i}`),this.online.push({kind:"statement",sql:`ALTER TABLE ${t} VALIDATE CONSTRAINT ${i}`,why:`${b(e)}.${n} has no NULL`}),this.settle.push({kind:"tx",sql:[`ALTER TABLE ${t} ALTER COLUMN ${o} SET NOT NULL`,`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${i}`],why:`${b(e)}.${n} is NOT NULL`})}alterColumn(e,t,n,s,i){let o=b(e),c=T(n.name);if(n.nullable&&!s.nullable){let r=s.fill??s.default;r===void 0?this.refuse(`column ${o}.${s.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 ${o}.${s.name} becomes NOT NULL`),this.fill(e,t,n.name,r,i),this.notNull(e,t,n.name,i),i.undo.push(`ALTER TABLE ${t} ALTER COLUMN ${c} DROP NOT NULL`))}if(!n.nullable&&s.nullable&&(this.changes.push(`column ${o}.${s.name} becomes nullable`),this.relaxNotNull(o,t,n.name,i)),(n.default??null)!==(s.default??null)){let r=this.sequenceRenamed(n,s);r!==void 0?(this.changes.push(`sequence ${r.from} becomes ${r.to} (at complete)`),i.complete.push(`ALTER SEQUENCE ${r.from} RENAME TO ${T(r.to)}`)):s.default!==void 0?(this.changes.push(`column ${o}.${s.name} defaults to ${s.default}`),i.tx.push(`ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${s.default}`),i.undo.push(n.default!==void 0?`ALTER TABLE ${t} ALTER COLUMN ${c} SET DEFAULT ${n.default}`:`ALTER TABLE ${t} ALTER COLUMN ${c} DROP DEFAULT`)):(this.changes.push(`column ${o}.${s.name} loses its default (at complete)`),i.complete.push(`ALTER TABLE ${t} ALTER COLUMN ${T(s.name)} DROP DEFAULT`))}(n.identity??null)!==(s.identity??null)&&this.refuse(`column ${o}.${s.name} changes identity`,"an identity cannot change while both versions write; add a new column"),this.regenerate(e,t,n,s,i)}regenerate(e,t,n,s,i){let o=b(e),c=T(n.name),r=n.generated,l=s.generated;if(!(!r&&!l)&&!(r&&l&&r.expr===l.expr&&r.stored===l.stored)){if(!r&&l){this.refuse(`column ${o}.${s.name} becomes a generated column`,"Postgres cannot make a column generated: add a new generated column and ignore the old one");return}if(r&&!l){if(!r.stored){this.refuse(`column ${o}.${s.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 ${o}.${s.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 h=L(e.schema,X(this.n,"gen",_e(e,n.name))),N=T(X(this.n,"gen",n.name)),u=this.where(e);i.tx.push(`ALTER TABLE ${t} ALTER COLUMN ${c} DROP EXPRESSION IF EXISTS`,`CREATE OR REPLACE FUNCTION ${h}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
96
+ BEGIN
97
+ IF position(${A(de(this.n,""))} in replace(current_setting('search_path'), '"', '')) <> 1 THEN
98
+ NEW.${c} := (SELECT (
99
+ ${J(r.expr,se(u.cols))}
100
+ ) FROM (SELECT (NEW).*) AS ${T(u.table)});
101
+ END IF;
102
+ RETURN NEW;
103
+ END $palgres$`,`CREATE TRIGGER ${N} BEFORE INSERT OR UPDATE ON ${t} FOR EACH ROW EXECUTE FUNCTION ${h}()`),i.complete.unshift(`DROP TRIGGER IF EXISTS ${N} ON ${t}`,`DROP FUNCTION IF EXISTS ${h}()`);return}if(r.stored!==l.stored){this.refuse(`column ${o}.${s.name} changes between stored and virtual`,"Postgres would compute every row again: add a new generated column and ignore the old one");return}if(l.stored&&this.input.hasRows(b(this.matches.get(o).from))){this.refuse(`column ${o}.${s.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 ${o}.${s.name} is generated as ${l.expr}`),i.tx.push(`ALTER TABLE ${t} ALTER COLUMN ${c} SET EXPRESSION AS (${l.expr})`),i.undo.push(`ALTER TABLE ${t} ALTER COLUMN ${c} SET EXPRESSION AS (${r.expr})`)}}retype(e,t,n,s,i){let o=e.to,c=b(o),r=In(s.from.type,s.to.type),l=this.to.tables.flatMap($=>$.foreignKeys.filter(O=>O.refSchema===o.schema&&O.refTable===o.name&&O.refColumns.includes(n)).map(O=>({o:$,f:O}))),h=[...o.checks.filter($=>ne($.expr,n)).map($=>`check ${$.name}`),...o.policies.filter($=>ne(`${$.using??""} ${$.withCheck??""}`,n)).map($=>`policy ${$.name}`),...o.indexes.filter($=>$.keys.some(O=>"expr"in O&&ne(O.expr,n))||$.where!==void 0&&ne($.where,n)).map($=>`index ${$.name}`),...o.primaryKey.includes(n)&&!r?["the primary key"]:[],...r?[]:l.map(({o:$,f:O})=>`foreign key ${b($)}.${O.name}`)];if(h.length>0){let $=!r&&(o.primaryKey.includes(n)||l.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 ${c}.${n} changes type from ${s.from.type} to ${s.to.type}, and ${h.join(", ")} use it`,`add a column of the new type with .fillWith("${n}::${s.to.type}"), move them to it, and ignore the old one${$}`);return}let N=l.flatMap(({o:$,f:O})=>O.columns.filter((k,_)=>O.refColumns[_]===n&&Ne($.columns.find(x=>x.name===k)?.type??"")!==Ne(s.to.type)).map(k=>`${b($)}.${k}`));if(N.length>0){this.refuse(`column ${c}.${n} becomes ${s.to.type}, and ${N.join(", ")}, which reference it, are not of its kind`,`change their type with it in this deploy, to ${s.to.type}`);return}if((s.from.identity??null)!==(s.to.identity??null)){this.refuse(`column ${c}.${n} changes identity`,"an identity cannot change while both versions write; add a new column");return}let u=this.conversion(s.from.type,s.to.type);if("refused"in u){this.refuse(`column ${c}.${n} changes type from ${s.from.type} to ${s.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(s.from.nullable&&!s.to.nullable){this.refuse(`column ${c}.${n} 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 g=ze(s.from.type,s.to.type);this.changes.push(`column ${c}.${n} changes type from ${s.from.type} to ${s.to.type}${g?"":" (a value that does not convert is kept in the old column at complete)"}`);let f=T(s.from.name),R=T(s.shadow),I=L(o.schema,X(this.n,"sync",_e(o,n))),p=T(X(this.n,"sync",n)),m=new Map([...e.cols].map(([$,O])=>[$,e.retyped.get($)?.from.name??O])),S=g||s.to.fill===void 0?void 0:J(s.to.fill,se(m)),w=$=>{let O=`NEW.${R} := ${u.on(`NEW.${f}`)};`;if(g)return`${$}${O}`;let k=x=>["BEGIN",` ${x}`,`EXCEPTION WHEN ${Ln} THEN`,` NEW.${R} := NULL;`,"END;"];return[...k(O),...S===void 0?[]:[`IF NEW.${R} IS NULL AND NEW.${f} IS NOT NULL THEN`,...k(`NEW.${R} := (SELECT (
104
+ ${S}
105
+ ) FROM (SELECT (NEW).*) AS ${T(e.physical)});`).map(x=>` ${x}`),"END IF;"]].map(x=>`${$}${x}`).join(`
106
+ `)};i.tx.push(`ALTER TABLE ${t} ADD COLUMN ${R} ${this.typeSql(s.to.type)}`,`CREATE OR REPLACE FUNCTION ${I}() RETURNS trigger LANGUAGE plpgsql AS $palgres$
107
+ DECLARE
108
+ next boolean := position(${A(de(this.n,""))} in replace(current_setting('search_path'), '"', '')) = 1;
109
+ BEGIN
110
+ -- The writer's own column, taken across \u2014 on an update only when it
111
+ -- changed: a value the other version wrote is not cast back over (a cast
112
+ -- may lose: a shorter varchar, an integer).
113
+ IF TG_OP = 'INSERT' THEN
114
+ IF next${s.from.identity?` AND NEW.${R} IS NOT NULL`:""} THEN
115
+ NEW.${f} := ${u.back(`NEW.${R}`)};${s.from.identity?`
116
+ ELSIF next THEN
117
+ -- An identity, which the new version gave none: the number the old
118
+ -- column was given, from the one sequence both versions number from.
119
+ NEW.${R} := ${u.on(`NEW.${f}`)};`:""}
120
+ ELSE
121
+ ${w(" ")}
122
+ END IF;
123
+ ELSIF next THEN
124
+ IF NEW.${R} IS DISTINCT FROM OLD.${R} THEN
125
+ NEW.${f} := ${u.back(`NEW.${R}`)};
126
+ END IF;
127
+ ELSIF NEW.${f} IS DISTINCT FROM OLD.${f} OR (NEW.${R} IS NULL AND NEW.${f} IS NOT NULL) THEN
128
+ -- the old version's write, or the backfill reaching a row
129
+ ${w(" ")}
130
+ END IF;
131
+ RETURN NEW;
132
+ END $palgres$`,`CREATE TRIGGER ${p} BEFORE INSERT OR UPDATE ON ${t} FOR EACH ROW EXECUTE FUNCTION ${I}()`),S!==void 0&&i.tx.push(`SELECT (
133
+ ${S}
134
+ ) FROM ${t} AS ${T(e.physical)} LIMIT 0`),s.to.default!==void 0&&i.tx.push(`ALTER TABLE ${t} ALTER COLUMN ${R} SET DEFAULT ${s.to.default}`),!s.from.nullable&&s.to.nullable&&this.relaxNotNull(c,t,s.from.name,i),i.undo.push(`DROP TRIGGER IF EXISTS ${p} ON ${t}`,`DROP FUNCTION IF EXISTS ${I}()`),i.undoColumns.push(`ALTER TABLE ${t} DROP COLUMN IF EXISTS ${R}`);let d=s.from.identity==="always"?R:f;this.backfills.push({kind:"backfill",table:t,key:this.keyOf(o),set:`${d} = ${d}`,where:`${R} IS NULL AND ${f} IS NOT NULL`,why:`${c}.${n} in its new type`}),i.complete.push(`DROP TRIGGER IF EXISTS ${p} ON ${t}`,`DROP FUNCTION IF EXISTS ${I}()`);for(let $ of Xt(s.to.default))i.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(${A($)}) AND refclassid = 'pg_catalog.pg_class'::regclass AND refobjid = ${A(t)}::regclass AND refobjsubid = (SELECT attnum FROM pg_catalog.pg_attribute WHERE attrelid = ${A(t)}::regclass AND attname = ${A(s.from.name)} AND NOT attisdropped) AND deptype = 'a') THEN ALTER SEQUENCE ${$} OWNED BY ${t}.${R}; END IF; END $palgres$`),Y(s.to.type)==="bigint"&&i.complete.push(`ALTER SEQUENCE IF EXISTS ${$} AS bigint`);if(i.names=!0,i.dropsColumns=!0,!g){this.keepUnconverted(e,t,n,s,i);return}if(s.to.nullable||this.notNull(o,t,s.shadow,i),s.to.identity){let $=s.to.identity==="always"?"ALWAYS":"BY DEFAULT";i.complete.push(`DO $palgres$
135
+ DECLARE
136
+ seq regclass := pg_catalog.pg_get_serial_sequence(${A(t)}, ${A(s.from.name)})::regclass;
137
+ seq_name text;
138
+ seq_step bigint;
139
+ seq_next bigint;
140
+ BEGIN
141
+ SELECT format('%I.%I', n.nspname, c.relname) INTO seq_name FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace WHERE c.oid = seq;
142
+ SELECT seqincrement INTO seq_step FROM pg_catalog.pg_sequence WHERE seqrelid = seq;
143
+ seq_next := nextval(seq);
144
+ ALTER TABLE ${t} 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)', ${A(t)}, ${A(s.shadow)}, seq_name, seq_next, seq_step);
146
+ END $palgres$`)}else i.complete.push(`ALTER TABLE ${t} DROP COLUMN ${f}`);i.complete.push(`ALTER TABLE ${t} RENAME COLUMN ${R} TO ${T(n)}`)}keepUnconverted(e,t,n,s,i){let o=e.to,c=b(o),r=T(s.from.name),l=X(this.n,"old",n),h=I=>I.includes(s.from.name);i.complete.push(...e.from.uniques.filter(I=>h(I.columns)).map(I=>`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T(I.name)}`),...e.from.foreignKeys.filter(I=>h(I.columns)).map(I=>`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T(I.name)}`),...e.from.indexes.filter(I=>h([...I.keys.flatMap(p=>"column"in p?[p.column]:[]),...I.include??[]])).map(I=>`DROP INDEX IF EXISTS ${L(o.schema,I.name)}`),`ALTER TABLE ${t} ALTER COLUMN ${r} DROP NOT NULL`,`ALTER TABLE ${t} ALTER COLUMN ${r} DROP DEFAULT`,`ALTER TABLE ${t} RENAME COLUMN ${r} TO ${T(l)}`,`ALTER TABLE ${t} RENAME COLUMN ${T(s.shadow)} TO ${T(n)}`);let N=L(o.schema,o.name),u=T(n),g=T(l),f=`(SELECT attnum FROM pg_catalog.pg_attribute WHERE attrelid = ${A(N)}::regclass AND attname = ${A(l)} AND NOT attisdropped)`,R=A(`column ${c}.${n}: values of it that did not become ${s.to.type} are kept in ${l}, outside the schema, and ${n} 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 ${N} WHERE ${u} IS NULL AND ${g} IS NOT NULL) THEN COMMENT ON COLUMN ${N}.${g} IS ${A(Bt)}; END IF; END IF; END $palgres$`,why:`${c}.${n}: whether every value became ${s.to.type}`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF pg_catalog.col_description(${A(N)}::regclass, ${f}) = ${A(Bt)} THEN ALTER TABLE ${N} DROP COLUMN ${g}; ELSIF ${f} IS NOT NULL THEN RAISE WARNING 'palgres: %', ${R}; END IF; END $palgres$`],why:`${c}.${n}: its values before, once converted`}),!s.to.nullable){let I=X(this.n,"nn",n),p=`EXISTS (SELECT 1 FROM pg_catalog.pg_constraint WHERE conname = ${A(I)} AND conrelid = ${A(N)}::regclass`;this.completeAfter.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF ${f} IS NULL AND NOT ${p}) THEN ALTER TABLE ${N} ADD CONSTRAINT ${T(I)} CHECK (${u} IS NOT NULL) NOT VALID; END IF; END $palgres$`],why:`${c}.${n} is held NOT NULL`},{kind:"statement",sql:`DO $palgres$ BEGIN IF ${p}) THEN ALTER TABLE ${N} VALIDATE CONSTRAINT ${T(I)}; END IF; END $palgres$`,why:`${c}.${n} has no NULL`},{kind:"tx",sql:[`DO $palgres$ BEGIN IF ${p} AND convalidated) THEN ALTER TABLE ${N} ALTER COLUMN ${u} SET NOT NULL; END IF; END $palgres$`,`ALTER TABLE ${N} DROP CONSTRAINT IF EXISTS ${T(I)}`],why:`${c}.${n} is NOT NULL`})}(this.guarded.retyped??=[]).push({schema:o.schema,table:o.name,column:n,kept:l,type:s.to.type,key:o.primaryKey})}checkedDomain(e){if(this.input.checkedDomain(this.typeSql(e))===!0)return!0;let t=Y(e).replace(/^public\./,""),n=i=>i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),s=new RegExp(String.raw`\bCREATE\s+DOMAIN\s+(?:"?public"?\.)?"?${n(t.replace(/^"|"$/g,""))}"?\s[\s\S]*\b(?:CHECK|NOT\s+NULL)\b`,"i");return this.to.raw.some(i=>s.test(i.sql))}conversion(e,t){let n=g=>/(\[\])*$/.exec(g)[0],s=g=>g.slice(0,g.length-n(g).length);if(n(e)!==n(t))return{refused:"one is an array and the other is not, or of another depth"};let i=n(e),o=g=>{let f=Y(s(g));return[...this.to.enums,...this.from.enums].find(R=>Ee(R.schema,R.name)===f||R.schema==="public"&&Ee(R.schema,R.name)===`public.${f}`)},c=g=>/^(text|citext|public\.citext|character varying(\(\d+\))?|character(\(\d+\))?)$/.test(Y(s(g))),r=g=>f=>`${f}::${this.typeSql(g)}`,l=o(e),h=o(t);if(l&&h){let g=(p,m)=>p.filter(S=>!m.includes(S)),f=g(l.values,h.values),R=g(h.values,l.values);if(f.length>0||R.length>0)return{refused:`the enums' labels differ (${[...f.map(p=>`-${p}`),...R.map(p=>`+${p}`)].join(", ")}), and a label one version writes the other's column cannot hold`};let I=p=>m=>`${m}::text${i}::${this.typeSql(p)}`;return{on:I(t),back:I(e)}}if(l||h)return c(l?t:e)?{on:r(t),back:r(e)}:{refused:`Postgres has no cast between an enum and ${l?t:e}`};let N=this.input.castable(this.typeSql(e),this.typeSql(t)),u=this.input.castable(this.typeSql(t),this.typeSql(e));return N===!1||u===!1?{refused:`Postgres has no cast from ${N===!1?e:t} to ${N===!1?t:e}`}:{on:r(t),back:r(e)}}constraints(e,t,n){let{to:s}=e,i=this.inNewNames(e.from),o=e.from,c=b(s),r=d=>d.some($=>e.retyped.has($)),l=d=>d.some($=>e.retyped.has($)),h=(d,$)=>r($)?X(this.n,"c",d):d,N=(d,$,O)=>{d!==$&&n.complete.push(O?`ALTER TABLE ${t} RENAME CONSTRAINT ${T(d)} TO ${T($)}`:`ALTER INDEX ${L(s.schema,d)} RENAME TO ${T($)}`)},u=(d,$,O,k)=>{let _=[],x=[];for(let H of $){let y=d.find(U=>U.name===H.name);y?(!k(y,H)||r(O(H)))&&(l(O(y))||x.push(y),_.push(H)):_.push(H)}for(let H of d)!$.some(y=>y.name===H.name)&&!l(O(H))&&x.push(H);return{added:_,gone:x}},g=(d,$)=>d.find(O=>O.name===$),f=d=>o.uniques.some($=>$.name===d)||o.indexes.some($=>$.name===d),R=u(i.uniques,s.uniques,d=>d.columns,(d,$)=>d.columns.join()===$.columns.join());this.renamedTwins(R,(d,$)=>d.columns.join()===$.columns.join()&&!r($.columns),(d,$)=>{this.changes.push(`unique ${c}.${d.name} is renamed ${$.name} (at complete)`),n.complete.push(`ALTER TABLE ${t} RENAME CONSTRAINT ${T(d.name)} TO ${T($.name)}`)});for(let d of R.gone)this.changes.push(`unique ${c}.${d.name} goes (at complete)`),n.complete.push(`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T(d.name)}`);for(let d of R.added){let $=f(d.name)?X(this.n,"c",d.name):h(d.name,d.columns),O=L(s.schema,$);this.changes.push(`unique ${c}.${d.name}`),this.online.push({kind:"statement",sql:`CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS ${T($)} ON ${t} (${ee(d.columns.map(k=>e.cols.get(k)))})`,why:`unique ${d.name}`}),this.settle.push({kind:"tx",sql:[`DO $palgres$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = ${A($)} AND conrelid = ${A(t)}::regclass) THEN ALTER TABLE ${t} ADD CONSTRAINT ${T($)} UNIQUE USING INDEX ${T($)}; END IF; END $palgres$`],why:`unique ${d.name}`}),n.undo.unshift(`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T($)}`,`DROP INDEX IF EXISTS ${O}`),N($,d.name,!0)}let I=u(i.checks,s.checks,d=>s.columns.filter($=>ne(d.expr,$.name)).map($=>$.name),(d,$)=>d.expr.trim()===$.expr.trim());for(let d of I.gone)this.changes.push(`check ${c}.${d.name} goes`),n.tx.push(`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T(d.name)}`),n.undo.push(`ALTER TABLE ${t} ADD CONSTRAINT ${T(d.name)} CHECK (${g(o.checks,d.name).expr}) NOT VALID`);for(let d of I.added)this.changes.push(`check ${c}.${d.name}`),n.tx.push(`ALTER TABLE ${t} ADD CONSTRAINT ${T(d.name)} CHECK (${J(d.expr,se(e.cols))}) NOT VALID`),this.online.push({kind:"statement",sql:`ALTER TABLE ${t} VALIDATE CONSTRAINT ${T(d.name)}`,why:`check ${d.name}`}),n.undo.unshift(`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T(d.name)}`);let p=u(i.foreignKeys,s.foreignKeys,d=>d.columns,(d,$)=>De(d)===De($)),m=d=>d.refColumns.some($=>this.matches.get(`${d.refSchema}.${d.refTable}`)?.retyped.has($)??!1);for(let d of s.foreignKeys){if(!m(d))continue;p.added.includes(d)||p.added.push(d);let $=i.foreignKeys.find(O=>O.name===d.name);$&&!p.gone.includes($)&&this.completeFks.push({kind:"tx",sql:[`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T($.name)}`],why:`foreign key ${d.name}, onto the old column`})}for(let d of p.gone)this.changes.push(`foreign key ${c}.${d.name} goes`),this.fkDrops.push({kind:"tx",sql:[`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T(d.name)}`],why:`foreign key ${d.name} goes`}),this.undoFksBack.push({kind:"tx",sql:[`ALTER TABLE ${t} ADD ${this.fkSqlOld(g(o.foreignKeys,d.name))} NOT VALID`],why:`foreign key ${d.name} again`});for(let d of p.added){let $=m(d)?X(this.n,"c",d.name):h(d.name,d.columns);this.changes.push(`foreign key ${c}.${d.name}${m(d)?" references the new column (the old one goes at complete)":""}`),this.lateFks.push({kind:"tx",sql:[`ALTER TABLE ${t} ADD ${this.fkSql({...d,name:$},e.cols)} NOT VALID`],why:`foreign key ${d.name}`}),this.lateFks.push({kind:"statement",sql:`ALTER TABLE ${t} VALIDATE CONSTRAINT ${T($)}`,why:`foreign key ${d.name}`}),this.undoFksGone.push({kind:"tx",sql:[`ALTER TABLE ${t} DROP CONSTRAINT IF EXISTS ${T($)}`],why:`foreign key ${d.name}`}),N($,d.name,!0)}for(let d of s.foreignKeys){let $=i.foreignKeys.find(O=>O.name===d.name);!$||De($)!==De(d)||r(d.columns)||m(d)||($.deferrable??!1)===(d.deferrable??!1)||(this.changes.push(`foreign key ${c}.${d.name} is ${d.deferrable?"":"not "}deferrable (in the catalog, no row read again; ${c} locked a moment, the lock given way to while others hold it and tried again)`),n.tx.push(`ALTER TABLE ${t} ALTER CONSTRAINT ${T(d.name)} ${d.deferrable?"DEFERRABLE":"NOT DEFERRABLE"}`),n.undo.push(`ALTER TABLE ${t} ALTER CONSTRAINT ${T(d.name)} ${d.deferrable?"NOT DEFERRABLE":"DEFERRABLE"}`))}if(s.primaryKey.some(d=>e.retyped.has(d))){let d=X(this.n,"pk",s.name),$=`${s.name}_pkey`;this.changes.push(`the primary key of ${c} 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 ${T(d)} ON ${t} (${ee(s.primaryKey.map(O=>e.cols.get(O)))})`,why:`the primary key of ${c}, on the new column`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${L(s.schema,d)}`,why:`the primary key of ${c}, on the new column`}),n.complete.push(`ALTER TABLE ${t} ADD PRIMARY KEY USING INDEX ${T(d)}`),Buffer.byteLength($)<=63&&n.complete.push(`DO $palgres$ BEGIN IF to_regclass(${A(L(s.schema,$))}) IS NULL THEN ALTER INDEX ${L(s.schema,d)} RENAME TO ${T($)}; END IF; END $palgres$`)}let S=d=>[...d.keys.flatMap($=>"column"in $?[$.column]:[]),...d.include??[]],w=u(i.indexes,s.indexes,S,(d,$)=>Fe(d)===Fe($));this.renamedTwins(w,(d,$)=>Fe(d)===Fe($)&&!r(S($)),(d,$)=>{this.changes.push(`index ${c}.${d.name} is renamed ${$.name} (at complete)`),n.complete.push(`ALTER INDEX ${L(s.schema,d.name)} RENAME TO ${T($.name)}`)});for(let d of w.added){if(!d.unique)continue;let $=S(d).slice(0,d.keys.length),O=w.gone.find(_=>_.unique&&S(_).slice(0,_.keys.length).join()===$.join());if(!O)continue;let k=this.to.tables.flatMap(_=>_.foreignKeys.filter(x=>x.refSchema===s.schema&&x.refTable===s.name&&x.refColumns.join()===$.join()).map(x=>`${b(_)}.${x.name}`));k.length>0&&this.refuse(`unique index ${c}.${O.name} is built again as ${d.name}, and foreign key ${k.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 d of w.gone)w.added.some($=>$.name===d.name)?(this.changes.push(`index ${c}.${d.name} is built again (the old one goes at complete)`),n.complete.push(`DROP INDEX IF EXISTS ${L(s.schema,d.name)}`)):(this.changes.push(`index ${c}.${d.name} goes (at complete)`),this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${L(s.schema,d.name)}`,why:`index ${d.name}`}));for(let d of w.added){let $=f(d.name)?X(this.n,"i",d.name):h(d.name,S(d));this.changes.push(`index ${c}.${d.name}`),this.online.push({kind:"statement",sql:this.indexSql(s.schema,e.physical,{...d,name:$},e.cols,!0),why:`index ${d.name}`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${L(s.schema,$)}`,why:`index ${d.name}`}),N($,d.name,!1)}}renamedTwins(e,t,n){for(let s of[...e.gone]){let i=e.added.find(o=>o.name!==s.name&&t(s,o)&&!e.gone.some(c=>c.name===o.name));i&&(e.gone.splice(e.gone.indexOf(s),1),e.added.splice(e.added.indexOf(i),1),n(s,i))}}indexSql(e,t,n,s,i){let o=se(s),c=n.keys.map(l=>{let h="column"in l?T(s.get(l.column)??l.column):`(${J(l.expr,o)})`;return l.desc&&(h+=" DESC"),l.nulls&&(h+=` NULLS ${l.nulls.toUpperCase()}`),h}),r=`CREATE ${n.unique?"UNIQUE ":""}INDEX ${i?"CONCURRENTLY ":""}IF NOT EXISTS ${T(n.name)} ON ${L(e,t)}`;return n.method&&n.method!=="btree"&&(r+=` USING ${n.method}`),r+=` (${c.join(", ")})`,n.include?.length&&(r+=` INCLUDE (${ee(n.include.map(l=>s.get(l)??l))})`),n.where!==void 0&&(r+=` WHERE ${J(n.where,o)}`),r}fkSql(e,t){let n=this.to.tables.find(i=>i.schema===e.refSchema&&i.name===e.refTable),s=n?this.where(n):{table:e.refTable,cols:new Map};return`CONSTRAINT ${T(e.name)} FOREIGN KEY (${ee(e.columns.map(i=>t.get(i)??i))}) REFERENCES ${L(e.refSchema,s.table)} (${ee(e.refColumns.map(i=>s.cols.get(i)??i))})${e.match==="full"?" MATCH FULL":""} ON DELETE ${e.onDelete.toUpperCase()} ON UPDATE ${e.onUpdate.toUpperCase()}${e.deferrable?" DEFERRABLE":""}`}fkSqlOld(e){return`CONSTRAINT ${T(e.name)} FOREIGN KEY (${ee(e.columns)}) REFERENCES ${L(e.refSchema,e.refTable)} (${ee(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((t,n)=>t.gen-n.gen)}search(e,t){let n=b(e),s=e.search,i=t?.from.search;if(s===void 0){t&&this.searchGone(t.from,t.physical);return}let o=mt(`table ${n}`,e,s);if(o.length>0){this.refusals.push(...o);return}let c=e.columns.find(S=>S.name===e.primaryKey[0]),r=this.generations(t?b(t.from):n),l=r.filter(S=>S.status!=="retired"),h=l.find(S=>S.status==="active"),N=l.at(-1),u=N===void 0?[]:Ie(N,s)?l:h?[h]:[],g=N===void 0?"active":Ie(N,s)||h!==void 0&&Ie(h,s)?void 0:"filling";if(t){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!==t.from.name&&this.refuse(`table ${e.schema}.${t.from.name} is renamed ${e.name} while it declares search`,S);let w=new Set;for(let d of new Set([c.name,...s.from])){let $=d===c.name?"search keeps each row's vector by it":"search reads it";if(t.retyped.has(d))this.refuse(`column ${n}.${d} changes type, and ${$}`,S);else if((t.cols.get(d)??d)!==d)this.refuse(`column ${n}.${d} ${t.parked.has(d)?"takes a name another column leaves in this deploy":`is renamed from ${t.cols.get(d)}`}, and ${$}`,S);else continue;w.add(t.retyped.get(d)?.from.name??t.cols.get(d)??d)}for(let d of u)for(let $ of d.from){if(w.has($))continue;e.columns.some(k=>k.name===$)&&!t.retyped.has($)&&(t.cols.get($)??$)===$||this.refuse(`column ${n}.${$} goes or changes, and the vectors that serve search of ${n} now (generation ${d.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:t?t.physical:e.name},R=L(f.schema,f.name);if(g!==void 0){let S=(r.at(-1)?.gen??0)+1;this.changes.push(g==="active"?`search of ${n}: its rows are embedded with ${s.model} (${s.dimensions} dimensions) in the background; found by their words until then`:`search of ${n}: every row is embedded again with ${s.model} (${s.dimensions} dimensions) in the background; the vectors there serve until the new ones are complete`),this.searchStart.push({kind:"tx",sql:Pt({table:f,gen:S,search:s,status:g,pk:{name:c.name,type:this.typeSql(c.type)},roles:this.input.roles,types:this.input.vectorSchema??"public"}),why:`search of ${n}: generation ${S}`}),t&&this.searchStart.push({kind:"statement",sql:qt(f,S,c.name),why:`search of ${n}: its rows queued`}),this.undoSearch.push({kind:"tx",sql:Ce(f,S),why:`search of ${n}: generation ${S}`})}if(i!==void 0&&i.staleness!==s.staleness&&u.length>0){this.changes.push(`search of ${n}: a changed row's old vector ${s.staleness==="null"?"goes":"stays"} until the row is embedded again`);for(let S of u)this.searchStart.push({kind:"tx",sql:be({table:f,gen:S.gen,from:S.from,staleness:s.staleness},!0),why:`search of ${n}: generation ${S.gen}'s triggers`}),this.undoSearch.push({kind:"tx",sql:be({table:f,gen:S.gen,from:S.from,staleness:i.staleness},!0),why:`search of ${n}: generation ${S.gen}'s triggers`})}for(let S of r)u.includes(S)||(this.changes.push(`search of ${n}: generation ${S.gen}'s vectors, ${S.status==="retired"?"left behind":"never full"}, go (at complete)`),this.searchComplete.push({kind:"tx",sql:Ce(f,S.gen),why:`search of ${n}: generation ${S.gen}`}));let I=Le(f,s.from),p=i===void 0?void 0:Le(f,i.from);if(I===p)return;let m=S=>`CREATE INDEX ${S?"CONCURRENTLY ":""}IF NOT EXISTS ${T(I)} ON ${R} USING gin (${Mt(s.from)})`;i!==void 0&&this.changes.push(`search of ${n} reads ${s.from.join(", ")}`),t?(this.online.push({kind:"statement",sql:m(!0),why:`search of ${n}: its words`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${L(f.schema,I)}`,why:`search of ${n}: its words`})):this.creates.push(m(!1)),p!==void 0&&this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${L(f.schema,p)}`,why:`search of ${n}: the words it read`})}searchGone(e,t){let n=this.generations(b(e));if(e.search===void 0&&n.length===0)return;let s={schema:e.schema,name:t},i=b(e);this.changes.push(`search of ${i} goes (at complete)`);for(let o of n)this.searchComplete.push({kind:"tx",sql:Ce(s,o.gen),why:`search of ${i}: generation ${o.gen}`});e.search!==void 0&&this.searchComplete.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${L(s.schema,Le(s,e.search.from))}`,why:`search of ${i}: the words it read`})}compileAccess(){if(this.to.access!==void 0)try{let e=yt(this.to,{authenticated:this.input.roles.authenticated,service:this.input.roles.service,visitor:this.input.roles.anon},(this.input.from?.access?.names??[]).map(t=>({name:t.view,type:t.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=Rt(e,this.to.access.text)}catch(e){if(!(e instanceof ht))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,t=this.fromRecorded;if(!e&&!t){for(let E of this.accessPolicies){let C=E.to??E.from;E.to&&this.refuse(`policy ${b(E.table)}.${C.name} reads the access schema`,"the schema declares none: give the database one (db.access)")}return}let n=T("access"),s={authenticated:this.input.roles.authenticated,service:this.input.roles.service,visitor:this.input.roles.anon},i=e?.digest!==t?.digest;if(e&&this.to.access){let E=gt(ut(this.to.access.text));for(let C of e.tables){let P=this.to.tables.find(F=>F.schema===C.schema&&F.name===C.name);if(!P)continue;let q=this.from.tables.find(F=>F.schema===P.schema&&F.name===(P.renamedFrom??P.name)),v="rename or retype in this deploy, and have the access schema read it in the next";q&&P.renamedFrom!==void 0&&P.renamedFrom!==P.name&&this.refuse(`the access schema reads ${b(P)}, renamed in this deploy`,v);let G=new Set([C.key,...Nt(E).filter(F=>F.type===C.type).map(F=>F.column)]);for(let F of P.columns){if(!G.has(F.name)||!q)continue;let V=q.columns.find(j=>j.name===(F.renamedFrom??F.name));V&&(F.renamedFrom!==void 0&&F.renamedFrom!==F.name?this.refuse(`the access schema reads ${b(P)}.${F.name}, renamed in this deploy`,v):Y(V.type)!==Y(F.type)&&this.refuse(`the access schema reads ${b(P)}.${F.name}, whose type changes in this deploy`,v))}}}let o=`(SELECT coalesce(pg_catalog.current_setting('palgres.version', true), '') = ${A(String(this.input.next))})`,c=(E,C,P,q)=>{let v=`CREATE POLICY ${T(C.name)} ON ${E} AS ${C.restrictive?"RESTRICTIVE":"PERMISSIVE"} FOR ${C.for.toUpperCase()} TO ${this.policyRoles(C,E)}`;return P!==void 0&&(v+=` USING (${P})`),q!==void 0&&(v+=` WITH CHECK (${q})`),v},r=(E,C)=>`DROP POLICY IF EXISTS ${T(C)} ON ${E}`,l=(E,C)=>C===void 0?void 0:E.restrictive?`(NOT ${o} OR (${C}))`:`(${o} AND (${C}))`,h=(E,C)=>C===void 0?void 0:E.restrictive?`(${o} OR (${C}))`:`(NOT ${o} AND (${C}))`,N=E=>`palgres_was_${Yt("sha256").update(E).digest("hex").slice(0,24)}`,u=[],g=[],f=[];for(let E of this.accessPolicies){let C=b(E.table);if(E.to&&(ae(E.to.using)||ae(E.to.withCheck))){let G=At([E.to.using,E.to.withCheck],E.table,this.toAccess),F=G!==null&&G.length===0,V=E.to.to.length===0?["public"]:E.to.to.filter(j=>le[j]!=="authenticated"&&le[j]!=="service"&&!(F&&le[j]==="anon"));if(V.length>0){let j=V.every(Tn=>le[Tn]==="anon")&&G!==null;this.refuse(`policy ${C}.${E.to.name} reads the access schema and is for ${V.join(", ")}`,j?`nothing opens ${G.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 P=(G,F,V)=>{if(G===void 0||V===void 0)return;let j=Ot(V,E.table,F);if("refused"in j){F===e?this.refuse(`policy ${C}.${G.name} reads the access schema`,j.refused):this.refuse(`policy ${C}.${G.name} of the version in force reads an access schema the database does not record (${j.refused})`,"nothing is changed: what the policy says could not be kept, or put back");return}return j.sql},q={using:P(E.to,e,E.to?.using),check:P(E.to,e,E.to?.withCheck)},v={using:P(E.from,t,E.from?.using),check:P(E.from,t,E.from?.withCheck)};if(E.to&&E.from){let G=F=>JSON.stringify([F.for,[...F.to].sort(),F.restrictive??!1,F.using===void 0,F.withCheck===void 0]);if(G(E.to)===G(E.from)&&q.using===v.using&&q.check===v.check)continue;if(this.changes.push(`policy ${C}.${E.to.name} changes`),g.push(r(E.q,E.to.name),c(E.q,E.to,q.using,q.check)),G(E.to)===G(E.from)){let F=(V,j)=>V===void 0||j===void 0?V:`CASE WHEN ${o} THEN (${V}) ELSE (${j}) END`;u.push(r(E.q,E.to.name),c(E.q,E.to,F(q.using,v.using),F(q.check,v.check))),f.push(r(E.q,E.to.name),c(E.q,E.from,v.using,v.check))}else{let F=N(E.from.name);u.push(r(E.q,E.to.name),r(E.q,F),c(E.q,E.to,l(E.to,q.using),l(E.to,q.check)),c(E.q,{...E.from,name:F},h(E.from,v.using),h(E.from,v.check))),g.unshift(r(E.q,F)),f.push(r(E.q,F),r(E.q,E.to.name),c(E.q,E.from,v.using,v.check))}}else if(E.to)this.changes.push(`policy ${C}.${E.to.name}`),u.push(r(E.q,E.to.name),c(E.q,E.to,l(E.to,q.using),l(E.to,q.check))),g.push(r(E.q,E.to.name),c(E.q,E.to,q.using,q.check)),f.push(r(E.q,E.to.name));else if(E.from){this.changes.push(`policy ${C}.${E.from.name} goes`);let G=[r(E.q,E.from.name),c(E.q,E.from,v.using,v.check)];u.push(r(E.q,E.from.name),c(E.q,E.from,h(E.from,v.using),h(E.from,v.check))),g.push(r(E.q,E.from.name)),f.push(...G)}}if(!i&&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}i&&this.changes.push(e?`access schema ${e.digest}${t?` in place of ${t.digest}`:""}`:`access schema ${t?.digest} goes`);let R=new Set((e?.stored??[]).map(E=>E.join("\0"))),I=(t?.stored??[]).filter(E=>!R.has(E.join("\0"))),p=I.map(E=>`(${E.map(A).join(", ")})`).join(", ");I.length>0&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
147
+ DECLARE n bigint;
148
+ BEGIN
149
+ IF pg_catalog.to_regclass('access.relationships') IS NULL THEN RETURN; END IF;
150
+ SELECT count(*) INTO n FROM ${n}.relationships r WHERE (r.object_type, r.relation, ${Ge("r")}) IN (${p}) AND ${Et("r")};
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', ${A(I.map(E=>`${E[0]}.${E[1]}`).join(", "))}, n;
153
+ END IF;
154
+ END $guard$`],why:"no relationship is left without its relation"}),e&&!t&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
155
+ DECLARE d text;
156
+ BEGIN
157
+ IF pg_catalog.to_regclass('access.schemas') IS NULL THEN RETURN; END IF;
158
+ SELECT digest INTO d FROM ${n}.schemas WHERE active AND digest <> ${A(e.digest)} LIMIT 1;
159
+ IF d IS NOT NULL THEN
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
+ END IF;
162
+ END $guard$`],why:"no access schema is in force that this app did not migrate"});let m=(E,C)=>E.type===C.type&&E.schema===C.schema&&E.name===C.name&&E.key===C.key,S=(e?.tables??[]).filter(E=>!(t?.tables??[]).some(C=>m(C,E))),w=S.map(E=>A(E.type)).join(", ");S.length>0&&this.accessGuard.push({kind:"tx",sql:[`DO $guard$
163
+ DECLARE n bigint;
164
+ BEGIN
165
+ IF pg_catalog.to_regclass('access.relationships') IS NULL THEN RETURN; END IF;
166
+ EXECUTE ${A(`SELECT count(*) FROM ${n}.relationships WHERE object_type IN (${w}) OR subject_type IN (${w})`)} INTO n;
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, ${A(S.map(E=>E.type).join(", "))};
169
+ END IF;
170
+ END $guard$`],why:"no relationship names a row it was not given on"});let d=`access_binding_${this.input.next}`,$=S.length>0?[`DROP TRIGGER IF EXISTS ${T(d)} ON ${n}.relationships`,`CREATE TRIGGER ${T(d)} BEFORE INSERT OR UPDATE ON ${n}.relationships FOR EACH ROW EXECUTE FUNCTION ${n}.binding_guard(${[String(this.input.next),...S.map(E=>E.type)].map(A).join(", ")})`]:[],O=S.length>0?[`DROP TRIGGER IF EXISTS ${T(d)} ON ${n}.relationships`]:[],k=i?(this.toAccess?.kept??[]).filter(E=>!(t?.kept??[]).some(C=>C.type===E.type&&C.relation===E.relation&&C.depth<=E.depth)):[],_=`access_nesting_${this.input.next}`,x=k.length>0?[`DROP TRIGGER IF EXISTS ${T(_)} ON ${n}.relationships`,`CREATE TRIGGER ${T(_)} BEFORE INSERT OR UPDATE ON ${n}.relationships FOR EACH ROW EXECUTE FUNCTION ${n}.nest_guard(${[String(this.input.next),...k.flatMap(E=>[E.type,E.relation])].map(A).join(", ")})`]:[],H=k.length>0?[`DROP TRIGGER IF EXISTS ${T(_)} ON ${n}.relationships`]:[],y=i&&this.toAccess?[...Tt(s),...this.toAccess.build,...this.toAccess.watch,...this.toAccess.open]:this.toAccess?[...this.toAccess.open]:[],U=this.toAccess?this.toAccess.recheck:[];y.length+u.length+$.length+x.length+U.length>0&&this.accessStart.push({kind:"tx",sql:[...y,...$,...x,...u,...U],why:"the access schema, beside the one in force"});let M=[...O,...H,...g];if(i&&this.toAccess&&e){M.push($t(),...this.toAccess.point,...this.toAccess.record);for(let E of t?.names??[])e.names.some(C=>C.view===E.view)||M.push(`DROP VIEW IF EXISTS ${n}.${T(E.view)}`)}if(i&&t){I.length>0&&M.push("SELECT pg_catalog.set_config('access.actor', 'access: schema changed', true)",`DELETE FROM ${n}.relationships r WHERE (r.object_type, r.relation, ${Ge("r")}) IN (${p})`,"SELECT pg_catalog.set_config('access.actor', '', true)");for(let E of t.tables)if(!e?.tables.some(C=>C.schema===E.schema&&C.name===E.name)&&this.to.tables.some(C=>C.schema===E.schema&&C.name===E.name))for(let C of[...Be,Oe])M.push(`DROP TRIGGER IF EXISTS ${T(C)} ON ${L(E.schema,E.name)}`);if(!e){for(let E of t.names)M.push(`DROP VIEW IF EXISTS ${n}.${T(E.view)}`);M.push(...St())}M.push(...Xe(t.schema))}M.length>0&&this.accessComplete.push({kind:"tx",sql:M,why:"the access schema in force"});let B=[...O,...H,...f];if(i&&e){S.length>0&&B.push(`DO $undo$
171
+ BEGIN
172
+ IF pg_catalog.to_regclass('access.relationships') IS NULL THEN RETURN; END IF;
173
+ PERFORM pg_catalog.set_config('access.actor', 'access: rolled back', true);
174
+ EXECUTE ${A(`DELETE FROM ${n}.relationships WHERE object_type IN (${w}) OR subject_type IN (${w})`)};
175
+ PERFORM pg_catalog.set_config('access.actor', '', true);
176
+ END $undo$`),B.push(...Xe(e.schema));for(let E of e.tables)if(!t?.tables.some(C=>C.schema===E.schema&&C.name===E.name)&&this.from.tables.some(C=>C.schema===E.schema&&C.name===E.name))for(let C of Be)B.push(`DROP TRIGGER IF EXISTS ${T(C)} ON ${L(E.schema,E.name)}`);for(let E of e.tables)this.from.tables.some(C=>C.schema===E.schema&&C.name===E.name)&&B.push(`DROP TRIGGER IF EXISTS ${T(Oe)} ON ${L(E.schema,E.name)}`);for(let E of t?.nests??[])B.push(`CREATE OR REPLACE TRIGGER ${T(Oe)} AFTER INSERT OR UPDATE ON ${L(E.schema,E.table)} FOR EACH ROW EXECUTE FUNCTION ${T(ft)}.nest_rows(${E.args.map(A).join(", ")})`)}B.length>0&&this.accessUndo.push({kind:"tx",sql:B,why:"the access schema, as it was"})}policyRoles(e,t){let n=new Set;for(let s of e.to){if(s.startsWith("role:")&&s.length>5){n.add(T(s.slice(5)));continue}let i=le[s];if(!i){this.refuse(`policy ${t}.${e.name} is for role ${s}`,`a policy is for ${Object.keys(le).join(", ")}`);continue}n.add(i==="public"?"PUBLIC":T(this.input.roles[i]))}return[...n].join(", ")}policySql(e,t,n){let s=se(n),i=`CREATE POLICY ${T(t.name)} ON ${e} AS ${t.restrictive?"RESTRICTIVE":"PERMISSIVE"} FOR ${t.for.toUpperCase()} TO ${this.policyRoles(t,e)}`;return t.using!==void 0&&(i+=` USING (${J(t.using,s)})`),t.withCheck!==void 0&&(i+=` WITH CHECK (${J(t.withCheck,s)})`),i}policies(e,t,n){let{to:s}=e,i=this.inNewNames(e.from),o=b(s),c=g=>JSON.stringify([g.for,[...new Set(g.to.map(f=>le[f]??f))].sort(),g.using??null,g.withCheck??null,g.restrictive??!1]),r=g=>e.from.policies.find(f=>f.name===g),l=g=>g!==void 0&&(ae(g.using)||ae(g.withCheck)),h=s.policies.some(l)||i.policies.some(l),N=se(e.cols).size>0,u=g=>({...g,...g.using!==void 0?{using:J(g.using,se(e.cols))}:{},...g.withCheck!==void 0?{withCheck:J(g.withCheck,se(e.cols))}:{}});for(let g of s.policies){let f=i.policies.find(R=>R.name===g.name);if(l(g)||l(f)){this.accessPolicies.push({q:t,table:s,to:g,...f?{from:r(g.name)}:{}});continue}if(!(f&&c(f)===c(g))){if(h){N&&this.refuse(`policy ${o}.${g.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:t,table:s,to:u(g),...f?{from:r(g.name)}:{}});continue}this.readsOthersRenamed(s,g,o)||(this.changes.push(`policy ${o}.${g.name}${f?" changes":""}`),n.undo.push(`DROP POLICY IF EXISTS ${T(g.name)} ON ${t}`),f&&(n.tx.push(`DROP POLICY IF EXISTS ${T(g.name)} ON ${t}`),n.undo.push(this.policySql(t,r(g.name),Gt(e.from)))),n.tx.push(this.policySql(t,g,e.cols)))}}for(let g of i.policies)if(!s.policies.some(f=>f.name===g.name)){if(l(g)||h){this.accessPolicies.push({q:t,table:s,from:r(g.name)});continue}this.changes.push(`policy ${o}.${g.name} goes`),n.tx.push(`DROP POLICY IF EXISTS ${T(g.name)} ON ${t}`),n.undo.push(this.policySql(t,r(g.name),Gt(e.from)))}}readsOthersRenamed(e,t,n){let s=`${t.using??""} ${t.withCheck??""}`;for(let i of this.to.tables){if(i===e)continue;let o=this.from.tables.find(r=>r.schema===i.schema&&r.name===(i.renamedFrom??i.name));if(!o)continue;let c=[...i.name!==o.name&&ne(s,i.name)?[`${i.schema}.${i.name}`]:[],...ne(s,i.name)?i.columns.filter(r=>r.renamedFrom!==void 0&&r.renamedFrom!==r.name&&o.columns.some(l=>l.name===r.renamedFrom)&&ne(s,r.name)).map(r=>`${i.schema}.${i.name}.${r.name}`):[]];if(c.length>0)return this.refuse(`policy ${n}.${t.name} reads ${c.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 t of this.to.raw){if(!t.before)continue;let n=this.from.raw.find(s=>s.name===t.name);if(!(n&&n.sql.trim()===t.sql.trim())){if(n&&/^\s*CREATE\s+(?:DOMAIN|TYPE|SEQUENCE)\b/i.test(n.sql)){this.refuse(`raw ${t.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 ${t.name}${n?" changes":""}`),e&&this.creates.push("SET LOCAL check_function_bodies = off"),e=!1,this.creates.push(...this.rawApply(t,n)),!n&&t.drop!==void 0&&this.undoCreates.push(t.drop),n&&this.undoRawsBack.push(...this.rawApply(n,t))}}}rawApply(e,t){return!t||/^\s*CREATE\s+OR\s+REPLACE\b/i.test(e.sql)||t.drop===void 0?[e.sql]:[t.drop,e.sql]}rawUnits(){let e=this.to.raw.filter(l=>!l.before),t=l=>/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:MATERIALIZED\s+)?VIEW\b/i.test(l),n=this.namesAtComplete,s=this.dropsColumnsAtComplete,i=e.findIndex(l=>{let h=this.from.raw.find(N=>N.name===l.name);return t(l.sql)?s&&h!==void 0?!0:h===void 0?n:h.sql.trim()!==l.sql.trim():!1}),o=new Set,c=new Set,r=null;if(i>=0){let l=e.slice(i),h=u=>t(u)||/^\s*CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)\b/i.test(u)||Je.test(u),N=[];for(let u of[...this.from.raw].reverse()){if(u.before||u.drop===void 0)continue;let g=l.some(R=>R.name===u.name),f=!this.to.raw.some(R=>R.name===u.name);(g&&h(u.sql)||f&&t(u.sql))&&N.push(u.drop),f&&t(u.sql)&&c.add(u.name)}for(let u of l){let g=this.from.raw.find(f=>f.name===u.name);(!g||g.sql.trim()!==u.sql.trim())&&this.changes.push(`raw ${u.name}${g?" changes":""}`),o.add(u.name)}if(n){this.viewsAtComplete={drops:N,creates:l.map(u=>u.sql)};for(let u of l){let g=this.changes.findIndex(f=>f===`raw ${u.name}`||f===`raw ${u.name} changes`);g>=0&&(this.changes[g]+=" (at complete)")}}else{r={kind:"tx",sql:["SET LOCAL check_function_bodies = off",...N,...l.map(u=>u.sql)],why:`raw ${l[0].name} and what follows it, made again`};for(let u of[...l].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 g=l.some(R=>R.name===u.name),f=!this.to.raw.some(R=>R.name===u.name);(g&&h(u.sql)||f&&t(u.sql))&&this.undoRawsBack.push(u.sql)}}}for(let l of this.to.raw){if(l.before||(r!==null&&l.name===e[i].name&&this.raws.push(r),o.has(l.name)))continue;let h=this.from.raw.find(u=>u.name===l.name),N=jt(l.sql);if(!(h&&h.sql.trim()===l.sql.trim())){if(h&&N){this.refuse(`raw index ${l.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 ${l.name}${h?" changes":""}`),N)this.raws.push({kind:"statement",sql:N.create,why:`raw ${l.name}`}),this.undoIndexesGone.unshift({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${N.qualified(l,this.to)}`,why:`raw ${l.name}`});else{if(l.drop===void 0&&(Je.test(l.sql)||t(l.sql))){this.refuse(`raw ${l.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(l,h)],why:`raw ${l.name}`}),l.drop!==void 0&&this.undoRawsGone.unshift(l.drop),h&&this.undoRawsBack.push(...l.drop!==void 0?[h.sql]:this.rawApply(h,l))}}}for(let l of[...this.from.raw].reverse()){if(this.to.raw.some(N=>N.name===l.name))continue;if(c.has(l.name)){this.changes.push(`raw ${l.name} goes (with the views made again)`);continue}let h=jt(l.sql);if(!h){if(l.drop===void 0){this.refuse(`raw ${l.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 ${l.name} goes (at complete)`),Je.test(l.sql)?this.completeUnitDrops.push(l.drop):this.completeIndexes.push({kind:"tx",sql:[l.drop],why:`raw ${l.name}`});continue}this.changes.push(`raw index ${l.name} goes (at complete)`),this.completeIndexes.push({kind:"statement",sql:`DROP INDEX CONCURRENTLY IF EXISTS ${h.qualified(l,this.from)}`,why:`raw ${l.name}`})}}views(){let{anon:e,authenticated:t,service:n}=this.input.roles,s=[e,t,n].map(T).join(", "),i=[];for(let o of[...new Set(this.layout.tables.map(c=>c.schema))]){let c=T(de(this.n,o));i.push(`DROP SCHEMA IF EXISTS ${c} CASCADE`,`CREATE SCHEMA ${c}`,`GRANT USAGE ON SCHEMA ${c} TO ${s}`)}for(let o of this.layout.tables){let c=o.columns.map(l=>l.physical===l.name?T(l.name):`${T(l.physical)} AS ${T(l.name)}`).join(", "),r=L(de(this.n,o.schema),o.name);i.push(`CREATE VIEW ${r} WITH (security_invoker = true) AS SELECT ${c} FROM ${L(o.schema,o.physical)}`),i.push(`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${r} TO ${s}`)}return i}dropViews(e,t){let n=[...new Set(t.tables.map(s=>s.schema))];return n.length>0?n.map(s=>`DROP SCHEMA IF EXISTS ${T(de(e,s))} CASCADE`):["SELECT 1"]}keyOf(e){let t=this.where(e);return e.primaryKey.map(n=>{let s=this.matches.get(b(e))?.retyped.get(n);return s?s.from.name:t.cols.get(n)??n})}};function Gt(a){return new Map(a.columns.map(e=>[e.name,e.name]))}function se(a){return new Map([...a].filter(([e,t])=>e!==t))}function ge(a,e,t){return e?[`ALTER TABLE ${a} ENABLE ROW LEVEL SECURITY`]:t?[`ALTER TABLE ${a} DISABLE ROW LEVEL SECURITY`]:[]}function De(a){return JSON.stringify([a.columns,a.refSchema,a.refTable,a.refColumns,a.onDelete,a.onUpdate,a.match??"simple"])}function Fe(a){return JSON.stringify([a.keys,a.unique,a.where??null,a.method??"btree",a.include??[]])}var Je=/^\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,Jt=/^\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 Xt(a){return ve(a).map(e=>e.schema===void 0?T(e.name):L(e.schema,e.name))}var zt=/\bnextval\('((?:[^']|'')+)'(?:::regclass)?\)/gi;function ve(a){if(a===void 0)return[];let e=[];for(let t of a.matchAll(zt)){let n=t[1].replace(/''/g,"'"),s='("(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)',i=new RegExp(`^(?:${s}\\.)?${s}$`).exec(n);if(!i)continue;let o=c=>c.startsWith('"')?c.slice(1,-1).replace(/""/g,'"'):c.toLowerCase();e.push(i[1]===void 0?{name:o(i[2])}:{schema:o(i[1]),name:o(i[2])})}return e}function tt(a){let e=a.sql.trim().replace(/;\s*$/,""),t=Jt.exec(e);return!t||e.includes(";")?void 0:t[2].replace(/^"|"$/g,"")}function jt(a){let e=a.trim().replace(/;\s*$/,""),t=Jt.exec(e);if(!t||e.includes(";"))return;let n=t[2].replace(/^"|"$/g,""),s=e.slice(t[0].length);return{unique:!!t[1],create:`CREATE ${t[1]?"UNIQUE ":""}INDEX CONCURRENTLY IF NOT EXISTS ${T(n)} ON ${s}`,qualified:(i,o)=>{let c=/^\s*(?:ONLY\s+)?("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*)(?:\.("[^"]+"|[A-Za-z_][A-Za-z0-9_$]*))?/i.exec(s),r=h=>h.replace(/^"|"$/g,""),l=c?.[2]?r(c[1]):i.table?.split(".")[0]??o.tables.find(h=>h.name===r(c?.[1]??""))?.schema??"public";return L(l,n)}}}var pe=(a,e)=>JSON.stringify(a)===JSON.stringify(e),Se=a=>new Map(a.map(e=>[e.name,e])),fe=a=>({type:a.type,nullable:a.nullable,default:a.default??null,identity:a.identity??null,generated:a.generated??null});function bn(a,e){if(a.name===e)return a;let{renamedFrom:t,...n}=a;return{...n,name:e}}function Qt(a,e,t){let n=re(t),s=[],i=[...a.unmanaged],o=new Map(a.schema.tables.map(p=>[b(p),p])),c=new Map(e.schema.tables.map(p=>[b(p),p])),r=new Set,l=[],h=new Set(n.raw.map(p=>tt(p)).filter(p=>p!==void 0));for(let p of n.tables){let m=o.get(b(p))??(p.renamedFrom!==void 0?o.get(`${p.schema}.${p.renamedFrom}`):void 0);if(!m)continue;r.add(b(m));let S=c.get(b(p));if(!S)throw new Error(`palgres: the shadow database has no ${b(p)}: the schema did not make it`);let w=Se(S.columns),d=m.columns.map(O=>{let k=p.columns.find(x=>x.name===O.name)??p.columns.find(x=>x.renamedFrom===O.name&&!m.columns.some(H=>H.name===x.name)),_=k&&w.get(k.name);return k&&_&&pe(fe(O),fe(_))?bn(k,O.name):O}),$=(O,k,_)=>{let x=Se(k),H=Se(_);return O.map(y=>{let U=x.get(y.name),M=H.get(y.name);return M&&U&&pe(y,U)?M:y})};l.push({schema:m.schema,name:m.name,...p.ignored!==void 0?{ignored:p.ignored}:{},...p.renamedFrom!==void 0&&p.name===m.name?{renamedFrom:p.renamedFrom}:{},columns:d,primaryKey:m.primaryKey,uniques:$(m.uniques,S.uniques,p.uniques),indexes:$(m.indexes.filter(O=>!h.has(O.name)),S.indexes,p.indexes),checks:$(m.checks,S.checks,p.checks),foreignKeys:$(m.foreignKeys.filter(O=>o.has(`${O.refSchema}.${O.refTable}`)&&n.tables.some(k=>k.schema===O.refSchema&&k.name===O.refTable||k.schema===O.refSchema&&k.renamedFrom===O.refTable)?!0:(i.push(`foreign key ${b(m)}.${O.name} references ${O.refSchema}.${O.refTable}, outside the schema \u2014 kept as it is; drop it when its target goes`),!1)),S.foreignKeys,p.foreignKeys),rls:m.rls,policies:$(m.policies,S.policies,p.policies)})}for(let p of o.keys())r.has(p)||i.push(`table ${p}: not in the schema \u2014 kept as it is`);for(let p of a.forced)r.has(p)||i.push(`table ${p}: row-level security FORCEd on its owner \u2014 kept as it is`);let N=new Map(a.schema.tables.flatMap(p=>p.indexes.map(m=>[`${p.schema}.${m.name}`,{t:p,i:m}]))),u=new Map(e.schema.tables.flatMap(p=>p.indexes.map(m=>[`${p.schema}.${m.name}`,{t:p,i:m}]))),g=[],f=!0;for(let[p,m]of e.objects){let S=a.objects.get(p);S===void 0?f=!1:S!==m&&s.push(`${p} is not what the schema's raw SQL makes: drop it, and the migration makes it as the schema says`)}for(let p of n.raw){let m=tt(p);if(m===void 0){f&&g.push(p);continue}let S=[...u.keys()].find($=>$.endsWith(`.${m}`)),w=S&&u.get(S),d=S&&N.get(S);if(!w||!d){let $=[...e.objects.keys()].find(O=>O.startsWith("index ")&&O.endsWith(`.${m}`));$!==void 0&&a.objects.get($)===e.objects.get($)&&g.push(p);continue}pe(d.i,w.i)&&b(d.t)===b(w.t)?g.push(p):s.push(`index ${S} is not what the schema's raw unit ${p.name} makes: drop it, and the migration makes it as the schema says`)}let R=[];for(let p of n.enums){let m=a.schema.enums.find(S=>S.schema===p.schema&&S.name===p.name);m&&R.push(pe(m.values,p.values)?p:m)}let I=n.extensions.filter(p=>a.schema.extensions.includes(p));return{schema:re({tables:l,enums:R,extensions:I,raw:g}),unforce:a.forced.filter(p=>r.has(p)),refusals:s,unmanaged:i}}function Rs(a,e){let t=[],n=new Map(a.schema.tables.map(s=>[b(s),s]));for(let s of e.schema.tables){let i=b(s),o=n.get(i);if(!o){t.push(`table ${i} is missing`);continue}for(let h of s.columns)o.columns.some(N=>N.name===h.name)||t.push(`column ${i}.${h.name} is missing`);for(let h of o.columns)s.columns.some(N=>N.name===h.name)||t.push(`column ${i}.${h.name}: not declared`);for(let h of s.columns){let N=o.columns.find(u=>u.name===h.name);N&&!pe(fe(N),fe(h))&&t.push(`column ${i}.${h.name}: ${JSON.stringify(fe(N))}, declared ${JSON.stringify(fe(h))}`)}pe(o.primaryKey,s.primaryKey)||t.push(`table ${i}: primary key (${o.primaryKey.join(", ")}), declared (${s.primaryKey.join(", ")})`),o.rls!==s.rls&&t.push(`table ${i}: row-level security ${o.rls?"on":"off"}, declared ${s.rls?"on":"off"}`);let c={uniques:"unique",indexes:"index",checks:"check",foreignKeys:"foreign key",policies:"policy"},r=(h,N)=>e.schema.tables.some(u=>u.schema===h&&u.name===N),l={...o,foreignKeys:o.foreignKeys.filter(h=>r(h.refSchema,h.refTable))};for(let[h,N]of Object.entries(c)){let u=Se(l[h]),g=Se(s[h]);for(let[f,R]of g)pe(u.get(f),R)||t.push(`${N} ${i}.${f}: ${u.has(f)?`${JSON.stringify(u.get(f))}, declared ${JSON.stringify(R)}`:"missing"}`);for(let f of u.keys())g.has(f)||t.push(`${N} ${i}.${f}: not declared`)}}return t}function ce(a,e){let t=a.join("_").replace(/[^A-Za-z0-9_]/g,"_").replace(/^([^A-Za-z_])/,"_$1");if(Buffer.byteLength(t)>55){let s=0;for(let i of a.join("."))s=Math.imul(s,31)+i.charCodeAt(0)>>>0;t=`${t.slice(0,46)}_${s.toString(36)}`}let n=t;for(let s=2;e.has(n);s++)n=`${t}_${s}`;return e.add(n),n}function Cn(a){let e="$palgres$";for(let t=1;a.includes(e);t++)e=`$palgres${t}$`;return e}var nt=(a,e)=>{let t=Cn(e+a);return`DO ${t} BEGIN IF NOT (${a}) THEN ${e}; END IF; END ${t}`};async function Zt(a,e,t,n){let s=new Set,i=[],o=[],c=[],r=await a(`SELECT n.nspname AS schema, t.typname AS name, pg_catalog.format_type(t.typbasetype, t.typtypmod) AS base,
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
+ pg_catalog.pg_get_expr(t.typdefaultbin, 0) AS default, t.typnotnull AS notnull,
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
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
181
+ WHERE n.nspname IN ${e} AND t.typtype = 'd'
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 m of r){let S=[`AS ${m.base}`];m.collation!==null&&S.push(`COLLATE ${m.collation}`),m.default!==null&&S.push(`DEFAULT ${m.default}`),m.notnull&&S.push("NOT NULL");for(let d of m.checks??[])S.push(`CONSTRAINT ${T(d.name)} ${d.def}`);let w=`domain ${m.schema}.${m.name}`;n.set(w,S.join(" ")),i.push({schema:m.schema,key:w,listed:`type ${m.schema}.${m.name} (`,kind:"domain",name:ce(["domain",m.schema==="public"?m.name:`${m.schema}_${m.name}`],s),before:!0,create:nt(`EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = ${he(m.schema)} AND t.typname = ${he(m.name)})`,`CREATE DOMAIN ${L(m.schema,m.name)} ${S.join(" ")}`),drop:`DROP DOMAIN IF EXISTS ${L(m.schema,m.name)}`})}let l=await a(`SELECT n.nspname AS schema, t.typname AS name,
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
+ 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
+ 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
+ WHERE n.nspname IN ${e} AND t.typtype = 'c' AND c.relkind = 'c'
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 m of l){let S=(m.attrs??[]).map($=>`${T($.name)} ${$.type}`).join(", "),w=`type ${m.schema}.${m.name}`;n.set(w,S);let d={schema:m.schema,key:w,listed:`type ${m.schema}.${m.name} (`,kind:"type",name:ce(["type",m.schema==="public"?m.name:`${m.schema}_${m.name}`],s),before:!m.usesTable,create:nt(`EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace WHERE n.nspname = ${he(m.schema)} AND t.typname = ${he(m.name)})`,`CREATE TYPE ${L(m.schema,m.name)} AS (${S})`),drop:`DROP TYPE IF EXISTS ${L(m.schema,m.name)}`};(d.before?i:o).push(d)}let h=await a(`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
+ s.seqmin::text AS min, s.seqmax::text AS max, s.seqcache::text AS cache, s.seqcycle AS cycle
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
+ WHERE n.nspname IN ${e}
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 m of h){let S=`AS ${m.type} INCREMENT BY ${m.increment} MINVALUE ${m.min} MAXVALUE ${m.max} START WITH ${m.start} CACHE ${m.cache}${m.cycle?" CYCLE":" NO CYCLE"}`,w=`sequence ${m.schema}.${m.name}`;n.set(w,S),i.push({schema:m.schema,key:w,listed:`sequence ${m.schema}.${m.name} (`,kind:"sequence",name:ce(["sequence",m.schema==="public"?m.name:`${m.schema}_${m.name}`],s),before:!0,create:`CREATE SEQUENCE IF NOT EXISTS ${L(m.schema,m.name)} ${S}`,drop:`DROP SEQUENCE IF EXISTS ${L(m.schema,m.name)}`})}let N=await a(`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
+ EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_class rc ON rc.oid = t.typrelid
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
+ OR t.typarray = p.prorettype)) AS "usesRelation"
198
+ FROM pg_catalog.pg_proc p JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
199
+ WHERE n.nspname IN ${e} AND p.proname NOT LIKE '\\_palgres\\_%' AND p.prokind IN ('f', 'p', 'w')
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 m of N){let S=`function ${m.schema}.${m.name}(${m.args})`,w={schema:m.schema,key:S,listed:`function ${m.schema}.${m.name}(${m.args})`,kind:"function",name:ce(["fn",m.schema==="public"?m.name:`${m.schema}_${m.name}`,m.args===""?"":m.args.replace(/\s+/g,"_")].filter(Boolean),s),before:!m.usesRelation,create:m.def.trim(),drop:`DROP ${m.kind==="p"?"PROCEDURE":"FUNCTION"} IF EXISTS ${L(m.schema,m.name)}(${m.args})`};(w.before?i:c).push(w)}let u=await a(`SELECT n.nspname AS schema, p.proname AS name, pg_catalog.pg_get_function_identity_arguments(p.oid) AS args,
202
+ a.aggtransfn::regprocedure::text AS sfunc, pg_catalog.format_type(a.aggtranstype, NULL) AS stype,
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
+ a.agginitval AS init, CASE WHEN a.aggsortop <> 0 THEN a.aggsortop::regoperator::text END AS sortop, p.proparallel AS parallel,
205
+ EXISTS (SELECT 1 FROM pg_catalog.pg_type t JOIN pg_catalog.pg_class rc ON rc.oid = t.typrelid WHERE rc.relkind <> 'c' AND (t.oid = a.aggtranstype OR t.oid = p.prorettype OR t.oid = ANY (p.proargtypes::oid[]))) AS "usesRelation"
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
+ WHERE n.nspname IN ${e} AND a.aggkind = 'n' AND a.aggmtransfn = 0
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 m of u){let S=m.sfunc.replace(/\(.*\)$/,""),w=[`SFUNC = ${S}`,`STYPE = ${m.stype}`];m.final!==null&&w.push(`FINALFUNC = ${m.final}`),m.combine!==null&&w.push(`COMBINEFUNC = ${m.combine}`),m.init!==null&&w.push(`INITCOND = ${he(m.init)}`),m.sortop!==null&&w.push(`SORTOP = ${m.sortop.replace(/\(.*\)$/,"")}`),w.push(`PARALLEL = ${m.parallel==="s"?"SAFE":m.parallel==="r"?"RESTRICTED":"UNSAFE"}`);let d=`aggregate ${m.schema}.${m.name}(${m.args})`;n.set(d,w.join(", "));let $={schema:m.schema,key:d,listed:`function ${m.schema}.${m.name}(${m.args})`,kind:"function",name:ce(["agg",m.schema==="public"?m.name:`${m.schema}_${m.name}`,m.args.replace(/\s+/g,"_")].filter(Boolean),s),before:!m.usesRelation&&!c.some(O=>O.key.startsWith(`function ${S}(`)||m.final!==null&&O.key.startsWith(`function ${m.final}(`)),create:`CREATE OR REPLACE AGGREGATE ${L(m.schema,m.name)}(${m.args}) (${w.join(", ")})`,drop:`DROP AGGREGATE IF EXISTS ${L(m.schema,m.name)}(${m.args})`};($.before?i:c).push($)}let g=await a(`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
+ (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
+ JOIN pg_catalog.pg_class rc ON rc.oid = d.refobjid JOIN pg_catalog.pg_namespace rn ON rn.oid = rc.relnamespace
212
+ WHERE r.ev_class = c.oid AND d.refclassid = 'pg_catalog.pg_class'::regclass AND d.refobjid <> c.oid) AS reads
213
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
214
+ WHERE n.nspname IN ${e} AND c.relkind IN ('v', 'm')
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(t),R=[...g];for(let m=!0;m&&R.length>0;){m=!1;for(let S=0;S<R.length;S++){let w=R[S];if(!(w.reads??[]).every(_=>f.has(_)))continue;R.splice(S--,1),m=!0,f.add(`${w.schema}.${w.name}`);let d=w.def.trim().replace(/;$/,""),$=w.options?.length?` WITH (${w.options.join(", ")})`:"",O=w.kind==="m",k=`${O?"materialized view":"view"} ${w.schema}.${w.name}`;n.set(k,JSON.stringify({options:w.options??[],query:d})),o.push({schema:w.schema,key:k,listed:`${O?"materialized view":"view"} ${w.schema}.${w.name}`,kind:O?"materialized view":"view",name:ce([O?"matview":"view",w.schema==="public"?w.name:`${w.schema}_${w.name}`],s),before:!1,create:O?`CREATE MATERIALIZED VIEW IF NOT EXISTS ${L(w.schema,w.name)}${$} AS ${d}`:`CREATE OR REPLACE VIEW ${L(w.schema,w.name)}${$} AS ${d}`,drop:`DROP ${O?"MATERIALIZED VIEW":"VIEW"} IF EXISTS ${L(w.schema,w.name)}`})}}o.push(...c);let I=await a(`SELECT n.nspname AS schema, c.relname AS table, ic.relname AS name, pg_catalog.pg_get_indexdef(i.indexrelid) AS def
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
+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace JOIN pg_catalog.pg_am am ON am.oid = ic.relam
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 ${we("ic")})))
221
+ ORDER BY ic.oid`);for(let m of I){if(!f.has(`${m.schema}.${m.table}`))continue;let S=`index ${m.schema}.${m.name}`;n.set(S,m.def),o.push({schema:m.schema,key:S,listed:`index ${m.schema}.${m.name} `,kind:"index",name:ce(["index",m.schema==="public"?m.name:`${m.schema}_${m.name}`],s),before:!1,create:m.def.replace(/^CREATE (UNIQUE )?INDEX /,"CREATE $1INDEX IF NOT EXISTS "),drop:`DROP INDEX IF EXISTS ${L(m.schema,m.name)}`})}let p=await a(`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
+ 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
+ WHERE n.nspname IN ${e} AND NOT t.tgisinternal AND t.tgname NOT LIKE '\\_palgres\\_%'
224
+ ORDER BY t.oid`);for(let m of p){if(!f.has(`${m.schema}.${m.table}`))continue;let S=`trigger ${m.schema}.${m.table}.${m.name}`;o.push({schema:m.schema,key:S,listed:`trigger ${m.name} on ${m.schema}.${m.table} `,kind:"trigger",name:ce(["trigger",m.schema==="public"?m.table:`${m.schema}_${m.table}`,m.name],s),before:!1,create:m.constraint?nt(`EXISTS (SELECT 1 FROM pg_catalog.pg_trigger x WHERE x.tgrelid = ${he(`${T(m.schema)}.${T(m.table)}`)}::regclass AND x.tgname = ${he(m.name)})`,m.def):m.def.replace(/^CREATE TRIGGER /,"CREATE OR REPLACE TRIGGER "),drop:`DROP TRIGGER IF EXISTS ${T(m.name)} ON ${L(m.schema,m.table)}`})}return[...i,...o]}var he=a=>`'${a.replace(/'/g,"''")}'`;var Ue={a:"no action",r:"restrict",c:"cascade",n:"set null",d:"set default"},kn={ALL:"all",SELECT:"select",INSERT:"insert",UPDATE:"update",DELETE:"delete"};async function st(a,e,t){let n=await a.reserve();try{return await _n(async s=>await n.unsafe(s),e,t)}finally{n.release()}}async function _n(a,e,t){let n=[],s=[],i=new Map,o=`(${e.map(A).join(", ")})`;await a("BEGIN READ ONLY");try{await a("SET LOCAL search_path = ''");let c=await a(`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
+ EXISTS (SELECT 1 FROM pg_catalog.pg_inherits i WHERE i.inhrelid = c.oid OR i.inhparent = c.oid) AS inherits,
226
+ (SELECT e.extname FROM pg_catalog.pg_depend d JOIN pg_catalog.pg_extension e ON e.oid = d.refobjid
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
+ FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
229
+ WHERE n.nspname IN ${o} AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
230
+ ORDER BY n.nspname, c.relname`),r=[],l=new Map;for(let p of c){let m=`${p.schema}.${p.name}`;if(p.extension!==null){n.push(`table ${m}: the extension ${p.extension}'s own \u2014 left to it`);continue}if(p.kind==="v"||p.kind==="m"||p.kind==="f"){n.push(`${p.kind==="v"?"view":p.kind==="m"?"materialized view":"foreign table"} ${m}`);continue}if(p.kind==="p"||p.partition||p.inherits){n.push(`table ${m}: partitioned or inherited \u2014 Palgres does not migrate it`);continue}p.forced&&s.push(m);let S={schema:p.schema,name:p.name,columns:[],primaryKey:[],uniques:[],indexes:[],checks:[],foreignKeys:[],rls:p.rls,policies:[]};r.push(S),l.set(p.oid,S)}let h=[...l.keys()];if(h.length>0){let p=`(${h.join(", ")})`,m=await a(`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
+ pg_catalog.pg_get_expr(d.adbin, d.adrelid) AS default, a.attidentity AS identity, a.attgenerated AS generated,
232
+ CASE WHEN a.attcollation <> t.typcollation THEN co.collname END AS collation
233
+ FROM pg_catalog.pg_attribute a
234
+ JOIN pg_catalog.pg_type t ON t.oid = a.atttypid
235
+ LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
236
+ LEFT JOIN pg_catalog.pg_collation co ON co.oid = a.attcollation
237
+ WHERE a.attrelid IN ${p} AND a.attnum > 0 AND NOT a.attisdropped
238
+ ORDER BY a.attrelid, a.attnum`);for(let y of m){let U=l.get(y.rel),M=`${U.schema}.${U.name}.${y.name}`,B=y.generated==="s"||y.generated==="v"?{expr:y.default??"",stored:y.generated==="s"}:void 0;y.collation!==null&&n.push(`column ${M}: collation ${y.collation} \u2014 kept, the model does not say it`);let E={name:y.name,type:Y(y.type),nullable:!y.notnull};B?E.generated=B:y.identity==="a"||y.identity==="d"?E.identity=y.identity==="a"?"always":"by default":y.default!==null&&(E.default=y.default),U.columns.push(E)}let S=await a(`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
+ (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
+ c.confrelid::int AS refrel,
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
+ 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
+ FROM pg_catalog.pg_constraint c LEFT JOIN pg_catalog.pg_class i ON i.oid = c.conindid
244
+ WHERE c.conrelid IN ${p}
245
+ ORDER BY c.conrelid, c.conname`),w=new Map,d=[...new Set(S.filter(y=>y.refrel).map(y=>y.refrel))];if(d.length>0)for(let y of await a(`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 (${d.join(", ")})`))w.set(y.oid,{schema:y.schema,name:y.name});let $=new Set;for(let y of S){let U=l.get(y.rel),M=`${U.schema}.${U.name}`;y.index&&(y.type==="p"||y.type==="u"||y.type==="x")&&$.add(`${U.schema}.${y.index}`);let B=y.type==="f"&&!y.deferred&&ue(Ue[y.del],Ue[y.upd]);if(y.deferrable&&y.type!=="n"&&!B){n.push(`constraint ${M}.${y.name}: deferrable \u2014 kept as it is, the model does not say it`);continue}switch(y.type){case"p":U.primaryKey=y.cols??[];break;case"u":if(/NULLS NOT DISTINCT/i.test(y.def)){n.push(`constraint ${M}.${y.name}: UNIQUE NULLS NOT DISTINCT \u2014 kept as it is`);break}U.uniques.push({name:y.name,columns:y.cols??[]});break;case"c":{let E=/^CHECK \((.*)\)( NOT VALID)?$/s.exec(y.def);if(!E||/\bNO INHERIT\b/.test(y.def)){n.push(`constraint ${M}.${y.name}: ${y.def} \u2014 kept as it is`);break}U.checks.push({name:y.name,expr:E[1]});break}case"f":{let E=y.refrel===null?void 0:w.get(y.refrel);if(!E||y.match==="p"){n.push(`constraint ${M}.${y.name}: ${y.def} \u2014 kept as it is`);break}let C={name:y.name,columns:y.cols??[],refSchema:E.schema,refTable:E.name,refColumns:y.refcols??[],onDelete:Ue[y.del],onUpdate:Ue[y.upd]};y.match==="f"&&(C.match="full"),y.deferrable&&(C.deferrable=!0),U.foreignKeys.push(C);break}case"n":break;default:n.push(`constraint ${M}.${y.name}: ${y.def} \u2014 kept as it is`)}}let O=await a(`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
+ -- indkey and indoption count from 0, and Bun cannot read an array that does not start at 1 ("[0:1]={\u2026}").
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
+ ARRAY(SELECT pg_catalog.pg_get_indexdef(i.indexrelid, k, true) FROM generate_series(1, i.indnatts) AS k) AS exprs,
249
+ pg_catalog.pg_get_expr(i.indpred, i.indrelid, true) AS where,
250
+ ${we("c")} AS "defaultOps",
251
+ i.indisvalid AS valid
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 ${p} AND c.relname NOT LIKE '\\_palgres\\_search\\_%'
254
+ ORDER BY i.indrelid, c.relname`);for(let y of O){let U=l.get(y.rel);if($.has(`${y.schema}.${y.name}`))continue;let M=`${U.schema}.${U.name}`;if(!y.valid){n.push(`index ${y.schema}.${y.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(y.method)||!y.defaultOps){n.push(`index ${y.schema}.${y.name} of ${M}: ${y.method}${y.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 C=0;C<y.keyatts;C++){let P=(y.options[C]&1)!==0,q=(y.options[C]&2)!==0,v={};P&&(v.desc=!0),q!==P&&(v.nulls=q?"first":"last");let G=y.attnums[C];B.push(G===0?{expr:y.exprs[C],...v}:{column:y.exprs[C].replace(/^"(.*)"$/,"$1").replace(/""/g,'"'),...v})}let E={name:y.name,keys:B,unique:y.unique};y.method!=="btree"&&(E.method=y.method),y.where!==null&&(E.where=y.where),y.keyatts<y.attnums.length&&(E.include=y.exprs.slice(y.keyatts).map(C=>C.replace(/^"(.*)"$/,"$1").replace(/""/g,'"'))),U.indexes.push(E)}let k=await a(`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 ${o} ORDER BY schemaname, tablename, policyname`),_=new Map([[t.anon,"anon"],[t.authenticated,"authenticated"],[t.service,"service_role"],["public","public"]]);for(let y of k){let U=r.find(E=>E.schema===y.schema&&E.name===y.table);if(!U)continue;let M=y.roles.map(E=>_.get(E)??`role:${E}`),B={name:y.name,for:kn[y.cmd],to:M};y.qual!==null&&(B.using=y.qual),y.check!==null&&(B.withCheck=y.check),y.permissive==="RESTRICTIVE"&&(B.restrictive=!0),U.policies.push(B)}let x=await a(`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 ${p} AND NOT t.tgisinternal AND t.tgname NOT LIKE '\\_palgres\\_%' ORDER BY 1, 2`);for(let y of x)n.push(`trigger ${y.name} on ${y.table} \u2014 kept as it is`),i.set(`trigger ${y.table}.${y.name}`,y.def);let H=await a(`SELECT format('%s.%s', schemaname, tablename) AS table, rulename AS name FROM pg_catalog.pg_rules WHERE schemaname IN ${o} ORDER BY 1, 2`);for(let y of H)n.push(`rule ${y.name} on ${y.table} \u2014 kept as it is`)}let N=await a(`SELECT n.nspname AS schema, t.typname AS name, t.typtype AS kind,
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
+ FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
259
+ WHERE n.nspname IN ${o} AND t.typtype IN ('e', 'd', 'c', 'r', 'm')
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 p of N)p.kind==="e"?u.push({schema:p.schema,name:p.name,values:p.values??[]}):n.push(`type ${p.schema}.${p.name} (${p.kind==="d"?"domain":p.kind==="c"?"composite":"range"}) \u2014 kept as it is`);let g=await a(`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
+ WHERE n.nspname IN ${o} AND p.proname NOT LIKE '\\_palgres\\_%'
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 p of g)n.push(`function ${p.name} \u2014 kept as it is`),i.set(`function ${p.name}`,p.def);let f=await a(`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
+ WHERE n.nspname IN ${o} AND c.relkind = 'S'
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 p of f)n.push(`sequence ${p.name} (owned by no column) \u2014 kept as it is`);let R=(await a("SELECT extname AS name FROM pg_catalog.pg_extension WHERE extname <> 'plpgsql' ORDER BY 1")).map(p=>p.name),I=await Zt(a,o,new Set(r.map(p=>`${p.schema}.${p.name}`)),i);return{schema:{tables:r,enums:u,extensions:R,raw:[]},unmanaged:n,forced:s,objects:i,units:I}}finally{await a("ROLLBACK")}}import{randomBytes as Un}from"node:crypto";var oe={SHARE:1,"SHARE ROW EXCLUSIVE":2,"ACCESS EXCLUSIVE":3},Z=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)`,z=String.raw`${Z}(?:\s*\.\s*${Z}){0,2}`,W=a=>new RegExp(a,"i");function tn(a){let e={needs:[],made:[]};for(let t of a)for(let n of Pe(t))nn(n,e);return e}function en(a){return a.startsWith('"')?a.slice(1,-1).replace(/""/g,'"'):a.toLowerCase()}var Q=a=>[...a.matchAll(new RegExp(Z,"g"))].map(e=>e[0]).join("."),Dn=W(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 nn(a,e){let t;if(t=/^DO\s+(?:LANGUAGE\s+\w+\s+)?(\$[A-Za-z_0-9]*\$)([\s\S]*?)\1/i.exec(a)){for(let n of Pe(t[2],!0)){let s=Dn.exec(n);s&&nn(n.slice(s.index),e)}return}if(t=W(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?(${z})\s*\*?\s*([\s\S]*)$`).exec(a))return xn(Q(t[1]),t[2],e);if(t=W(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?([\s\S]*?)(?:\s+(?:CASCADE|RESTRICT))?\s*$`).exec(a)){for(let n of Me(t[1]))e.needs.push({of:"relation",name:n,mode:"ACCESS EXCLUSIVE"},{of:"table",name:n});return}if(t=W(String.raw`^DROP\s+VIEW\s+(?:IF\s+EXISTS\s+)?([\s\S]*?)(?:\s+(?:CASCADE|RESTRICT))?\s*$`).exec(a)){for(let n of Me(t[1]))e.needs.push({of:"view",name:n});return}if(t=W(String.raw`^(?:CREATE\s+OR\s+REPLACE\s+(?:(?:TEMP|TEMPORARY)\s+)?(?:RECURSIVE\s+)?VIEW|ALTER\s+VIEW\s+(?:IF\s+EXISTS\s+)?)\s*(${z})`).exec(a)){e.needs.push({of:"view",name:Q(t[1])});return}if(t=W(String.raw`^CREATE\s+(?:OR\s+REPLACE\s+)?(?:CONSTRAINT\s+)?TRIGGER\s+${Z}\s+[\s\S]*?\bON\s+(?:ONLY\s+)?(${z})`).exec(a)){e.needs.push({of:"relation",name:Q(t[1]),mode:"SHARE ROW EXCLUSIVE"});return}if(t=W(String.raw`^(?:DROP\s+TRIGGER|(?:CREATE|ALTER|DROP)\s+POLICY|DROP\s+RULE)\s+(?:IF\s+EXISTS\s+)?${Z}\s+ON\s+(${z})`).exec(a)){e.needs.push({of:"relation",name:Q(t[1]),mode:"ACCESS EXCLUSIVE"});return}if(t=W(String.raw`^CREATE\s+(?:OR\s+REPLACE\s+)?RULE\s+${Z}\s+AS\s+ON\s+\w+\s+TO\s+(${z})`).exec(a)){e.needs.push({of:"relation",name:Q(t[1]),mode:"ACCESS EXCLUSIVE"});return}if(t=W(String.raw`^CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?!CONCURRENTLY\b)(?:IF\s+NOT\s+EXISTS\s+)?(?:${Z}\s+)?ON\s+(?:ONLY\s+)?(${z})`).exec(a)){e.needs.push({of:"relation",name:Q(t[1]),mode:"SHARE"});return}if(t=W(String.raw`^DROP\s+INDEX\s+(?!CONCURRENTLY\b)(?:IF\s+EXISTS\s+)?([\s\S]*?)(?:\s+(?:CASCADE|RESTRICT))?\s*$`).exec(a)){for(let n of Me(t[1]))e.needs.push({of:"index",name:n});return}if(t=W(String.raw`^TRUNCATE\s+(?:TABLE\s+)?([\s\S]*?)(?:\s+(?:RESTART|CONTINUE|CASCADE|RESTRICT)\b[\s\S]*)?$`).exec(a)){for(let n of Me(t[1]))e.needs.push({of:"relation",name:n,mode:"ACCESS EXCLUSIVE"});return}if(t=W(String.raw`^CREATE\s+(?:(?:GLOBAL|LOCAL)\s+)?(?:TEMP(?:ORARY)?\s+|UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?(${z})([\s\S]*)$`).exec(a)){e.made.push(Q(t[1]));let n=W(String.raw`^\s*PARTITION\s+OF\s+(${z})`).exec(t[2]);n&&e.needs.push({of:"relation",name:Q(n[1]),mode:"ACCESS EXCLUSIVE"});for(let s of sn(t[2]))e.needs.push({of:"relation",name:s,mode:"SHARE ROW EXCLUSIVE"})}}var Fn=[/^VALIDATE\s+CONSTRAINT\b/i,W(String.raw`^(?:ALTER\s+(?:COLUMN\s+)?${Z}\s+)?SET\s+STATISTICS\b`),W(String.raw`^(?:ALTER\s+(?:COLUMN\s+)?${Z}\s+)?(?:SET|RESET)\s*\(`),/^CLUSTER\s+ON\b/i,/^SET\s+WITHOUT\s+CLUSTER\b/i];function xn(a,e,t){let n=null,s=[];for(let i of Pe(e,!1,",")){let o,c="ACCESS EXCLUSIVE";W(String.raw`^ADD\s+(?:CONSTRAINT\s+${Z}\s+)?FOREIGN\s+KEY\b`).test(i)||/^(?:ENABLE|DISABLE)\s+(?:REPLICA\s+|ALWAYS\s+)?TRIGGER\b/i.test(i)?c="SHARE ROW EXCLUSIVE":Fn.some(r=>r.test(i))?c=null:(o=W(String.raw`^ATTACH\s+PARTITION\s+(${z})`).exec(i))?(c=null,s.push({of:"relation",name:Q(o[1]),mode:"ACCESS EXCLUSIVE"})):(o=W(String.raw`^DETACH\s+PARTITION\s+(${z})`).exec(i))?s.push({of:"relation",name:Q(o[1]),mode:"ACCESS EXCLUSIVE"}):(o=W(String.raw`^DROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?(${Z})`).exec(i))?s.push({of:"constraint",table:a,name:en(o[1])}):(o=W(String.raw`^DROP\s+(?:COLUMN\s+)?(?:IF\s+EXISTS\s+)?(${Z})`).exec(i))&&s.push({of:"column",table:a,name:en(o[1])});for(let r of sn(i))s.push({of:"relation",name:r,mode:"SHARE ROW EXCLUSIVE"});c!==null&&(n===null||oe[c]>oe[n])&&(n=c)}n!==null&&t.needs.push({of:"relation",name:a,mode:n}),t.needs.push(...s)}function sn(a){return[...a.matchAll(new RegExp(String.raw`\bREFERENCES\s+(${z})`,"gi"))].map(e=>Q(e[1]))}function Me(a){return Pe(a,!1,",").map(e=>W(String.raw`^(?:ONLY\s+)?(${z})\s*\*?$`).exec(e)?.[1]).filter(e=>e!==void 0).map(Q)}async function an(a,e){if(e.length===0)return[];let t=e.map((r,l)=>r.of==="relation"?{i:l,of:r.of,rel:r.name,mode:r.mode}:r.of==="constraint"||r.of==="column"?{i:l,of:r.of,rel:r.table,name:r.name}:{i:l,of:r.of,rel:r.name}),n=await a(`WITH r AS (SELECT n.*, to_regclass(n.rel)::oid AS oid FROM jsonb_to_recordset(${A(JSON.stringify(t))}::jsonb) AS n(i int, "of" text, rel text, name text, mode text)),
268
+ got AS (
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
+ UNION ALL
271
+ SELECT r.i, c.confrelid, 'ACCESS EXCLUSIVE' FROM r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid AND c.conname = r.name AND c.contype = 'f' WHERE r.of = 'constraint'
272
+ UNION ALL
273
+ SELECT r.i, CASE WHEN c.conrelid = r.oid THEN c.confrelid ELSE c.conrelid END, 'ACCESS EXCLUSIVE'
274
+ FROM r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid AND a.attname = r.name AND NOT a.attisdropped
275
+ JOIN pg_catalog.pg_constraint c ON c.contype = 'f' AND ((c.conrelid = r.oid AND a.attnum = ANY (c.conkey)) OR (c.confrelid = r.oid AND a.attnum = ANY (c.confkey)))
276
+ WHERE r.of = 'column'
277
+ UNION ALL
278
+ SELECT r.i, CASE WHEN c.conrelid = r.oid THEN c.confrelid ELSE c.conrelid END, 'ACCESS EXCLUSIVE'
279
+ FROM r JOIN pg_catalog.pg_constraint c ON c.contype = 'f' AND r.oid IN (c.conrelid, c.confrelid) WHERE r.of = 'table'
280
+ UNION ALL
281
+ SELECT r.i, x.indrelid, 'ACCESS EXCLUSIVE' FROM r JOIN pg_catalog.pg_index x ON x.indexrelid = r.oid WHERE r.of = 'index')
282
+ SELECT g.i, g.rel::text AS oid, g.rel::regclass::text AS name, coalesce(g.mode, 'ACCESS EXCLUSIVE') AS mode, k.relkind AS kind,
283
+ CASE WHEN k.relkind = 'v' THEN (SELECT coalesce(array_agg(DISTINCT d.refobjid::text), '{}') FROM pg_catalog.pg_rewrite w JOIN pg_catalog.pg_depend d ON d.classid = 'pg_catalog.pg_rewrite'::regclass AND d.objid = w.oid AND d.refclassid = 'pg_catalog.pg_class'::regclass
284
+ JOIN pg_catalog.pg_class b ON b.oid = d.refobjid AND b.relkind IN ('r', 'p') WHERE w.ev_class = g.rel AND d.refobjid <> g.rel) END AS reads
285
+ FROM got g JOIN pg_catalog.pg_class k ON k.oid = g.rel
286
+ WHERE k.relkind IN ('r', 'p', 'v')
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`),s=new Map,i=new Map;for(let r of n){let l=String(r.oid),h=r.mode;if(r.kind==="v"){i.has(l)||i.set(l,{lock:{oid:l,name:String(r.name),mode:"ACCESS EXCLUSIVE"},reads:r.reads.map(String)});continue}let N=s.get(l);N?oe[h]>oe[N.mode]&&(N.mode=h):s.set(l,{oid:l,name:String(r.name),mode:h})}let o=r=>s.get(r)?.mode==="ACCESS EXCLUSIVE";return[...[...i.values()].filter(r=>r.reads.length>0&&r.reads.every(o)).map(r=>r.lock),...s.values()]}async function on(a,e,t){if(e.length===0)return new Set;let n=e.map(i=>`(${A(i.oid)}::oid, ${A(i.mode)})`).join(", "),s=await a(`SELECT DISTINCT h.relation::text AS oid
289
+ FROM pg_catalog.pg_locks h JOIN (VALUES ${n}) AS want(rel, mode) ON want.rel = h.relation
290
+ JOIN pg_catalog.pg_locks w ON w.pid = h.pid AND NOT w.granted
291
+ WHERE h.locktype = 'relation' AND h.granted AND h.pid <> pg_backend_pid()
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,t)/1e3})`);return new Set(s.map(i=>String(i.oid)))}var vn={ShareLock:"SHARE",ShareRowExclusiveLock:"SHARE ROW EXCLUSIVE",ExclusiveLock:"ACCESS EXCLUSIVE",AccessExclusiveLock:"ACCESS EXCLUSIVE"};async function rn(a,e){let t=e.length===0?"":`AND l.relation NOT IN (SELECT o FROM unnest(ARRAY[${e.map(i=>`to_regclass(${A(i)})::oid`).join(", ")}]) AS o WHERE o IS NOT NULL)`,n=await a(`SELECT l.relation::text AS oid, l.relation::regclass::text AS name, l.mode
294
+ FROM pg_catalog.pg_locks l JOIN pg_catalog.pg_class c ON c.oid = l.relation
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') ${t}`),s=new Map;for(let i of n){let o=String(i.oid),c=vn[String(i.mode)],r=s.get(o);r?oe[c]>oe[r.mode]&&(r.mode=c):s.set(o,{oid:o,name:String(i.name),mode:c})}return[...s.values()]}function Pe(a,e=!1,t=";"){let n=[],s="",i=0,o=0,c=a.length;for(;o<c;){let r=a[o];if(r==="-"&&a[o+1]==="-"){for(;o<c&&a[o]!==`
297
+ `;)o++;s+=" ";continue}if(r==="/"&&a[o+1]==="*"){let l=0;do a[o]==="/"&&a[o+1]==="*"?(l++,o+=2):a[o]==="*"&&a[o+1]==="/"?(l--,o+=2):o++;while(o<c&&l>0);s+=" ";continue}if(r==="'"){let l=/[Ee]/.test(a[o-1]??"")&&!/[A-Za-z0-9_$]/.test(a[o-2]??""),h=o+1;for(;h<c;)if(l&&a[h]==="\\")h+=2;else if(a[h]==="'"&&a[h+1]==="'")h+=2;else{if(a[h]==="'")break;h++}s+=e?`'${" ".repeat(Math.max(0,h-o-1))}'`:a.slice(o,h+1),o=h+1;continue}if(r==='"'){let l=o+1;for(;l<c&&!(a[l]==='"'&&a[l+1]!=='"');)l+=a[l]==='"'?2:1;s+=a.slice(o,l+1),o=l+1;continue}if(r==="$"&&!/[A-Za-z0-9_$]/.test(a[o-1]??"")){let l=/^\$[A-Za-z_][A-Za-z0-9_]*\$|^\$\$/.exec(a.slice(o));if(l){let h=a.indexOf(l[0],o+l[0].length),N=h<0?c:h+l[0].length;s+=a.slice(o,N),o=N;continue}}if(r==="("?i++:r===")"&&i--,r===t&&i===0){s.trim()&&n.push(s.trim()),s="",o++;continue}s+=r,o++}return s.trim()&&n.push(s.trim()),n}var te=class extends Error{refusals;constructor(e){super(`palgres: the migration is refused:
298
+ - ${e.join(`
299
+ - `)}`),this.name="MigrationRefused",this.refusals=e}},He=class extends Error{from;to;openedBy;constructor(e,t,n=null){super(`palgres: the migration from version ${e??"none"} to ${t}${n?`, opened by ${n},`:""} is still open: complete it or roll it back first`),this.name="MigrationOpen",this.from=e,this.to=t,this.openedBy=n}},We=class extends Error{version;constructor(e,t,n){super(`palgres: ${t} connection(s) of version ${e} are still open after ${n} ms`),this.name="VersionStillConnected",this.version=e}},at=1e4,cn=`CREATE OR REPLACE FUNCTION palgres.defer_keys(keys text[], deferred boolean) RETURNS void
300
+ LANGUAGE plpgsql SET search_path = pg_catalog, pg_temp AS $palgres$
301
+ DECLARE
302
+ named text;
303
+ BEGIN
304
+ SELECT string_agg(format('%I.%I', n.nspname, c.conname), ', ' ORDER BY n.nspname, c.conname) INTO named
305
+ FROM pg_catalog.pg_constraint c JOIN pg_catalog.pg_namespace n ON n.oid = c.connamespace
306
+ WHERE c.contype = 'f' AND c.condeferrable AND n.nspname || '.' || c.conname = ANY (keys);
307
+ IF named IS NOT NULL THEN
308
+ EXECUTE 'SET CONSTRAINTS ' || named || CASE WHEN deferred THEN ' DEFERRED' ELSE ' IMMEDIATE' END;
309
+ END IF;
310
+ END $palgres$`,ye=class extends Error{constructor(e,t){super(`palgres: ${e} was not had in the step's time`,{cause:t}),this.name="LockNotHad"}},Re=class extends Error{constructor(e,t){super(`palgres: rows of ${e} to fill were held by writers through ${t} passes`),this.name="RowsHeld"}},Mn=new Set(["55P03","40P01","40001","57014","25006"]);function Bs(a){if(It(a)!==void 0)return!0;let e=a;for(let t=0;t<4&&typeof e=="object"&&e!==null;t++){if(e instanceof We||e instanceof Re)return!0;let n=$e(e);if(n!==void 0)return Mn.has(n)||n.startsWith("53");e=e.cause}return!1}var Pn={anon:"anon",authenticated:"authenticated",service:"service_role"},qn=a=>`palgres:v${a}`,ln="palgres.migrate",mn=class a{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,t={}){this.fieldsSource=t.fields,this.pool=e,this.roles={...Pn,...t.roles},this.lockTimeoutMs=t.lockTimeoutMs??500,this.statementWaitMs=t.statementWaitMs??6e5,this.attempts=t.attempts??10,this.batchSize=t.batchSize??1e3,this.disconnectTimeoutMs=t.disconnectTimeoutMs??6e4,this.log=t.log??(()=>{}),this.shadow=t.shadow,this.openedBy=t.openedBy??"deploy"}async status(){return this.session(async e=>{let t=await this.active(e),n=await this.open(e);return{active:t&&{n:t.n,digest:t.digest,state:"active"},open:n&&{from:n.from_n,to:n.to_n,phase:n.phase,opened_by:n.opened_by}}},!1)}async plan(e){dn(e);let t=Ae(e),n=async(s,i)=>{let o;try{o=await this.adopt(s,e)}catch(l){if(!(l instanceof te))throw l;return{from:null,to:1,changes:[],refusals:l.refusals,start:[],complete:[],rollback:[],layout:{tables:[]}}}let c=i?[]:await this.authRefusals(s);if(!o){let l=await this.planFrom(s,null,e);return{...l,refusals:[...c,...l.refusals]}}if(o.version.digest===t)return{from:null,to:o.version.n,changes:[],refusals:c,start:[],complete:[],rollback:[],layout:o.layout,adoption:o.adoption};let r=await this.planFrom(s,o.version,e);return{...r,refusals:[...c,...r.refusals],adoption:o.adoption}};return this.session(async s=>{let i=await this.active(s);return i?this.planFrom(s,i,e):n(s,!0)},!1,s=>n(s,!1))}async start(e){dn(e);let t=Ae(e);return this.session(async n=>{let s=await this.open(n);if(s){if((await this.version(n,s.to_n))?.digest!==t)throw new He(s.from_n,s.to_n,s.opened_by);if(s.phase==="started")return{state:"resumed",from:s.from_n,to:s.to_n,changes:s.plan.changes,completed:!1};if(s.phase!=="starting")throw new He(s.from_n,s.to_n);return this.log(`palgres: resuming the start of version ${s.to_n}`),await this.runStart(n,s),{state:"resumed",from:s.from_n,to:s.to_n,changes:s.plan.changes,completed:!1}}let i=await this.active(n);if(i?.digest===t)return{state:"in-sync",version:i.n};let o=i?null:await this.adopt(n,e),c=async()=>{n.ledger===!1&&(await this.ownAuth(n),await this.ensure(n),n.ledger=!0)};if(o){if(o.version.digest===t)return await c(),await o.record(),{state:"adopted",version:o.version.n,adoption:o.adoption};i=o.version}let r=o?.adoption,l=await this.planFrom(n,i,e);if(l.refusals.length>0)throw new te(l.refusals);await this.cipherFor(l),await c(),await o?.record(),await this.tx(n,["ALTER TABLE palgres.migration ADD COLUMN IF NOT EXISTS opened_by text",cn,`INSERT INTO palgres.versions (n, digest, schema, layout, state, direct) VALUES (${l.to}, ${A(t)}, ${A(JSON.stringify(pt(e)))}::jsonb, ${A(JSON.stringify(l.layout))}::jsonb, 'starting', ${Bn(l.layout)})`,`INSERT INTO palgres.migration (from_n, to_n, plan, phase, opened_by) VALUES (${l.from??"NULL"}, ${l.to}, ${A(JSON.stringify(l))}::jsonb, 'starting', ${A(this.openedBy)})`]),this.log(`palgres: version ${l.from??"none"} \u2192 ${l.to}:
311
+ ${l.changes.join(`
312
+ `)||"(no change but the views)"}`);let h={from_n:l.from,to_n:l.to,plan:l,done:{},phase:"starting",opened_by:this.openedBy};return await this.runStart(n,h),l.from===null?(await this.runComplete(n,{...h,phase:"started"}),{state:"started",from:null,to:l.to,changes:l.changes,completed:!0}):{state:"started",from:l.from,to:l.to,changes:l.changes,completed:!1,...r?{adoption:r}:{}}})}async complete(){return this.session(async e=>{let t=await this.open(e);if(!t)return{state:"none"};if(t.phase==="starting"||t.phase==="rolling_back")throw new Error(`palgres: version ${t.to_n} is ${t.phase==="starting"?"still starting: run start again to finish it":"being rolled back: run rollback again"}`);await this.cipherFor(t.plan),t.from_n!==null&&await this.waitGone(e,t.from_n),await this.runComplete(e,t);let n=await this.kept(e,t.plan),s=await this.unconverted(e,t.plan);return n.length+s.length===0?{state:"completed",version:t.to_n}:(n.length>0&&this.log(`palgres: kept, holding what version ${t.from_n} wrote while version ${t.to_n} rolled out \u2014 outside the schema now, and no longer migrated: ${n.join("; ")}. Drop them yourself once their data may go.`),s.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): ${s.join("; ")}. Write those rows' values yourself, then drop the old column.`),{state:"completed",version:t.to_n,kept:[...n,...s]})})}async unconverted(e,t){let n=[];for(let s of t.guarded?.retyped??[]){let i=L(s.schema,s.table);if((await e.query(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = to_regclass(${A(i)}) AND attname = ${A(s.kept)} AND NOT attisdropped) AS there`))[0]?.there!==!0)continue;let c=`FROM ${i} WHERE ${T(s.column)} IS NULL AND ${T(s.kept)} IS NOT NULL`,r=s.key.length===0?"ctid::text":s.key.length===1?`${T(s.key[0])}::text`:`ROW(${s.key.map(T).join(", ")})::text`,[{n:l}]=await e.query(`SELECT count(*)::int AS n ${c}`),h=(await e.query(`SELECT ${r} AS k ${c} ORDER BY ${s.key.length===0?"ctid":s.key.map(T).join(", ")} LIMIT 10`)).map(u=>String(u.k)),N=s.key.length===0?"ctid":s.key.join(", ");n.push(`column ${s.schema}.${s.table}.${s.kept}: the values of ${s.column} that did not become ${s.type}, in ${Number(l)} row(s) \u2014 ${N} ${h.join(", ")}${Number(l)>h.length?", \u2026":""}`)}return n}async kept(e,t){let n=[];for(let[s,i]of t.guarded?.tables??[])(await e.query(`SELECT to_regclass(${A(L(s,i))}) IS NOT NULL AS there`))[0]?.there===!0&&n.push(`table ${s}.${i}`);for(let[s,i,o]of t.guarded?.columns??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_attribute WHERE attrelid = to_regclass(${A(L(s,i))}) AND attname = ${A(o)} AND NOT attisdropped) AS there`))[0]?.there===!0&&n.push(`column ${s}.${i}.${o}`);return n}async rollback(){return this.session(async e=>{let t=await this.open(e);if(!t)return{state:"none"};if(t.phase==="completing")throw new Error(`palgres: version ${t.to_n} is completing: what the old version used is going; run complete again`);return await this.cipherFor(t.plan),await this.waitGone(e,t.to_n),t.phase!=="rolling_back"&&(await this.tx(e,["UPDATE palgres.migration SET phase = 'rolling_back', updated_at = now()"]),t.phase="rolling_back"),await this.runSteps(e,t,"rollback",[`UPDATE palgres.versions SET state = 'abandoned', retired_at = now() WHERE n = ${t.to_n}`,"DELETE FROM palgres.migration"]),this.log(`palgres: version ${t.to_n} rolled back; ${t.from_n??"no version"} serves`),{state:"rolled-back",version:t.from_n}})}async runStart(e,t){await this.runSteps(e,t,"start",[`UPDATE palgres.versions SET state = 'active', ready_at = now() WHERE n = ${t.to_n}`,"UPDATE palgres.migration SET phase = 'started', updated_at = now()"])}async runComplete(e,t){t.phase!=="completing"&&(await this.tx(e,["UPDATE palgres.migration SET phase = 'completing', updated_at = now()"]),t.phase="completing"),await this.runSteps(e,t,"complete",[...t.from_n!==null?[`UPDATE palgres.versions SET state = 'retired', retired_at = now() WHERE n = ${t.from_n}`]:[],`UPDATE palgres.versions SET direct = true WHERE n = ${t.to_n}`,"DELETE FROM palgres.migration"]),this.log(`palgres: version ${t.to_n} serves alone`)}async runSteps(e,t,n,s){let i=t.plan[n],o=t.done[n]??0;for(let c=o;c<i.length;c++){let r=i[c],l=`UPDATE palgres.migration SET done = done || ${A(JSON.stringify({[n]:c+1}))}::jsonb, updated_at = now()`,h=c===i.length-1;if(this.log(`palgres: ${n} ${c+1}/${i.length}: ${r.why}`),r.kind==="tx"){await this.tx(e,[...r.sql,...h?s:[l]]);continue}if(r.kind==="statement")await this.statement(e,r.sql);else if(r.kind==="backfill")await this.backfill(e,t,c,r);else if(r.kind==="seal")await this.seal(e,r);else if(r.kind==="settle")await new Promise(N=>setTimeout(N,r.ms));else throw new te([`version ${t.to_n}'s migration has a step of a kind this Palgres does not run (${JSON.stringify(r.kind)})`]);await this.tx(e,h?s:[l])}i.length===0&&await this.tx(e,s)}async tx(e,t){let n=t.every(h=>/^(?:UPDATE|INSERT\s+INTO|DELETE\s+FROM)\s+palgres\./i.test(h)),{needs:s,made:i}=n?{needs:[],made:[]}:tn(t),o=await an(e.query,s),{holding:c,statementTimeout:r}=await this.settings(e),l=0;await this.retrying(e,async h=>{await e.query("BEGIN");try{let N=this.lockTimeoutFor(h);await e.query(`SET LOCAL lock_timeout = ${N}`);let u=Date.now()+c,g=f=>e.query(`SELECT set_config('lock_timeout', '${Math.max(1,Math.floor(f))}', true)`);if(!n&&o.length>0){let f=Date.now();u=f+c;let R=[o[l],...o.filter((p,m)=>m!==l)],I=new Set;for(let[p,m]of R.entries()){let S=Math.max(1,Math.floor(u-Date.now())),w=p>0&&(u-Date.now()<1||I.has(m.oid));p>0&&await e.query(`SELECT set_config('lock_timeout', '${S}', true), set_config('statement_timeout', '${S}', true)`);try{await e.query(`LOCK TABLE ${m.name} IN ${m.mode} MODE${w?" NOWAIT":""}`)}catch(d){let $=$e(d);throw($==="55P03"||$==="57014")&&(l=o.indexOf(m),this.log(`palgres: ${m.name} is held by others (${m.mode} not had${w?" at once":` in ${p===0?N:S} ms`}): the step gives way`)),$==="57014"?new ye(m.name,d):d}p===0&&R.length>1&&(I=await on(e.query,R.slice(1),Date.now()-f))}await e.query(`SET LOCAL statement_timeout = ${A(r)}`)}for(let[f,R]of t.entries())!n&&o.length===0&&f===0?u=Date.now()+c:n||await g(u-Date.now()),await e.query(R);n||await this.notTakenFirst(e,o,i),await e.query("COMMIT")}catch(N){throw await e.query("ROLLBACK").catch(()=>{}),N}})}async settings(e){if(e.deadlockMs===void 0||e.statementTimeout===void 0){let[t]=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(t?.ms??1e3),e.statementTimeout=String(t?.st??"0")}return{holding:Math.max(1,Math.min(this.lockTimeoutMs,Math.floor(e.deadlockMs/2))),statementTimeout:e.statementTimeout}}async notTakenFirst(e,t,n){for(let s of await rn(e.query,n)){let i=t.find(o=>o.oid===s.oid);i&&oe[i.mode]>=oe[s.mode]||this.log(`palgres: ${s.name} was locked ${s.mode} by a statement, ${i?`more strongly than the step took it first (${i.mode})`:"not taken first"}`)}}async statement(e,t){let n=/^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS ("(?:[^"]|"")+") ON /.exec(t);await this.retrying(e,async()=>{if(n){let s=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 = ${A(pn(n[1]))} AND NOT i.indisvalid`);for(let i of s)await e.query(`DROP INDEX CONCURRENTLY IF EXISTS ${L(String(i.schema),pn(n[1]))}`)}await e.query(`SET lock_timeout = ${this.statementWaitMs}`);try{await e.query(t)}finally{await e.query("RESET lock_timeout")}})}async backfill(e,t,n,s){let{holding:i}=await this.settings(e),o=s.key.length>0,c=t.done.cursor?.step===n?t.done.cursor:void 0,r=c?.last??(o?null:0),l=c?.inclusive??!1,h=o?0:await this.pages(e,s.table),N=o?await this.highest(e,s):null,u=!1,g=c?.skippedFrom??null,f=g===null?[]:null,R=null,I=0,p=0,m=0;for(;;){let S=R?.splice(0,this.batchSize),w=S!==void 0,d=w?S.length===0:u?!1:o?N===null:Number(r)>=h,$;if(d||await this.retrying(e,async()=>{await e.query("BEGIN");try{await e.query(`SET LOCAL lock_timeout = ${i}`),await e.query("SET LOCAL statement_timeout = 30000");let k=(await e.query(o?this.keyedBatch(s,S??null,r,l,N,u):this.pageBatch(s,S??null,u?h:Number(r),u)))[0],_=k.left??[],x=w?!0:o?Number(k.seen)>0:!u,H={gone:Number(k.gone),seen:x,last:w||u&&!o?r:o?k.last??r:Number(r)+this.pagesPerBatch(),left:_},y=g??(_.length>0?o?_[0]:!0:R||S?o?S[0]??null:!0:null);await e.query(`UPDATE palgres.migration SET done = done || ${A(JSON.stringify({cursor:{step:n,last:H.last,inclusive:S?l:!1,skippedFrom:y}}))}::jsonb, updated_at = now()`),await e.query("COMMIT"),$=H}catch(k){throw await e.query("ROLLBACK").catch(()=>{}),k}}),$&&(I+=$.gone,p+=$.gone,w||(r=$.last,l=!1),$.left.length>0&&(g??=o?$.left[0]:!0,f!==null&&(f=f.length+$.left.length>at?null:[...f,...$.left])),$.seen))continue;if(!w&&!u){u=!0;continue}if(g===null)break;if(p>0)m=0;else if(++m>=this.attempts)throw new Re(s.table,m);let O=Math.min(250*2**Math.max(0,m-1),5e3);this.log(`palgres: ${f===null?"rows":`${f.length} row(s)`} of ${s.table} held by writers; gone over again in ${O} ms`),await new Promise(k=>setTimeout(k,O)),f!==null?R=f:o?(R=null,r=g,l=!0,N=await this.highest(e,s)):(R=null,r=0,h=await this.pages(e,s.table)),g=null,f=[],p=0,u=!1}this.log(`palgres: ${I} row(s)`)}async highest(e,t){let n=t.key.map(T).join(", ");return(await e.query(`SELECT (SELECT to_jsonb(x) FROM (SELECT ${n} FROM ${t.table} ORDER BY ${n} DESC LIMIT 1) x) AS k`))[0].k??null}pagesPerBatch(){return Math.max(1,Math.ceil(this.batchSize/50))}async pages(e,t){return Number((await e.query(`SELECT (pg_catalog.pg_relation_size(${A(t)}::regclass) / current_setting('block_size')::int)::int AS n`))[0].n)}keyedBatch(e,t,n,s,i,o){let c="_palgres_t",r=e.key.map(T).join(", "),l=e.key.map(p=>`${c}.${T(p)}`).join(", "),h=e.key.map((p,m)=>T(`_palgres_k${m}`)),N=e.key.map((p,m)=>`${c}.${T(p)} AS ${h[m]}`).join(", "),u=p=>e.key.map((m,S)=>`${p}.${h[S]} AS ${T(m)}`).join(", "),g=p=>`(SELECT ${r} FROM jsonb_populate_record(NULL::${e.table}, ${A(JSON.stringify(p))}::jsonb))`,f=n===null?"true":`(${l}) ${s?">=":">"} ${g(n)}`,R=t!==null?`(${l}) IN (SELECT ${r} FROM jsonb_populate_recordset(NULL::${e.table}, ${A(JSON.stringify(t))}::jsonb))`:o?`${f} AND (${e.where})`:`${f} AND (${l}) <= ${g(i)}`,I=t!==null?R:`${f} AND (${l}) <= (SELECT ${h.join(", ")} FROM edge)`;return`WITH win AS (SELECT ${N} FROM ${e.table} ${c} WHERE ${R} ORDER BY ${l} LIMIT ${this.batchSize}),
313
+ edge AS (SELECT * FROM win ORDER BY ${h.join(" DESC, ")} DESC LIMIT 1),
314
+ batch AS (SELECT ${N} FROM ${e.table} ${c} WHERE ${I} AND (${e.where}) FOR NO KEY UPDATE OF ${c} SKIP LOCKED),
315
+ done AS (UPDATE ${e.table} SET ${e.set} FROM batch WHERE (${e.key.map(p=>`${e.table}.${T(p)}`).join(", ")}) = (${h.map(p=>`batch.${p}`).join(", ")}) AND (${e.where}) RETURNING NOT (${e.where}) AS gone),
316
+ left_ AS (SELECT ${N} FROM ${e.table} ${c} WHERE ${I} AND (${e.where}) AND NOT EXISTS (SELECT 1 FROM batch b WHERE (${h.map(p=>`b.${p}`).join(", ")}) = (${l})))
317
+ SELECT (SELECT count(*) FROM win)::int AS seen, (SELECT count(*) FROM done WHERE gone)::int AS gone,
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 ${h.join(", ")} LIMIT ${at+1}) x) AS left`}pageBatch(e,t,n,s){let i=t!==null?`ctid = ANY (${A(`{${t.map(o=>`"${String(o)}"`).join(",")}}`)}::tid[])`:s?`ctid >= '(${n},0)'::tid`:`ctid >= '(${n},0)'::tid AND ctid < '(${n+this.pagesPerBatch()},0)'::tid`;return`WITH batch AS (SELECT ctid AS c FROM ${e.table} WHERE ${i} AND (${e.where}) FOR NO KEY UPDATE SKIP LOCKED),
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
+ left_ AS (SELECT ctid AS c FROM ${e.table} WHERE ${i} 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 ${at+1}) x) AS left`}async retrying(e,t){for(let n=1;;n++)try{await t(n);return}catch(s){let i=s instanceof ye?"57014":$e(s);if(i!=="55P03"&&i!=="40P01"&&!(s instanceof ye)||n>=this.attempts)throw s;let o=Math.min(250*2**(n-1),5e3);this.log(`palgres: a lock was busy (${i}); again in ${o} ms`),await new Promise(c=>setTimeout(c,o))}}async cipherFor(e){let t=[...new Set([...e.complete,...e.rollback].filter(n=>n.kind==="seal").map(n=>n.address))];if(!(t.length===0||this.fields!==void 0)){if(this.fieldsSource===void 0)throw new te([`${t.join(", ")} ${t.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 kt(this.fieldsSource)}}async seal(e,t){let n=this.fields;if(n===void 0)throw new te([`${t.address}'s rows are sealed or opened with the project's field keys \u2014 Migrator({ fields })`]);await this.waitBegunBefore(e,t.address);let{holding:s}=await this.settings(e);for(let i=1;;i++){let o=null,c=0;do await this.retrying(e,async()=>{await e.query("BEGIN");try{await e.query(`SET LOCAL lock_timeout = ${s}`),await e.query("SET LOCAL statement_timeout = 30000");let l=await Ft((h,N)=>e.query(h,N),t,n,o,this.batchSize);await e.query("COMMIT"),c+=l.done,o=l.last}catch(l){throw await e.query("ROLLBACK").catch(()=>{}),l}});while(o!==null);let r=await xt((l,h)=>e.query(l,h),t,n);if(this.log(`palgres: ${t.address}: pass ${i}, ${c} row(s) ${t.direction==="seal"?"sealed":"opened"}${r?", some written meanwhile":""}`),!r)return;if(i>=this.attempts)throw new Re(t.table,i);await new Promise(l=>setTimeout(l,Math.min(250*2**(i-1),5e3)))}}async waitBegunBefore(e,t){let n=(await e.query("SELECT coalesce(array_agg(x)::text[], ARRAY[]::text[]) AS xids FROM pg_snapshot_xip(pg_current_snapshot()) AS x"))[0].xids,s=Date.now()+this.statementWaitMs;for(let i=n;i.length>0;){if(i=(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'",[`{${i.join(",")}}`]))[0].xids,i.length===0)return;if(Date.now()>=s)throw new Error(`palgres: ${t}: ${i.length} transaction(s) open when its phase turned final are still open after ${this.statementWaitMs} ms \u2014 run complete again`);await new Promise(c=>setTimeout(c,200))}}async waitGone(e,t){let n=Date.now()+this.disconnectTimeoutMs;for(;;){let s=await e.query(`SELECT count(*)::int AS n FROM pg_stat_activity WHERE application_name = ${A(qn(t))} AND datname = current_database() AND pid <> pg_backend_pid()`),i=Number(s[0].n);if(i===0)return;if(Date.now()>=n)throw new We(t,i,this.disconnectTimeoutMs);await new Promise(o=>setTimeout(o,500))}}async adopt(e,t){let n=[...new Set([...t.tables.map(g=>g.schema),...t.raw.flatMap(g=>g.schema?[g.schema]:[])])],s=await st(this.pool,n,this.roles);if(!t.tables.some(g=>s.schema.tables.some(f=>f.schema===g.schema&&(f.name===g.name||f.name===g.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 o=await this.made(e,t,n,s),c=Qt(s,o,t);if(c.refusals.length>0)throw new te(c.refusals);let r=[this.roles.anon,this.roles.authenticated,this.roles.service].map(T).join(", "),l={tables:c.schema.tables.filter(g=>!g.ignored).map(g=>({schema:g.schema,name:g.name,physical:g.name,columns:g.columns.filter(f=>!f.ignored).map(f=>({name:f.name,physical:f.name}))}))},h=c.schema.tables.map(g=>L(g.schema,g.name)),N=Ae(c.schema),u=async()=>{await this.tx(e,[...c.unforce.map(g=>`ALTER TABLE ${L(g.slice(0,g.indexOf(".")),g.slice(g.indexOf(".")+1))} NO FORCE ROW LEVEL SECURITY`),...[...new Set(c.schema.tables.map(g=>g.schema))].map(g=>`GRANT USAGE ON SCHEMA ${T(g)} TO ${r}`),...h.map(g=>`GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE ${g} TO ${r}`),`DO $palgres$ DECLARE s regclass; BEGIN
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[${h.length>0?h.map(g=>`${A(g)}::regclass`).join(", "):"NULL::regclass"}]::oid[]) LOOP
325
+ EXECUTE format('GRANT USAGE, SELECT ON SEQUENCE %s TO ${r.replace(/'/g,"''")}', s);
326
+ END LOOP; END $palgres$`,`INSERT INTO palgres.versions (n, digest, schema, layout, state, direct, ready_at) VALUES (1, ${A(N)}, ${A(JSON.stringify(c.schema))}::jsonb, ${A(JSON.stringify(l))}::jsonb, 'active', true, now())`]),this.log(`palgres: takes the database over as version 1 (${c.schema.tables.length} table(s))${c.unforce.length>0?`; FORCE row-level security off on ${c.unforce.join(", ")}`:""}${c.unmanaged.length>0?`
327
+ left as it is:
328
+ ${c.unmanaged.join(`
329
+ `)}`:""}`)};return{version:{n:1,digest:N,state:"active",schema:c.schema},adoption:{unforced:c.unforce,unmanaged:c.unmanaged},layout:l,record:u}}async made(e,t,n,s){let i=`palgres_shadow_${Un(6).toString("hex")}`;await e.query(`CREATE DATABASE ${T(i)}`);try{let o=this.shadow(i);try{await new a(o,{roles:this.roles,lockTimeoutMs:this.lockTimeoutMs}).start(t);let c=await st(o,n,this.roles);return await Gn(o,s,c),c}finally{await o.end()}}finally{await e.query(`DROP DATABASE IF EXISTS ${T(i)}`)}}async planFrom(e,t,n){let s=new Set;for(let p of t?.schema.tables??[])(await e.query(`SELECT EXISTS (SELECT 1 FROM ${L(p.schema,p.name)}) AS any`))[0].any&&s.add(b(p));let i=new Map,o=[],c=(p,m)=>{let S=`${p}\0${m}`;return i.has(S)||(i.set(S,void 0),o.push([p,m])),i.get(S)},l=(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,h=Math.max(l,t?.n??0)+1,N=new Map,u=p=>(N.has(p)||N.set(p,void 0),N.get(p)),g=new Map;if((await e.query(`SELECT to_regclass('${K}.generations') IS NOT NULL AS there`))[0]?.there===!0)for(let p of await e.query(`SELECT table_key, gen, model, dimensions, metric, from_columns, status FROM ${K}.generations ORDER BY table_key, gen`)){let m=String(p.table_key);g.has(m)||g.set(m,[]),g.get(m).push({gen:Number(p.gen),model:String(p.model),dimensions:Number(p.dimensions),metric:p.metric,from:p.from_columns.map(String),status:p.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,R=()=>Vt({from:t&&{n:t.n,schema:t.schema,access:t.access??null},next:h,to:n,hasRows:p=>s.has(p),castable:c,checkedDomain:u,roles:this.roles,generations:p=>g.get(p)??[],vectorSchema:typeof f=="string"?f:"public"}),I=R();if(o.length===0&&N.size===0)return I;for(let[p,m]of o)i.set(`${p}\0${m}`,await this.casts(e,p,m));for(let p of N.keys())N.set(p,await this.checkedDomain(e,p));return R()}async checkedDomain(e,t){let n=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(${A(t)})`);return n.length===0?void 0:n[0].checked===!0}async casts(e,t,n){try{return await e.query(`SELECT CAST(NULL::${t} AS ${n})`),!0}catch(s){let i=$e(s);if(i==="42846")return!1;if(i==="42704")return;throw s}}async active(e){if(e.ledger===!1)return null;let t=await e.query("SELECT n, digest, schema, layout FROM palgres.versions WHERE state = 'active' ORDER BY n DESC LIMIT 1"),n=await this.open(e),i=(n?await e.query(`SELECT n, digest, schema, layout FROM palgres.versions WHERE n = ${n.from_n??-1}`):t)[0];return i?{n:Number(i.n),digest:String(i.digest),state:"active",schema:qe(i.schema),access:qe(i.layout)?.access??null}:null}async version(e,t){if(e.ledger===!1)return null;let n=await e.query(`SELECT n, digest, state FROM palgres.versions WHERE n = ${t}`);return n[0]?{n:t,digest:String(n[0].digest),state:n[0].state}:null}async open(e){if(e.ledger===!1)return null;let n=(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 n?{from_n:n.from_n===null?null:Number(n.from_n),to_n:Number(n.to_n),plan:Wn(qe(n.plan),Number(n.to_n)),done:qe(n.done),phase:n.phase,opened_by:typeof n.opened_by=="string"?n.opened_by:null}:null}async session(e,t=!0,n){let s=await this.pool.reserve(),i={query:async(o,c)=>await s.unsafe(o,c)};try{if(await i.query("SET application_name = 'palgres:migrate'"),await i.query(`SET search_path = public, ${hn}, pg_temp`),t){await i.query(`SELECT pg_advisory_lock(hashtextextended(${A(ln)}, 0))`);let o=(await i.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 = '${K}') AS search`))[0];i.ledger=o.there===!0,i.searchLedger=typeof o.search=="string"?o.search:null,i.ledger&&await this.ensure(i)}else if((await i.query("SELECT to_regclass('palgres.migration') IS NULL AS none"))[0].none)return await(n?n(i):e(Hn));return await e(i)}finally{t&&await i.query(`SELECT pg_advisory_unlock(hashtextextended(${A(ln)}, 0))`).catch(()=>{}),s.release()}}async ownAuth(e){let t=await this.authRefusals(e);if(t.length>0)throw new te(t)}async authRefusals(e){let t={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', '')"]},n=o=>o.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(o=>!(t[String(o.name)]??[]).some(c=>n(c)===n(String(o.src)))).map(o=>`auth.${o.name}() is the database's own (returns ${o.returns}: ${n(String(o.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 t=[this.roles.anon,this.roles.authenticated,this.roles.service],n=await e.query(`SELECT r FROM unnest(ARRAY[${t.map(A).join(", ")}]) AS r WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = r)`);if(n.length>0)throw new Error(`palgres: the database has no role ${n.map(i=>i.r).join(", ")} \u2014 the app's roles are made with the database`);let s=t.map(T).join(", ");await this.tx(e,["CREATE SCHEMA IF NOT EXISTS palgres",`CREATE TABLE IF NOT EXISTS palgres.versions (
330
+ n integer PRIMARY KEY,
331
+ digest text NOT NULL,
332
+ schema jsonb NOT NULL,
333
+ layout jsonb NOT NULL,
334
+ state text NOT NULL CHECK (state IN ('starting', 'active', 'retired', 'abandoned')),
335
+ started_at timestamptz NOT NULL DEFAULT now(),
336
+ ready_at timestamptz,
337
+ retired_at timestamptz,
338
+ direct boolean NOT NULL DEFAULT false
339
+ )`,`CREATE TABLE IF NOT EXISTS palgres.migration (
340
+ one boolean PRIMARY KEY DEFAULT true CHECK (one),
341
+ from_n integer,
342
+ to_n integer NOT NULL,
343
+ plan jsonb NOT NULL,
344
+ done jsonb NOT NULL DEFAULT '{}',
345
+ phase text NOT NULL CHECK (phase IN ('starting', 'started', 'completing', 'rolling_back')),
346
+ updated_at timestamptz NOT NULL DEFAULT now(),
347
+ opened_by text
348
+ )`,"GRANT USAGE ON SCHEMA palgres TO PUBLIC","GRANT SELECT (n, digest, state, direct) ON palgres.versions TO PUBLIC",`CREATE TABLE IF NOT EXISTS ${ie} (
349
+ address text PRIMARY KEY,
350
+ direction text NOT NULL CHECK (direction IN ('seal', 'open')),
351
+ phase text NOT NULL CHECK (phase IN ('mixed', 'final'))
352
+ )`,`GRANT SELECT ON ${ie} TO PUBLIC`,cn,"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 ${s}`,`GRANT EXECUTE ON FUNCTION auth.jwt(), auth.uid(), auth.role() TO ${s}`,...e.searchLedger===ke(this.roles)?[]:Ht(this.roles)]),e.searchLedger=ke(this.roles)}},Hn={query:async()=>[]};function Wn(a,e){let t=a.format??1;if(!Number.isInteger(t)||t<1||t>Ze)throw new te([`version ${e}'s migration was planned by a newer Palgres (plan format ${String(a.format)}; this one runs ${Ze} and before): release the version that planned it, or one after, to go on with it`]);for(let n of["start","complete","rollback"])for(let s of a[n]??[])if(!Kt.has(s.kind))throw new te([`version ${e}'s migration has a step of a kind this Palgres does not run (${JSON.stringify(s.kind)}, in its ${n}): release the version that planned it, or one after, to go on with it`]);return a}function dn(a){let e=dt(re(a));if(e.length>0)throw new rt(e)}function qe(a){return typeof a=="string"?JSON.parse(a):a}function pn(a){return a.slice(1,-1).replace(/""/g,'"')}var hn="extensions";function Gs(a,e="public"){return`${T(de(a,e))}, ${T(e)}, ${hn}, pg_temp`}function Bn(a){return a.tables.every(e=>e.physical===e.name&&e.columns.every(t=>t.physical===t.name))}async function Gn(a,e,t){for(let[n,s]of t.objects){if(!n.startsWith("view ")&&!n.startsWith("materialized view "))continue;let i=e.objects.get(n);if(i===void 0||i===s)continue;let{options:o,query:c}=JSON.parse(i),r=await a.reserve();try{await r.unsafe("BEGIN"),await r.unsafe("SET LOCAL search_path = ''"),await r.unsafe(`CREATE TEMP VIEW palgres_fixpoint AS ${c}`);let l=await r.unsafe("SELECT pg_catalog.pg_get_viewdef('pg_temp.palgres_fixpoint'::regclass, true) AS def");JSON.stringify({options:o,query:l[0].def.trim().replace(/;$/,"")})===s&&e.objects.set(n,s)}catch{}finally{await Promise.resolve(r.unsafe("ROLLBACK")).catch(()=>{}),r.release()}}}var Xn=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(" ")),jn=new Set(["defineSchema","defineTable","uuid","text","integer","bigint","numeric","boolean","timestamp","date","jsonb","policy","raw","foreignKey","enumType","sqlType","AnyColumn","TableHandle"]),it=a=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(a),gn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,D=a=>JSON.stringify(a).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029"),Yn=a=>a.replace(/[\r\n\u2028\u2029]+/g," "),fn=a=>a==="__proto__"?`[${D(a)}]`:gn.test(a)?a:D(a),un={uuid:"uuid()",text:"text()",integer:"integer()",bigint:"bigint()",numeric:"numeric()",boolean:"boolean()","timestamp with time zone":"timestamp()",date:"date()",jsonb:"jsonb()"},Kn=new Set(["uuid","text","integer","bigint","numeric","boolean","timestamp with time zone","date"]);function Vn(a){let e=/^'((?:[^']|'')*)'(?:::[a-z_ ."]+(?:\[\])?)?$/i.exec(a);return e?e[1].replace(/''/g,"'"):void 0}function Ks(a,e={}){let t=e.from??"palbase/backend",n=[],s=new Map,i=new Map(a.enums.map(f=>[Ee(f.schema,f.name),f])),o=new Map,c=new Set;for(let f of a.tables){let R=gn.test(f.name)&&!Xn.has(f.name)&&!jn.has(f.name)?f.name:`t_${f.name.replace(/[^A-Za-z0-9_$]/g,"_")}`;for(f.schema!=="public"&&c.has(R)&&(R=`${f.schema}_${R}`);c.has(R);)R=`${R}_`;c.add(R),o.set(b(f),R)}let r=e.units??[],l=zn(a),h=Jn(a),N=[...new Set([...a.tables.map(f=>f.schema),...r.map(f=>f.schema)])].sort(),u=new Map,g=new Set;for(let f of N.filter(it)){let R=f;for(let I=2;g.has(R.toLowerCase());I++)R=`${f}_${I}`;g.add(R.toLowerCase()),u.set(f,R)}for(let f of N){if(!it(f)){n.push(`schema ${JSON.stringify(f)} is not a plain name: not pulled`);continue}let R=a.tables.filter(_=>_.schema===f),I=new Set(["defineSchema","defineTable"]),p=new Map,m=R.map(_=>Qn(_,a,i,o,I,p,n,l,h)),S=r.filter(_=>_.schema===f);S.length>0&&I.add("raw");let w=S.map(_=>` raw(${D(_.name)}, ${D(_.create)}, { drop: ${D(_.drop)}${_.before?", before: true":""} }),`),d=[`import { ${[...I].sort().join(", ")} } from ${D(t)};`];for(let[_,x]of[...p].sort())d.push(`import { ${[...x].sort().join(", ")} } from ${D(`./${u.get(_)}.ts`)};`);let $=f==="public"&&a.extensions.length>0?`, extensions: [${a.extensions.map(D).join(", ")}]`:"",O=(e.unmanaged??[]).filter(_=>_.includes(` ${f}.`)&&!r.some(x=>_.startsWith(x.listed))),k=O.length>0?`// Left as it is in the database, outside this file:
353
+ ${O.map(_=>`// ${Yn(_)}`).join(`
354
+ `)}
355
+
356
+ `:"";s.set(`db/${u.get(f)}.ts`,`// Written by palgres pull from the database, ${new Date().toISOString().slice(0,10)}.
357
+ ${k}${d.join(`
358
+ `)}
359
+
360
+ ${m.join(`
361
+
362
+ `)}${m.length>0?`
363
+
364
+ `:""}export default defineSchema(${D(f)}, {
365
+ tables: [${R.map(_=>o.get(b(_))).join(", ")}],${$?`
366
+ ${$.slice(2)},`:""}${w.length>0?`
367
+ raw: [
368
+ ${w.join(`
369
+ `)}
370
+ ],`:""}
371
+ });
372
+ `)}return{files:s,notes:n}}function En(a,e){let t=s=>`${a.schema==="public"?a.name:`${a.schema}_${a.name}`}_${s}_fkey`,n=new Map;for(let s of a.foreignKeys)s.columns.length===1&&s.name===t(s.columns[0])&&s.match!=="full"&&!ot(e,s)&&n.set(s.columns[0],s);return n}var ot=(a,e)=>!it(e.refSchema)||!a.tables.some(t=>t.schema===e.refSchema&&t.name===e.refTable);function Jn(a){let e=new Map(a.tables.map(h=>[b(h),h.foreignKeys.filter(N=>!ot(a,N)).map(N=>`${N.refSchema}.${N.refTable}`)])),t=new Map,n=new Map,s=new Map,i=[],o=new Set,c=0,r=0,l=h=>{t.set(h,c),n.set(h,c),c++,i.push(h),o.add(h);for(let u of e.get(h)??[])t.has(u)?o.has(u)&&n.set(h,Math.min(n.get(h),t.get(u))):(l(u),n.set(h,Math.min(n.get(h),n.get(u))));if(n.get(h)!==t.get(h))return;let N;do N=i.pop(),o.delete(N),s.set(N,r);while(N!==h);r++};for(let h of e.keys())t.has(h)||l(h);return(h,N,u)=>s.get(b(h))===s.get(`${N}.${u}`)}function zn(a){let e=c=>c.endsWith("_id")?c.slice(0,-3):c,t=new Map,n=[];for(let c of a.tables)for(let[r,l]of En(c,a))n.push({fk:`${b(c)}.${r}`,child:b(c),column:r,target:`${l.refSchema}.${l.refTable}`,childName:c.name});let s=new Map,i=(c,r)=>s.set(`${c}\0${r}`,(s.get(`${c}\0${r}`)??0)+1);for(let c of n)i(c.child,e(c.column)),c.target!==c.child&&i(c.target,c.childName);let o=(c,r)=>(s.get(`${c}\0${r}`)??0)>1;for(let c of n){let r={};o(c.child,e(c.column))&&(r.as=c.column),c.target!==c.child&&o(c.target,c.childName)&&(r.reverseAs=`${c.childName}_${e(c.column)}`),(r.as!==void 0||r.reverseAs!==void 0)&&t.set(c.fk,r)}return t}function Qn(a,e,t,n,s,i,o,c,r){let l=b(a),h=[],N=a.primaryKey.length===1?a.primaryKey[0]:void 0,u=new Set(a.uniques.filter(d=>d.columns.length===1&&d.name===`${a.name}_${d.columns[0]}_key`).map(d=>d.columns[0])),g=En(a,e),f=d=>ot(e,d);for(let d of a.foreignKeys)f(d)&&o.push(`foreign key ${l}.${d.name} references ${d.refSchema}.${d.refTable}, outside the pulled schemas: left out, kept in the database as it is`);for(let d of a.foreignKeys)f(d)||!ue(d.onDelete,d.onUpdate)||d.deferrable||o.push(`foreign key ${l}.${d.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 R=new Set(a.indexes.map(d=>d.name)),I={name(d,$){let O=n.get(`${d}.${$}`);if(d!==a.schema){let k=i.get(d)??new Set;k.add(O),i.set(d,k)}return O},arrow(d,$,O){return r(a,d,$)?(s.add(`type ${O}`),`(): ${O} =>`):"() =>"}};h.push(" columns: {");for(let d of a.columns)h.push(` ${fn(d.name)}: ${Zn(a,d,t,s,o,N===d.name,u.has(d.name),g.get(d.name),R,I,c.get(`${l}.${d.name}`))},`);h.push(" },"),a.primaryKey.length>1&&h.push(` primaryKey: [${a.primaryKey.map(D).join(", ")}],`);let p=a.uniques.filter(d=>!(d.columns.length===1&&u.has(d.columns[0])&&d.name===`${a.name}_${d.columns[0]}_key`));p.length>0&&h.push(` unique: [${p.map(d=>`{ name: ${D(d.name)}, columns: [${d.columns.map(D).join(", ")}] }`).join(", ")}],`),a.checks.length>0&&h.push(` checks: [${a.checks.map(d=>`{ name: ${D(d.name)}, expr: ${D(d.expr)} }`).join(", ")}],`);let m=[],S=[];for(let d of a.indexes)(ts(d)?m:S).push(d);m.length>0&&h.push(` indexes: () => [${m.map(d=>ns(d)).join(", ")}],`);let w=a.foreignKeys.filter(d=>!f(d)&&g.get(d.columns[0])!==d);return w.length>0&&(s.add("foreignKey"),h.push(` foreignKeys: (c) => [${w.map(d=>as(a,d,I)).join(", ")}],`)),a.policies.length>0&&!a.rls?o.push(`table ${l} has ${a.policies.length} polic${a.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`):a.policies.length>0&&(s.add("policy"),h.push(` policies: () => [${a.policies.map(d=>is(a,d)).join(", ")}],`)),a.rls||h.push(" rls: false,"),S.length>0&&(s.add("raw"),h.push(` raw: [${S.map(d=>`raw(${D(d.name)}, ${D(ss(a,d))})`).join(", ")}],`)),`export const ${n.get(l)} = defineTable(${D(a.name)}, {
373
+ ${h.join(`
374
+ `)}
375
+ });`}function Zn(a,e,t,n,s,i,o,c,r,l,h){let N=`${b(a)}.${e.name}`,u,g=e.type,f=!1;g.endsWith("[]")&&(Kn.has(g.slice(0,-2))||t.has(g.slice(0,-2)))&&(g=g.slice(0,-2),f=!0);let R=t.get(g),I=/^numeric\((\d+),(\d+)\)$/.exec(g);if(un[g]?u=un[g]:R&&R.schema===a.schema?(u=`enumType(${D(R.name)}, [${R.values.map(D).join(", ")}])`,n.add("enumType")):I?u=`numeric({ precision: ${I[1]}, scale: ${I[2]} })`:(u=`sqlType(${D(e.type)})`,n.add("sqlType"),f=!1),n.add(u.slice(0,u.indexOf("("))),f&&(u+=".array()"),i&&(u+=".primaryKey()"),e.identity&&(u+=e.identity==="always"?".identity()":".identity({ always: false })"),e.nullable&&!i&&(u+=".nullable()"),o&&(u+=".unique()"),e.generated&&(u+=`.generated(${D(e.generated.expr)}${e.generated.stored?", { stored: true }":""})`),e.default!==void 0&&(u+=es(e,f)),c){let p=l.name(c.refSchema,c.refTable),m=[];h?.as!==void 0&&m.push(`as: ${D(h.as)}`),h?.reverseAs!==void 0&&m.push(`reverseAs: ${D(h.reverseAs)}`),c.onDelete!=="no action"&&m.push(`onDelete: ${D(c.onDelete)}`),c.onUpdate!=="no action"&&m.push(`onUpdate: ${D(c.onUpdate)}`),$n(a,e.name)||m.push("index: false"),ue(c.onDelete,c.onUpdate)&&!c.deferrable&&m.push("deferrable: false"),u+=`.references(${l.arrow(c.refSchema,c.refTable,"AnyColumn")} ${p}.${fn(c.refColumns[0])}${m.length>0?`, { ${m.join(", ")} }`:""})`}return/^(owner|user_id|created_by|author_id|.*_user_id)$/.test(e.name)&&!c&&s.push(`column ${N} may hold a user's id: mark it ownedByUser() or userRef() so user.deleted reaches it`),u}function $n(a,e){let t=a.indexes.find(s=>s.name===`${a.name}_${e}_idx`);if(t===void 0||t.unique||t.where!==void 0||t.method!==void 0||t.include?.length||t.keys.length!==1)return!1;let n=t.keys[0];return"column"in n&&n.column===e&&!n.desc&&n.nulls===void 0}function es(a,e){let t=a.default;if(t==="gen_random_uuid()")return".defaultRandom()";if(t==="now()"&&a.type==="timestamp with time zone"||t==="CURRENT_DATE"&&a.type==="date")return".defaultNow()";if(t==="true"||t==="false")return`.default(${t})`;if(/^-?\d+(\.\d+)?$/.test(t)&&(a.type==="integer"||a.type==="bigint"))return`.default(${t})`;if(t==="'{}'::text[]"||/^'\{\}'::/.test(t))return e?".default([])":`.defaultSql(${D(t)})`;let n=Vn(t);if(n!==void 0&&(/^'(?:[^']|'')*'::text$/.test(t)||a.type.startsWith("public.")&&!/::(?:text|character varying|character)\b/.test(t)))return`.default(${D(n)})`;if(n!==void 0&&a.type==="jsonb"&&/^'(?:[^']|'')*'::jsonb$/.test(t))try{let s=JSON.stringify(JSON.parse(n));if(s===n&&!/"__proto__"\s*:/.test(n))return`.default(${s})`}catch{}return`.defaultSql(${D(t)})`}function ts(a){if(a.method!==void 0||a.where!==void 0||!a.keys.every(t=>"column"in t))return!1;let e=a.keys[0];return a.keys.every(t=>t.desc===e.desc&&t.nulls===e.nulls)}function ns(a){let e=a.keys[0],t=[`name: ${D(a.name)}`,`columns: [${a.keys.map(n=>D(n.column)).join(", ")}]`];return a.unique&&t.push("unique: true"),e.desc&&t.push("sort: 'desc'"),e.nulls&&t.push(`nulls: ${D(e.nulls)}`),a.include?.length&&t.push(`include: [${a.include.map(D).join(", ")}]`),`{ ${t.join(", ")} }`}function ss(a,e){let t=s=>`"${s.replace(/"/g,'""')}"`,n=e.keys.map(s=>`${"column"in s?t(s.column):s.expr}${s.desc?" DESC":""}${s.nulls?` NULLS ${s.nulls.toUpperCase()}`:""}`).join(", ");return`CREATE ${e.unique?"UNIQUE ":""}INDEX ${t(e.name)} ON ${t(a.schema)}.${t(a.name)}${e.method?` USING ${e.method}`:""} (${n})${e.include?.length?` INCLUDE (${e.include.map(t).join(", ")})`:""}${e.where?` WHERE ${e.where}`:""}`}function as(a,e,t){let n=`foreignKey(${D(e.name)}).on(${e.columns.map(s=>`c.col(${D(s)})`).join(", ")}).references(${t.arrow(e.refSchema,e.refTable,"TableHandle")} ${t.name(e.refSchema,e.refTable)}, ${e.refColumns.map(D).join(", ")})`;return e.onDelete!=="no action"&&(n+=`.onDelete(${D(e.onDelete)})`),e.onUpdate!=="no action"&&(n+=`.onUpdate(${D(e.onUpdate)})`),e.match==="full"&&(n+=".match('full')"),e.columns.length===1&&!$n(a,e.columns[0])&&(n+=".index(false)"),ue(e.onDelete,e.onUpdate)&&!e.deferrable&&(n+=".deferrable(false)"),n}function is(a,e){let t=`policy(${D(e.name)}).for(${D(e.for)}).to(${e.to.map(D).join(", ")})`;e.restrictive&&(t+=".as('restrictive')"),e.using!==void 0&&(t+=`.using(${D(e.using)})`),e.withCheck!==void 0&&(t+=`.withCheck(${D(e.withCheck)})`);let n=s=>a.primaryKey[0]===s||a.uniques.some(i=>i.columns[0]===s)||a.indexes.some(i=>i.where===void 0&&"column"in(i.keys[0]??{})&&i.keys[0].column===s);return Lt(a,e).some(s=>!n(s)&&!a.indexes.some(i=>i.name===`${a.name}_${s}_idx`))&&(t+=".withoutIndexes()"),t}export{kt as a,je as b,ie as c,Nn as d,_t as e,Ct as f,Ft as g,os as h,K as i,Ve as j,yn as k,Mt as l,Rn as m,ds as n,de as o,Vt as p,Qt as q,Rs as r,st as s,te as t,He as u,We as v,Re as w,Bs as x,Pn as y,qn as z,mn as A,hn as B,Gs as C,Bn as D,Ks as E};