@rebasepro/server-postgres 0.29.1 → 0.29.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{BranchService-BIIBF5ZL.js → BranchService-CrXvcES2.js} +3 -3
- package/dist/{BranchService-BIIBF5ZL.js.map → BranchService-CrXvcES2.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +64 -4
- package/dist/PostgresBootstrapper.d.ts +27 -0
- package/dist/auth/ensure-tables.d.ts +2 -2
- package/dist/auth/schema-version.d.ts +5 -5
- package/dist/auth/services.d.ts +9 -9
- package/dist/{backup-cli-QcOpmRpQ.js → backup-cli-CTKCOLpX.js} +3 -3
- package/dist/{backup-cli-QcOpmRpQ.js.map → backup-cli-CTKCOLpX.js.map} +1 -1
- package/dist/{boot-ddl-BSNpEUOS.js → boot-ddl-CqGIwSYx.js} +2 -2
- package/dist/{boot-ddl-BSNpEUOS.js.map → boot-ddl-CqGIwSYx.js.map} +1 -1
- package/dist/{cli-console-DTsm96lW.js → cli-console-DBPw-oAz.js} +6 -6
- package/dist/{cli-console-DTsm96lW.js.map → cli-console-DBPw-oAz.js.map} +1 -1
- package/dist/{cli-errors-DwqFRIWz.js → cli-errors-DYTxnLbW.js} +5 -5
- package/dist/{cli-errors-DwqFRIWz.js.map → cli-errors-DYTxnLbW.js.map} +1 -1
- package/dist/cli.js +185 -49
- package/dist/cli.js.map +1 -1
- package/dist/{connection-COuS5Fm-.js → connection-C1zXTPJq.js} +7 -3
- package/dist/{connection-COuS5Fm-.js.map → connection-C1zXTPJq.js.map} +1 -1
- package/dist/data-transformer.d.ts +2 -2
- package/dist/database-health.d.ts +2 -1
- package/dist/{database-preflight-D5JtPt8i.js → database-preflight-iBpT7-vv.js} +36 -3
- package/dist/database-preflight-iBpT7-vv.js.map +1 -0
- package/dist/{databasePoolManager-7hXVurmG.js → databasePoolManager-DIjzlTK4.js} +2 -2
- package/dist/{databasePoolManager-7hXVurmG.js.map → databasePoolManager-DIjzlTK4.js.map} +1 -1
- package/dist/{deferred-index-build-B8feKnUj.js → deferred-index-build-BCU9RoHK.js} +18 -6
- package/dist/deferred-index-build-BCU9RoHK.js.map +1 -0
- package/dist/{doctor-BaR11xUe.js → doctor-Kg1oUK0Q.js} +11 -11
- package/dist/doctor-Kg1oUK0Q.js.map +1 -0
- package/dist/{ensure-collection-policies-85HiG-k1.js → ensure-collection-policies-Bo-_fDAy.js} +25 -15
- package/dist/ensure-collection-policies-Bo-_fDAy.js.map +1 -0
- package/dist/{ensure-collection-tables-DR_WcxLA.js → ensure-collection-tables-DCJINkT_.js} +11 -8
- package/dist/ensure-collection-tables-DCJINkT_.js.map +1 -0
- package/dist/{ensure-tables-Dh5UP_Zs.js → ensure-tables-BPGaGh0y.js} +4 -4
- package/dist/ensure-tables-BPGaGh0y.js.map +1 -0
- package/dist/{enum-labels-kept-DSU8lAnd.js → enum-labels-kept-YAgOZS4I.js} +3 -3
- package/dist/{enum-labels-kept-DSU8lAnd.js.map → enum-labels-kept-YAgOZS4I.js.map} +1 -1
- package/dist/{generate-drizzle-schema-5spbTyQ6.js → generate-drizzle-schema-DcrFr7YX.js} +2 -2
- package/dist/{generate-drizzle-schema-5spbTyQ6.js.map → generate-drizzle-schema-DcrFr7YX.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js → generate-drizzle-schema-logic-LTLZvt6r.js} +3 -3
- package/dist/{generate-drizzle-schema-logic-C5FB7Fpo.js.map → generate-drizzle-schema-logic-LTLZvt6r.js.map} +1 -1
- package/dist/{generate-files-Bl3_D_oP.js → generate-files-CsaVzatS.js} +3 -3
- package/dist/{generate-files-Bl3_D_oP.js.map → generate-files-CsaVzatS.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-BC3JA93M.js → generate-postgres-ddl-logic-Dg0bcENZ.js} +45 -7
- package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +1 -0
- package/dist/{generated-schema-diff-Jm93vyJB.js → generated-schema-diff-By4dxyTH.js} +8 -5
- package/dist/generated-schema-diff-By4dxyTH.js.map +1 -0
- package/dist/history/HistoryService.d.ts +2 -3
- package/dist/history/ensure-history-table.d.ts +8 -3
- package/dist/index.es.js +15 -15
- package/dist/interfaces.d.ts +24 -2
- package/dist/{introspect-db-logic-DgQVzccW.js → introspect-db-logic-DWqAEURB.js} +7 -5
- package/dist/introspect-db-logic-DWqAEURB.js.map +1 -0
- package/dist/{migrate-baseline-BfHmq3vN.js → migrate-baseline-CmWXL7qx.js} +163 -502
- package/dist/migrate-baseline-CmWXL7qx.js.map +1 -0
- package/dist/{migrate-policy-stamps-B4k1ggma.js → migrate-policy-stamps-BN_Qad6c.js} +42 -13
- package/dist/migrate-policy-stamps-BN_Qad6c.js.map +1 -0
- package/dist/{open-rebase-CiO_sjMT.js → open-rebase-40paQfVW.js} +1401 -655
- package/dist/open-rebase-40paQfVW.js.map +1 -0
- package/dist/open-rebase.d.ts +1 -1
- package/dist/{pg-error-utils-D1Nc0UML.js → pg-error-utils-DJHjCF7-.js} +2 -2
- package/dist/{pg-error-utils-D1Nc0UML.js.map → pg-error-utils-DJHjCF7-.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +24 -37
- package/dist/{plan-schema-BYxOzflz.js → plan-schema-vJd3UEmT.js} +41 -11
- package/dist/plan-schema-vJd3UEmT.js.map +1 -0
- package/dist/{policy-drift-DKuTJHfc.js → policy-drift-C-m0uWHH.js} +78 -10
- package/dist/policy-drift-C-m0uWHH.js.map +1 -0
- package/dist/push-index-adoption-Cp7oZxSl.js +22 -0
- package/dist/push-index-adoption-Cp7oZxSl.js.map +1 -0
- package/dist/{push-index-prebuild-bqXimSZz.js → push-index-prebuild-DbwKGtQT.js} +4 -4
- package/dist/{push-index-prebuild-bqXimSZz.js.map → push-index-prebuild-DbwKGtQT.js.map} +1 -1
- package/dist/{push-kept-defaults-CN9R8cHf.js → push-kept-defaults-CLcgsEPt.js} +2 -2
- package/dist/{push-kept-defaults-CN9R8cHf.js.map → push-kept-defaults-CLcgsEPt.js.map} +1 -1
- package/dist/{push-legacy-renames-CU_UYPbz.js → push-legacy-renames-BthD0E9W.js} +4 -4
- package/dist/{push-legacy-renames-CU_UYPbz.js.map → push-legacy-renames-BthD0E9W.js.map} +1 -1
- package/dist/{push-policy-plan-JcyK94bc.js → push-policy-plan-BgcrroxQ.js} +14 -8
- package/dist/push-policy-plan-BgcrroxQ.js.map +1 -0
- package/dist/read-routing.d.ts +10 -30
- package/dist/{render-ddl-DCdVP-pQ.js → render-ddl-Ci3S_SoI.js} +34 -3
- package/dist/render-ddl-Ci3S_SoI.js.map +1 -0
- package/dist/{request-role-cli-DSdRtvgH.js → request-role-cli-Dy1EgJU9.js} +10 -10
- package/dist/{request-role-cli-DSdRtvgH.js.map → request-role-cli-Dy1EgJU9.js.map} +1 -1
- package/dist/{request-role-migration-D9BZ5Uba.js → request-role-migration-GHTJnPMV.js} +2 -2
- package/dist/{request-role-migration-D9BZ5Uba.js.map → request-role-migration-GHTJnPMV.js.map} +1 -1
- package/dist/rls-bootstrap-sql-kPX4-MB1.js +549 -0
- package/dist/rls-bootstrap-sql-kPX4-MB1.js.map +1 -0
- package/dist/{rls-enforcement-BO618rnr.js → rls-enforcement-Cc_UhOxb.js} +316 -10
- package/dist/rls-enforcement-Cc_UhOxb.js.map +1 -0
- package/dist/{rls-settings-De5NoHHy.js → rls-settings-BCGMIig3.js} +23 -3
- package/dist/rls-settings-BCGMIig3.js.map +1 -0
- package/dist/schema/doctor-cli.js +9 -9
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/drizzle-ddl.d.ts +2 -2
- package/dist/schema/ensure-collection-policies.d.ts +23 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +14 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/index-adoption.d.ts +99 -0
- package/dist/schema/introspect-db-logic.d.ts +2 -1
- package/dist/schema/introspect-db.js +3 -3
- package/dist/schema/migrate-policy-stamps.d.ts +19 -1
- package/dist/schema/plan/diff-plan.d.ts +8 -1
- package/dist/schema/plan/render-ddl.d.ts +7 -0
- package/dist/schema/plan/types.d.ts +15 -0
- package/dist/schema/push-index-adoption.d.ts +10 -0
- package/dist/schema/push-policy-plan.d.ts +5 -1
- package/dist/schema/rls-bootstrap-sql.d.ts +19 -2
- package/dist/schema/search-column.d.ts +2 -2
- package/dist/search-column-BM-GV6vH.js.map +1 -1
- package/dist/security/policy-drift.d.ts +31 -1
- package/dist/security/rls-enforcement.d.ts +118 -1
- package/dist/security/rls-settings.d.ts +33 -0
- package/dist/services/FetchService.d.ts +33 -8
- package/dist/services/PersistService.d.ts +75 -4
- package/dist/services/RelationService.d.ts +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +2 -2
- package/dist/services/channel-bus/index.d.ts +2 -2
- package/dist/services/channel-history.d.ts +2 -2
- package/dist/services/channel-presence.d.ts +3 -3
- package/dist/services/dataService.d.ts +6 -2
- package/dist/services/realtimeService.d.ts +18 -5
- package/dist/services/socket-liveness.d.ts +6 -1
- package/dist/types.d.ts +1 -1
- package/dist/utils/drizzle-conditions.d.ts +12 -0
- package/dist/utils/positional-params.d.ts +40 -0
- package/dist/{websocket-B33YjKhs.js → websocket-B7ex6AQM.js} +3 -3
- package/dist/websocket-B7ex6AQM.js.map +1 -0
- package/dist/websocket.d.ts +14 -3
- package/package.json +7 -7
- package/dist/database-preflight-D5JtPt8i.js.map +0 -1
- package/dist/deferred-index-build-B8feKnUj.js.map +0 -1
- package/dist/doctor-BaR11xUe.js.map +0 -1
- package/dist/ensure-collection-policies-85HiG-k1.js.map +0 -1
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +0 -1
- package/dist/ensure-tables-Dh5UP_Zs.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-BC3JA93M.js.map +0 -1
- package/dist/generated-schema-diff-Jm93vyJB.js.map +0 -1
- package/dist/introspect-db-logic-DgQVzccW.js.map +0 -1
- package/dist/migrate-baseline-BfHmq3vN.js.map +0 -1
- package/dist/migrate-policy-stamps-B4k1ggma.js.map +0 -1
- package/dist/open-rebase-CiO_sjMT.js.map +0 -1
- package/dist/plan-schema-BYxOzflz.js.map +0 -1
- package/dist/policy-drift-DKuTJHfc.js.map +0 -1
- package/dist/push-policy-plan-JcyK94bc.js.map +0 -1
- package/dist/render-ddl-DCdVP-pQ.js.map +0 -1
- package/dist/rls-enforcement-BO618rnr.js.map +0 -1
- package/dist/rls-settings-De5NoHHy.js.map +0 -1
- package/dist/websocket-B33YjKhs.js.map +0 -1
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { a as __require,
|
|
4
|
-
import { U as withAppClient, it as redactConnectionPasswords } from "./cli-errors-
|
|
5
|
-
import {
|
|
6
|
-
import { sqlRows } from "@rebasepro/common";
|
|
3
|
+
import { a as __require, n as require_arg, o as __toESM, r as __commonJSMin } from "./cli-prompt-DXG0yk-h.js";
|
|
4
|
+
import { U as withAppClient, it as redactConnectionPasswords } from "./cli-errors-DYTxnLbW.js";
|
|
5
|
+
import { g as renderPredicate, m as isRebaseIndexName } from "./source-fZb92pN8.js";
|
|
7
6
|
import { suggestNearMiss } from "@rebasepro/utils";
|
|
8
7
|
import process$1, { execArgv, execPath, hrtime, platform } from "node:process";
|
|
9
8
|
import { constants } from "node:os";
|
|
@@ -20,6 +19,164 @@ import { appendFileSync, createReadStream, createWriteStream, readFileSync, stat
|
|
|
20
19
|
import { finished } from "node:stream/promises";
|
|
21
20
|
import { Duplex, PassThrough, Readable, Transform, Writable, getDefaultHighWaterMark } from "node:stream";
|
|
22
21
|
import { Buffer as Buffer$1 } from "node:buffer";
|
|
22
|
+
//#region src/schema/index-adoption.ts
|
|
23
|
+
/**
|
|
24
|
+
* Adopting an index the database already has, instead of building a twin.
|
|
25
|
+
*
|
|
26
|
+
* A declared index is found by its derived name (`collection-index.ts`), so an
|
|
27
|
+
* index someone made by hand — or one an introspected database arrived with —
|
|
28
|
+
* is invisible to it however exactly it matches the declaration: boot and
|
|
29
|
+
* `db push` built the same index again under the derived name, and every write
|
|
30
|
+
* to the table then maintained two. Declaring the indexes an application
|
|
31
|
+
* already has is the first thing anyone does when they bring a database to
|
|
32
|
+
* Rebase, so that was the common case, not an edge.
|
|
33
|
+
*
|
|
34
|
+
* So before an index is built, an existing one with the same definition on the
|
|
35
|
+
* same table takes the derived name (`ALTER INDEX … RENAME TO …`: a catalogue
|
|
36
|
+
* update, no rebuild, a brief lock). From then on it is the declared index:
|
|
37
|
+
* found by name, kept by push, dropped when the declaration is removed.
|
|
38
|
+
*
|
|
39
|
+
* "The same definition" is read from the catalogue part by part, not by
|
|
40
|
+
* comparing SQL text: the access method, uniqueness, the key columns in order
|
|
41
|
+
* with their direction and NULLS placement, the INCLUDE columns, the predicate,
|
|
42
|
+
* and — because two indexes over the same columns can still answer different
|
|
43
|
+
* queries — that every key uses its type's default operator class and the
|
|
44
|
+
* column's own collation. An index that differs in any of those, is over an
|
|
45
|
+
* expression, backs a constraint, is INVALID, or already carries a Rebase name
|
|
46
|
+
* is left alone, and the declared one is built beside it as before.
|
|
47
|
+
*
|
|
48
|
+
* A partial index is adopted only when the two predicates read the same once
|
|
49
|
+
* Postgres's own spelling is normalised away (identifier quotes, casts on
|
|
50
|
+
* literals, parentheses, case). A wrong adoption would leave a declared index
|
|
51
|
+
* answering a narrower question than the one declared, so a predicate this
|
|
52
|
+
* cannot read as the same is not adopted.
|
|
53
|
+
*/
|
|
54
|
+
/**
|
|
55
|
+
* Every index on an ordinary or partitioned table in `schemas`, as
|
|
56
|
+
* {@link ExistingIndexShape} rows. The schema names are written in as quoted
|
|
57
|
+
* literals: the boot's catalogue reader runs its queries without parameters.
|
|
58
|
+
*/
|
|
59
|
+
var indexShapesSql = (schemas) => `
|
|
60
|
+
SELECT n.nspname AS "schema",
|
|
61
|
+
t.relname AS "table",
|
|
62
|
+
i.relname AS "index",
|
|
63
|
+
am.amname AS "method",
|
|
64
|
+
x.indisunique AS "unique",
|
|
65
|
+
ARRAY(
|
|
66
|
+
SELECT a.attname::text
|
|
67
|
+
FROM unnest((x.indkey::int2[])[0:x.indnkeyatts - 1]) WITH ORDINALITY AS k(attnum, ord)
|
|
68
|
+
LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum AND k.attnum > 0
|
|
69
|
+
ORDER BY k.ord
|
|
70
|
+
) AS "keys",
|
|
71
|
+
ARRAY(SELECT o::int FROM unnest(x.indoption::int2[]) WITH ORDINALITY AS u(o, ord) ORDER BY u.ord) AS "options",
|
|
72
|
+
ARRAY(
|
|
73
|
+
SELECT a.attname::text
|
|
74
|
+
FROM unnest((x.indkey::int2[])[x.indnkeyatts:]) WITH ORDINALITY AS k(attnum, ord)
|
|
75
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
76
|
+
ORDER BY k.ord
|
|
77
|
+
) AS "include",
|
|
78
|
+
pg_get_expr(x.indpred, x.indrelid) AS "predicate",
|
|
79
|
+
NOT EXISTS (
|
|
80
|
+
SELECT 1
|
|
81
|
+
FROM unnest((x.indclass::oid[])[0:x.indnkeyatts - 1], (x.indcollation::oid[])[0:x.indnkeyatts - 1],
|
|
82
|
+
(x.indkey::int2[])[0:x.indnkeyatts - 1]) AS k(opclass, coll, attnum)
|
|
83
|
+
JOIN pg_opclass oc ON oc.oid = k.opclass
|
|
84
|
+
LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
85
|
+
WHERE NOT oc.opcdefault OR NULLIF(k.coll, 0) IS DISTINCT FROM NULLIF(a.attcollation, 0)
|
|
86
|
+
) AS "defaultOpclassAndCollation",
|
|
87
|
+
EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = i.oid) AS "constraint",
|
|
88
|
+
x.indisvalid AS "valid"
|
|
89
|
+
FROM pg_index x
|
|
90
|
+
JOIN pg_class i ON i.oid = x.indexrelid
|
|
91
|
+
JOIN pg_class t ON t.oid = x.indrelid
|
|
92
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
93
|
+
JOIN pg_am am ON am.oid = i.relam
|
|
94
|
+
WHERE n.nspname IN (${[...new Set(schemas)].map((schema) => `'${schema.replace(/'/g, "''")}'`).join(", ")})
|
|
95
|
+
AND t.relkind IN ('r', 'p')
|
|
96
|
+
ORDER BY n.nspname, t.relname, i.relname`;
|
|
97
|
+
/** Read the {@link ExistingIndexShape}s of the given schemas. */
|
|
98
|
+
async function readIndexShapes(client, schemas) {
|
|
99
|
+
if (schemas.length === 0) return [];
|
|
100
|
+
const { rows } = await client.query(indexShapesSql(schemas));
|
|
101
|
+
return rows;
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* A predicate with Postgres's own spelling taken out: identifier quotes, the
|
|
105
|
+
* casts it puts on literals (`'live'::text`), parentheses, case, whitespace.
|
|
106
|
+
*/
|
|
107
|
+
function normalizePredicate(text) {
|
|
108
|
+
return text.replace(/::(?:character varying|double precision|time(?:stamp)?(?: with(?:out)? time zone)?|[a-z_][a-z0-9_]*)(?:\[\])?/gi, "").replace(/"/g, "").replace(/[()]/g, "").replace(/\s+/g, " ").trim().toLowerCase();
|
|
109
|
+
}
|
|
110
|
+
/** Whether `shape` is `spec` under another name. */
|
|
111
|
+
function indexMatchesSpec(spec, shape) {
|
|
112
|
+
if (shape.schema !== spec.schema || shape.table !== spec.table) return false;
|
|
113
|
+
if (shape.constraint || !shape.valid || !shape.defaultOpclassAndCollation) return false;
|
|
114
|
+
if (shape.method !== spec.method || shape.unique !== spec.unique) return false;
|
|
115
|
+
if (shape.keys.length !== spec.keys.length) return false;
|
|
116
|
+
const ordered = spec.method === "btree";
|
|
117
|
+
for (let i = 0; i < spec.keys.length; i++) {
|
|
118
|
+
const key = spec.keys[i];
|
|
119
|
+
if (shape.keys[i] === null || shape.keys[i] !== key.column) return false;
|
|
120
|
+
if (!ordered) continue;
|
|
121
|
+
const desc = (shape.options[i] & 1) === 1;
|
|
122
|
+
const nullsFirst = (shape.options[i] & 2) === 2;
|
|
123
|
+
if (desc !== (key.direction === "desc") || nullsFirst !== (key.nulls === "first")) return false;
|
|
124
|
+
}
|
|
125
|
+
if (shape.include.length !== spec.include.length || shape.include.some((column, i) => column !== spec.include[i])) return false;
|
|
126
|
+
if (shape.predicate === null !== (spec.predicate === null)) return false;
|
|
127
|
+
if (shape.predicate !== null && spec.predicate !== null && normalizePredicate(shape.predicate) !== normalizePredicate(renderPredicate(spec.predicate))) return false;
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* The renames that make existing indexes the declared ones: for each spec
|
|
132
|
+
* whose derived name the catalogue does not hold, the first existing index on
|
|
133
|
+
* its table with the same definition — never one carrying a Rebase name (it is
|
|
134
|
+
* some declaration's, or one a removed declaration left for push to drop), and
|
|
135
|
+
* never the same one twice.
|
|
136
|
+
*/
|
|
137
|
+
function planIndexAdoptions(specs, shapes) {
|
|
138
|
+
const held = new Set(shapes.map((shape) => `${shape.schema}.${shape.index}`));
|
|
139
|
+
const taken = /* @__PURE__ */ new Set();
|
|
140
|
+
const adoptions = [];
|
|
141
|
+
for (const spec of specs) {
|
|
142
|
+
if (held.has(`${spec.schema}.${spec.indexName}`)) continue;
|
|
143
|
+
const match = shapes.find((shape) => !taken.has(`${shape.schema}.${shape.index}`) && !isRebaseIndexName(shape.index) && indexMatchesSpec(spec, shape));
|
|
144
|
+
if (!match) continue;
|
|
145
|
+
taken.add(`${match.schema}.${match.index}`);
|
|
146
|
+
held.add(`${spec.schema}.${spec.indexName}`);
|
|
147
|
+
adoptions.push({
|
|
148
|
+
schema: spec.schema,
|
|
149
|
+
table: spec.table,
|
|
150
|
+
from: match.index,
|
|
151
|
+
to: spec.indexName
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
return adoptions;
|
|
155
|
+
}
|
|
156
|
+
var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
157
|
+
/** The `ALTER INDEX … RENAME TO …` for one adoption. */
|
|
158
|
+
function indexAdoptionStatement(adoption) {
|
|
159
|
+
return `ALTER INDEX ${quoteIdent(adoption.schema)}.${quoteIdent(adoption.from)} RENAME TO ${quoteIdent(adoption.to)};`;
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* A migration's `CREATE INDEX` of a declared (Rebase-named) index, written
|
|
163
|
+
* `CREATE INDEX IF NOT EXISTS`. `rebase db migrate` adopts an identical
|
|
164
|
+
* existing index before it applies — renaming it to the declared name — and
|
|
165
|
+
* the migration's own statement then finds it there instead of failing on the
|
|
166
|
+
* name. An index named any other way is left as Atlas wrote it.
|
|
167
|
+
*/
|
|
168
|
+
function declaredIndexesIfNotExists(migrationSql) {
|
|
169
|
+
let rewritten = 0;
|
|
170
|
+
return {
|
|
171
|
+
sql: migrationSql.replace(/\bCREATE\s+(UNIQUE\s+)?INDEX\s+(?!IF\s+NOT\s+EXISTS\b|CONCURRENTLY\b)"([^"]+)"/gi, (statement, unique, name) => {
|
|
172
|
+
if (!isRebaseIndexName(name)) return statement;
|
|
173
|
+
rewritten++;
|
|
174
|
+
return `CREATE ${unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS "${name}"`;
|
|
175
|
+
}),
|
|
176
|
+
rewritten
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
//#endregion
|
|
23
180
|
//#region ../../node_modules/.pnpm/is-plain-obj@4.1.0/node_modules/is-plain-obj/index.js
|
|
24
181
|
function isPlainObject(value) {
|
|
25
182
|
if (typeof value !== "object" || value === null) return false;
|
|
@@ -6191,502 +6348,6 @@ createExeca(mapNode);
|
|
|
6191
6348
|
createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);
|
|
6192
6349
|
var { sendMessage, getOneMessage, getEachMessage, getCancelSignal } = getIpcExport();
|
|
6193
6350
|
//#endregion
|
|
6194
|
-
//#region src/schema/rls-bootstrap-sql.ts
|
|
6195
|
-
var rls_bootstrap_sql_exports = /* @__PURE__ */ __exportAll({
|
|
6196
|
-
DROP_LEGACY_AUTH_SCHEMA_SQL: () => DROP_LEGACY_AUTH_SCHEMA_SQL,
|
|
6197
|
-
LEGACY_AUTH_SCHEMA_CONTENTS_SQL: () => LEGACY_AUTH_SCHEMA_CONTENTS_SQL,
|
|
6198
|
-
LEGACY_RLS_DEPENDENTS_SQL: () => LEGACY_RLS_DEPENDENTS_SQL,
|
|
6199
|
-
LEGACY_RLS_FUNCTION_DEPENDENTS_SQL: () => LEGACY_RLS_FUNCTION_DEPENDENTS_SQL,
|
|
6200
|
-
REQUEST_ROLE_FUNCTION_SQL: () => REQUEST_ROLE_FUNCTION_SQL,
|
|
6201
|
-
RLS_BOOTSTRAP_SQL: () => RLS_BOOTSTRAP_SQL,
|
|
6202
|
-
RLS_BOOTSTRAP_STATEMENTS: () => RLS_BOOTSTRAP_STATEMENTS,
|
|
6203
|
-
dropLegacyAuthSchema: () => dropLegacyAuthSchema,
|
|
6204
|
-
ensureRequestRoleFunction: () => ensureRequestRoleFunction,
|
|
6205
|
-
rlsRuntimeIsCurrent: () => rlsRuntimeIsCurrent
|
|
6206
|
-
});
|
|
6207
|
-
/**
|
|
6208
|
-
* Canonical SQL bootstrap for the RLS helper functions.
|
|
6209
|
-
*
|
|
6210
|
-
* Generated RLS policies reference `rebase.uid()` / `rebase.roles()` /
|
|
6211
|
-
* `rebase.jwt()`, so any SQL stream that can contain policies must be
|
|
6212
|
-
* self-contained: it has to (re)create these helpers first. This matters for
|
|
6213
|
-
* the migration directory in particular — Atlas replays migrations against a
|
|
6214
|
-
* clean dev database where no out-of-band bootstrap has ever run, so a
|
|
6215
|
-
* migration carrying policies without this preamble fails with
|
|
6216
|
-
* "function rebase.uid() does not exist".
|
|
6217
|
-
*
|
|
6218
|
-
* Idempotent (`IF NOT EXISTS` / `OR REPLACE`) so it can be prepended to every
|
|
6219
|
-
* policies block and re-applied freely. The runtime boot path
|
|
6220
|
-
* (`auth/ensure-tables.ts`) creates the same functions under an advisory lock
|
|
6221
|
-
* for HMR-safety; keep the definitions in sync.
|
|
6222
|
-
*
|
|
6223
|
-
* ## Creating the `rebase` schema here is now safe, and required
|
|
6224
|
-
*
|
|
6225
|
-
* It deliberately did not, once. These functions lived in a schema called
|
|
6226
|
-
* `auth`, and the note here read: creating `rebase` would leak it into Atlas's
|
|
6227
|
-
* replayed migration state, and — absent from the desired `schema.sql` — Atlas
|
|
6228
|
-
* would then plan `DROP SCHEMA "rebase" CASCADE`, taking the auth tables with
|
|
6229
|
-
* it. That reasoning still holds; what changed is the second half of it. The
|
|
6230
|
-
* DDL generator now emits `CREATE SCHEMA IF NOT EXISTS "rebase"`
|
|
6231
|
-
* unconditionally, so the schema is always in the desired state and the diff is
|
|
6232
|
-
* empty. (It used to appear only when some collection happened to declare
|
|
6233
|
-
* `schema: "rebase"` — true for the scaffold's users collection, and not a
|
|
6234
|
-
* property anything guaranteed.) `db push` additionally excludes the whole
|
|
6235
|
-
* schema from the declarative apply.
|
|
6236
|
-
*
|
|
6237
|
-
* See `@rebasepro/types`' `rls-functions` for why the functions moved out of
|
|
6238
|
-
* `auth` at all: the short version is that the name was Supabase's, and
|
|
6239
|
-
* `CREATE OR REPLACE FUNCTION auth.uid() RETURNS text` cannot be applied over
|
|
6240
|
-
* Supabase's `RETURNS uuid` — Postgres refuses, and the refusal used to be
|
|
6241
|
-
* swallowed.
|
|
6242
|
-
*/
|
|
6243
|
-
/**
|
|
6244
|
-
* The bootstrap as individual statements.
|
|
6245
|
-
*
|
|
6246
|
-
* Kept as an array because the two consumers need different shapes and only one
|
|
6247
|
-
* of them can take a multi-command string: the migration preamble is written to
|
|
6248
|
-
* a file and replayed by Atlas, but the boot path runs through drizzle, whose
|
|
6249
|
-
* node-postgres handle speaks the extended query protocol and rejects more than
|
|
6250
|
-
* one command per call. Splitting a joined string back apart on `$$;` would be
|
|
6251
|
-
* a parser for a problem that does not need one.
|
|
6252
|
-
*/
|
|
6253
|
-
var RLS_BOOTSTRAP_STATEMENTS = [
|
|
6254
|
-
`CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`,
|
|
6255
|
-
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.uid() RETURNS text AS $$
|
|
6256
|
-
SELECT COALESCE(
|
|
6257
|
-
NULLIF(current_setting('app.uid', true), ''),
|
|
6258
|
-
NULLIF(current_setting('app.user_id', true), '')
|
|
6259
|
-
);
|
|
6260
|
-
$$ LANGUAGE sql STABLE`,
|
|
6261
|
-
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.jwt() RETURNS jsonb AS $$
|
|
6262
|
-
SELECT COALESCE(
|
|
6263
|
-
NULLIF(current_setting('app.jwt', true), ''),
|
|
6264
|
-
'{}'
|
|
6265
|
-
)::jsonb;
|
|
6266
|
-
$$ LANGUAGE sql STABLE`,
|
|
6267
|
-
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.roles() RETURNS text AS $$
|
|
6268
|
-
SELECT COALESCE(NULLIF(current_setting('app.user_roles', true), ''), '');
|
|
6269
|
-
$$ LANGUAGE sql STABLE`,
|
|
6270
|
-
`CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_anonymous() RETURNS boolean AS $$
|
|
6271
|
-
SELECT COALESCE(NULLIF(current_setting('app.is_anonymous', true), ''), 'false')::boolean;
|
|
6272
|
-
$$ LANGUAGE sql STABLE`
|
|
6273
|
-
];
|
|
6274
|
-
/** Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one comparable string. */
|
|
6275
|
-
var describeFunction = (facts) => JSON.stringify([
|
|
6276
|
-
facts.returns.toLowerCase(),
|
|
6277
|
-
facts.language.toLowerCase(),
|
|
6278
|
-
facts.volatility,
|
|
6279
|
-
facts.strict,
|
|
6280
|
-
facts.parallel,
|
|
6281
|
-
facts.securityDefiner,
|
|
6282
|
-
facts.leakproof,
|
|
6283
|
-
facts.cost,
|
|
6284
|
-
facts.hasConfig,
|
|
6285
|
-
facts.body
|
|
6286
|
-
]);
|
|
6287
|
-
/**
|
|
6288
|
-
* What each `CREATE OR REPLACE FUNCTION` in {@link RLS_BOOTSTRAP_STATEMENTS}
|
|
6289
|
-
* would leave in the catalogue, by `schema.name`. Parsed
|
|
6290
|
-
* from the statements themselves, so the two cannot drift; a statement this
|
|
6291
|
-
* does not recognise makes {@link rlsRuntimeIsCurrent} answer "no", and the
|
|
6292
|
-
* bootstrap runs as it always did.
|
|
6293
|
-
*/
|
|
6294
|
-
var expectedRlsFunctions = () => {
|
|
6295
|
-
const expected = /* @__PURE__ */ new Map();
|
|
6296
|
-
for (const statement of RLS_BOOTSTRAP_STATEMENTS) {
|
|
6297
|
-
if (/^CREATE SCHEMA IF NOT EXISTS /.test(statement)) continue;
|
|
6298
|
-
const match = /^CREATE OR REPLACE FUNCTION (\w+)\.(\w+)\(\) RETURNS (\w+) AS \$\$([\s\S]*)\$\$ LANGUAGE (\w+) (IMMUTABLE|STABLE|VOLATILE)$/.exec(statement);
|
|
6299
|
-
if (!match) return void 0;
|
|
6300
|
-
const [, schema, name, returns, body, language, volatility] = match;
|
|
6301
|
-
expected.set(`${schema}.${name}`, describeFunction({
|
|
6302
|
-
returns,
|
|
6303
|
-
language,
|
|
6304
|
-
volatility: volatility[0].toLowerCase(),
|
|
6305
|
-
strict: false,
|
|
6306
|
-
parallel: "u",
|
|
6307
|
-
securityDefiner: false,
|
|
6308
|
-
leakproof: false,
|
|
6309
|
-
cost: 100,
|
|
6310
|
-
hasConfig: false,
|
|
6311
|
-
body
|
|
6312
|
-
}));
|
|
6313
|
-
}
|
|
6314
|
-
return expected;
|
|
6315
|
-
};
|
|
6316
|
-
/**
|
|
6317
|
-
* Whether the `rebase` schema and every RLS helper function are exactly what
|
|
6318
|
-
* {@link RLS_BOOTSTRAP_STATEMENTS} would make them — one catalogue read.
|
|
6319
|
-
*
|
|
6320
|
-
* The boot ran those statements unconditionally, on every boot and on every
|
|
6321
|
-
* source: four `CREATE OR REPLACE FUNCTION`s in a transaction under an
|
|
6322
|
-
* advisory lock. Replacing a function rewrites its `pg_proc` row even when
|
|
6323
|
-
* nothing changed, and every cached plan that inlined it — every plan of every
|
|
6324
|
-
* statement a policy applies to, on every connection — is invalidated by it.
|
|
6325
|
-
* A function that differs in anything `CREATE OR REPLACE` sets (body,
|
|
6326
|
-
* language, volatility, strictness, parallel safety, security, leakproofness,
|
|
6327
|
-
* cost, `SET` options), or is missing, answers `false`, and the statements run
|
|
6328
|
-
* as before.
|
|
6329
|
-
*/
|
|
6330
|
-
async function rlsRuntimeIsCurrent(run) {
|
|
6331
|
-
const expected = expectedRlsFunctions();
|
|
6332
|
-
if (!expected) return false;
|
|
6333
|
-
const rows = await run(`SELECT n.nspname AS schema, p.proname AS name, pg_get_function_identity_arguments(p.oid) AS args,
|
|
6334
|
-
format_type(p.prorettype, NULL) AS returns, l.lanname AS language,
|
|
6335
|
-
p.provolatile::text AS volatility, p.proisstrict AS strict, p.proparallel::text AS parallel,
|
|
6336
|
-
p.prosecdef AS security_definer, p.proleakproof AS leakproof, p.procost AS cost,
|
|
6337
|
-
p.proconfig IS NOT NULL AS has_config, p.prosrc AS body
|
|
6338
|
-
FROM pg_proc p
|
|
6339
|
-
JOIN pg_namespace n ON p.pronamespace = n.oid
|
|
6340
|
-
JOIN pg_language l ON p.prolang = l.oid
|
|
6341
|
-
WHERE (n.nspname, p.proname) IN (${[...expected.keys()].map((key) => key.split(".")).map(([schema, name]) => `('${schema}', '${name}')`).join(", ")})`);
|
|
6342
|
-
const live = /* @__PURE__ */ new Map();
|
|
6343
|
-
for (const row of rows) {
|
|
6344
|
-
if (String(row.args ?? "") !== "") continue;
|
|
6345
|
-
live.set(`${row.schema}.${row.name}`, describeFunction({
|
|
6346
|
-
returns: String(row.returns),
|
|
6347
|
-
language: String(row.language),
|
|
6348
|
-
volatility: String(row.volatility),
|
|
6349
|
-
strict: row.strict === true,
|
|
6350
|
-
parallel: String(row.parallel),
|
|
6351
|
-
securityDefiner: row.security_definer === true,
|
|
6352
|
-
leakproof: row.leakproof === true,
|
|
6353
|
-
cost: Number(row.cost),
|
|
6354
|
-
hasConfig: row.has_config === true,
|
|
6355
|
-
body: String(row.body)
|
|
6356
|
-
}));
|
|
6357
|
-
}
|
|
6358
|
-
for (const [key, definition] of expected) if (live.get(key) !== definition) return false;
|
|
6359
|
-
return true;
|
|
6360
|
-
}
|
|
6361
|
-
/** The same statements as one script, for migration files and raw clients. */
|
|
6362
|
-
var RLS_BOOTSTRAP_SQL = "-- Rebase schema + RLS helper functions (required by the policies below)\n" + RLS_BOOTSTRAP_STATEMENTS.map((s) => `${s};`).join("\n\n") + "\n";
|
|
6363
|
-
/**
|
|
6364
|
-
* The three functions every pre-1.0 release put in `auth`. (The auth tables
|
|
6365
|
-
* lived in `rebase`, or wherever the users collection was declared.)
|
|
6366
|
-
*
|
|
6367
|
-
* `uid()` is matched on either spelling of the principal because Rebase wrote
|
|
6368
|
-
* both. Until v0.10.0 its body was
|
|
6369
|
-
* `SELECT NULLIF(current_setting('app.user_id', true), '')`; v0.10.0 renamed
|
|
6370
|
-
* the GUC to `app.uid` and kept `app.user_id` as a fallback; v0.14.0 moved the
|
|
6371
|
-
* helpers to `rebase`. A database last booted before v0.10.0 therefore holds an
|
|
6372
|
-
* `auth.uid()` that reads `app.user_id` alone — as does anything that copied
|
|
6373
|
-
* that body, the Rebase control plane included — and matching `app.uid` only
|
|
6374
|
-
* left every one of them in place, with the schema around it.
|
|
6375
|
-
*
|
|
6376
|
-
* This is the one place either spelling is listed: the drop and the report of
|
|
6377
|
-
* what it left are both generated from it, so they cannot disagree about which
|
|
6378
|
-
* functions are Rebase's.
|
|
6379
|
-
*/
|
|
6380
|
-
var LEGACY_AUTH_HELPERS = [
|
|
6381
|
-
{
|
|
6382
|
-
name: "uid",
|
|
6383
|
-
returns: "text",
|
|
6384
|
-
reads: ["app.uid", "app.user_id"]
|
|
6385
|
-
},
|
|
6386
|
-
{
|
|
6387
|
-
name: "jwt",
|
|
6388
|
-
returns: "jsonb",
|
|
6389
|
-
reads: ["app.jwt"]
|
|
6390
|
-
},
|
|
6391
|
-
{
|
|
6392
|
-
name: "roles",
|
|
6393
|
-
returns: "text",
|
|
6394
|
-
reads: ["app.user_roles"]
|
|
6395
|
-
}
|
|
6396
|
-
];
|
|
6397
|
-
/**
|
|
6398
|
-
* `pg_proc p` has a Rebase helper's name, arity and result type: what
|
|
6399
|
-
* `CREATE OR REPLACE` would have left, whatever the body.
|
|
6400
|
-
*
|
|
6401
|
-
* Two things that share that shape are excluded outright: a body reading
|
|
6402
|
-
* `request.jwt` (Supabase's helpers and anything modelled on them) and a
|
|
6403
|
-
* function an extension installed (`pg_session_jwt` puts an `auth.jwt()
|
|
6404
|
-
* RETURNS jsonb` in the same schema).
|
|
6405
|
-
*/
|
|
6406
|
-
var isLegacyHelperShaped = (helper) => `(
|
|
6407
|
-
p.proname = '${helper.name}' AND p.pronargs = 0
|
|
6408
|
-
AND pg_get_function_result(p.oid) = '${helper.returns}'
|
|
6409
|
-
AND strpos(p.prosrc, 'request.jwt') = 0
|
|
6410
|
-
AND NOT EXISTS (
|
|
6411
|
-
SELECT 1 FROM pg_depend e
|
|
6412
|
-
WHERE e.classid = 'pg_proc'::regclass AND e.objid = p.oid AND e.deptype = 'e'
|
|
6413
|
-
))`;
|
|
6414
|
-
/** `pg_proc p` is a helper Rebase wrote: its shape, and a body reading one of its GUCs. */
|
|
6415
|
-
var isLegacyHelper = (helper) => `${isLegacyHelperShaped(helper)}
|
|
6416
|
-
AND (${helper.reads.map((guc) => `strpos(p.prosrc, '${guc}') > 0`).join(" OR ")})`;
|
|
6417
|
-
/**
|
|
6418
|
-
* Removes the pre-1.0 `auth` schema, but only when Rebase is what put it there.
|
|
6419
|
-
*
|
|
6420
|
-
* ## Why this is safe against a Supabase database
|
|
6421
|
-
*
|
|
6422
|
-
* Two independent guards, and both have to pass:
|
|
6423
|
-
*
|
|
6424
|
-
* 1. **Each function is identified before it is dropped.** Ours returns `text`
|
|
6425
|
-
* and reads the `app.uid` or `app.user_id` GUC; Supabase's returns `uuid`
|
|
6426
|
-
* and reads `request.jwt.claims`. Nothing is dropped on a signature we did
|
|
6427
|
-
* not write, so a Supabase database — where our `CREATE OR REPLACE` could
|
|
6428
|
-
* never have succeeded in the first place, Postgres refusing to change a
|
|
6429
|
-
* return type — matches nothing and this is a no-op. See
|
|
6430
|
-
* {@link LEGACY_AUTH_HELPERS} for exactly what is matched.
|
|
6431
|
-
* 2. **`DROP SCHEMA … RESTRICT`**, never CASCADE. If anything else at all still
|
|
6432
|
-
* lives in `auth` (Supabase's `users` table, its other helpers), the drop
|
|
6433
|
-
* fails and the schema stays. CASCADE here would be unrecoverable.
|
|
6434
|
-
*
|
|
6435
|
-
* ## Why it cannot run too early
|
|
6436
|
-
*
|
|
6437
|
-
* Postgres records a dependency from every RLS policy to the functions its body
|
|
6438
|
-
* calls, so `DROP FUNCTION auth.uid()` fails for as long as a single policy
|
|
6439
|
-
* still references it. That is the interlock, and it is load-bearing: the drop
|
|
6440
|
-
* can only succeed once every policy has been recompiled to \`rebase.uid()\`.
|
|
6441
|
-
* Callers therefore run this *after* applying policies, and treat a failure as
|
|
6442
|
-
* "not yet — try again next boot" rather than as an error.
|
|
6443
|
-
*/
|
|
6444
|
-
var DROP_LEGACY_AUTH_SCHEMA_SQL = `
|
|
6445
|
-
DO $rebase_drop_legacy$
|
|
6446
|
-
DECLARE
|
|
6447
|
-
dropped_any boolean := false;
|
|
6448
|
-
BEGIN
|
|
6449
|
-
-- Each function is matched on its own result type and body, so a schema
|
|
6450
|
-
-- that merely shares the name keeps everything it has.
|
|
6451
|
-
${LEGACY_AUTH_HELPERS.map((helper) => ` IF EXISTS (
|
|
6452
|
-
SELECT 1 FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
6453
|
-
WHERE n.nspname = '${LEGACY_RLS_SCHEMA}' AND ${isLegacyHelper(helper)}
|
|
6454
|
-
) THEN
|
|
6455
|
-
DROP FUNCTION ${LEGACY_RLS_SCHEMA}.${helper.name}();
|
|
6456
|
-
dropped_any := true;
|
|
6457
|
-
END IF;`).join("\n\n")}
|
|
6458
|
-
|
|
6459
|
-
-- RESTRICT: only an empty schema goes. Anything else in there — including a
|
|
6460
|
-
-- Supabase installation left untouched above — keeps it. Swallowed so the
|
|
6461
|
-
-- helpers dropped above stay dropped; dropLegacyAuthSchema looks afterwards
|
|
6462
|
-
-- and says what is left.
|
|
6463
|
-
IF dropped_any THEN
|
|
6464
|
-
BEGIN
|
|
6465
|
-
EXECUTE 'DROP SCHEMA ${LEGACY_RLS_SCHEMA} RESTRICT';
|
|
6466
|
-
EXCEPTION WHEN OTHERS THEN
|
|
6467
|
-
NULL;
|
|
6468
|
-
END;
|
|
6469
|
-
END IF;
|
|
6470
|
-
END
|
|
6471
|
-
$rebase_drop_legacy$;
|
|
6472
|
-
`;
|
|
6473
|
-
/**
|
|
6474
|
-
* What the `auth` schema holds, one row per object keeping it alive.
|
|
6475
|
-
*
|
|
6476
|
-
* No rows: the schema does not exist. A single row with a `null` object: it
|
|
6477
|
-
* exists and is empty. Read from the namespace entries in `pg_depend`, which
|
|
6478
|
-
* are what `DROP SCHEMA … RESTRICT` itself consults — minus whatever goes with
|
|
6479
|
-
* its owner (a serial's sequence, an identity column's), which Postgres does not
|
|
6480
|
-
* name either.
|
|
6481
|
-
*/
|
|
6482
|
-
var LEGACY_AUTH_SCHEMA_CONTENTS_SQL = `
|
|
6483
|
-
SELECT pg_describe_object(d.classid, d.objid, d.objsubid) AS object,
|
|
6484
|
-
CASE
|
|
6485
|
-
WHEN d.classid <> 'pg_proc'::regclass THEN NULL
|
|
6486
|
-
WHEN EXISTS (
|
|
6487
|
-
SELECT 1 FROM pg_proc p
|
|
6488
|
-
WHERE p.oid = d.objid
|
|
6489
|
-
AND (${LEGACY_AUTH_HELPERS.map((helper) => `(${isLegacyHelper(helper)})`).join(" OR ")})
|
|
6490
|
-
) THEN 'ours'
|
|
6491
|
-
WHEN EXISTS (
|
|
6492
|
-
SELECT 1 FROM pg_proc p
|
|
6493
|
-
WHERE p.oid = d.objid
|
|
6494
|
-
AND (${LEGACY_AUTH_HELPERS.map(isLegacyHelperShaped).join(" OR ")})
|
|
6495
|
-
) THEN 'lookalike'
|
|
6496
|
-
END AS helper
|
|
6497
|
-
FROM pg_namespace n
|
|
6498
|
-
LEFT JOIN pg_depend d
|
|
6499
|
-
ON d.refclassid = 'pg_namespace'::regclass AND d.refobjid = n.oid AND d.deptype = 'n'
|
|
6500
|
-
AND NOT EXISTS (
|
|
6501
|
-
SELECT 1 FROM pg_depend o
|
|
6502
|
-
WHERE o.classid = d.classid AND o.objid = d.objid AND o.deptype IN ('a', 'i')
|
|
6503
|
-
)
|
|
6504
|
-
WHERE n.nspname = '${LEGACY_RLS_SCHEMA}'
|
|
6505
|
-
ORDER BY helper NULLS LAST, object
|
|
6506
|
-
`;
|
|
6507
|
-
/**
|
|
6508
|
-
* Policies whose body still calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
|
|
6509
|
-
*
|
|
6510
|
-
* Postgres will not drop a function a policy depends on, so this is exactly the
|
|
6511
|
-
* set standing between a database and losing the legacy schema. Rebase's own
|
|
6512
|
-
* policies leave the list on the next push or boot, when they are recompiled —
|
|
6513
|
-
* anything still here afterwards is hand-written, will never be recompiled by
|
|
6514
|
-
* anybody, and is the reason the drop keeps being skipped. Silence there would
|
|
6515
|
-
* leave an operator staring at a schema the release notes said would go.
|
|
6516
|
-
*/
|
|
6517
|
-
var LEGACY_RLS_DEPENDENTS_SQL = `
|
|
6518
|
-
SELECT n.nspname AS schema, c.relname AS "table", p.polname AS policy
|
|
6519
|
-
FROM pg_policy p
|
|
6520
|
-
JOIN pg_class c ON c.oid = p.polrelid
|
|
6521
|
-
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
6522
|
-
WHERE pg_get_expr(p.polqual, p.polrelid) ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
|
|
6523
|
-
OR pg_get_expr(p.polwithcheck, p.polrelid) ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
|
|
6524
|
-
ORDER BY 1, 2, 3
|
|
6525
|
-
`;
|
|
6526
|
-
/**
|
|
6527
|
-
* Functions whose body calls `auth.uid()` / `auth.roles()` / `auth.jwt()`.
|
|
6528
|
-
*
|
|
6529
|
-
* This is the half `DROP FUNCTION ... RESTRICT` cannot see, and the reason it
|
|
6530
|
-
* needs its own query. Postgres records a dependency for a *policy* that calls a
|
|
6531
|
-
* function, which is why the drop is safe against the policies above — but a
|
|
6532
|
-
* `LANGUAGE sql` function whose body is a **string literal** is not parsed when
|
|
6533
|
-
* it is created, so nothing is recorded and `RESTRICT` has nothing to refuse on.
|
|
6534
|
-
* The drop succeeds and the caller is left pointing at a function that no longer
|
|
6535
|
-
* exists, which fails at *query* time rather than at boot.
|
|
6536
|
-
*
|
|
6537
|
-
* A downstream project building on these helpers is not hypothetical: the Rebase
|
|
6538
|
-
* control plane defined `auth.is_org_member(uuid)` and `auth.is_org_admin(uuid)`
|
|
6539
|
-
* in this very schema, each calling `auth.uid()` in a string body, and eleven of
|
|
6540
|
-
* its row-level-security policies went through them. Every one of those would
|
|
6541
|
-
* have started failing the first time a recompile left no policy referencing
|
|
6542
|
-
* `auth.uid()` directly — the drop's own precondition. (Its migration 0065 has
|
|
6543
|
-
* since moved both to `public`, calling `rebase.uid()`.)
|
|
6544
|
-
*
|
|
6545
|
-
* Matching on the body text is the only option available, and it is deliberately
|
|
6546
|
-
* broad: a false positive costs a schema that stays one release longer and says
|
|
6547
|
-
* why, while a false negative costs somebody their policies.
|
|
6548
|
-
*/
|
|
6549
|
-
var LEGACY_RLS_FUNCTION_DEPENDENTS_SQL = `
|
|
6550
|
-
SELECT n.nspname AS schema, p.proname AS function
|
|
6551
|
-
FROM pg_proc p
|
|
6552
|
-
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
6553
|
-
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
6554
|
-
AND NOT (n.nspname = '${LEGACY_RLS_SCHEMA}' AND p.proname IN ('uid', 'jwt', 'roles'))
|
|
6555
|
-
AND p.prosrc ~* '\\m${LEGACY_RLS_SCHEMA}\\.(uid|jwt|roles)\\s*\\('
|
|
6556
|
-
ORDER BY 1, 2
|
|
6557
|
-
`;
|
|
6558
|
-
/**
|
|
6559
|
-
* Retire the pre-1.0 `auth` schema, reporting what is holding it back.
|
|
6560
|
-
*
|
|
6561
|
-
* The shared implementation behind the CLI's post-push step and the runtime's
|
|
6562
|
-
* post-policy step. Both used to just fire {@link DROP_LEGACY_AUTH_SCHEMA_SQL}
|
|
6563
|
-
* and swallow whatever came back, which is right for the ordinary case — a
|
|
6564
|
-
* table not recompiled *yet* — and wrong for the one that never resolves: a
|
|
6565
|
-
* hand-written policy nothing will ever rewrite. Then the schema stays forever
|
|
6566
|
-
* and nothing ever says why.
|
|
6567
|
-
*
|
|
6568
|
-
* The drop itself had the same blind spot. A helper it did not recognise as
|
|
6569
|
-
* Rebase's stayed, and so did anything else in the schema, behind a
|
|
6570
|
-
* `DROP SCHEMA … RESTRICT` whose failure is swallowed so the helpers it did
|
|
6571
|
-
* drop stay dropped. The control plane's `auth.uid()` was one such: it read
|
|
6572
|
-
* `app.user_id` alone, the drop looked for `app.uid`, and the schema stayed
|
|
6573
|
-
* with no word said. So the schema is read twice. Before, so that one with no
|
|
6574
|
-
* Rebase helper in it is left alone: one already gone, as on every boot after
|
|
6575
|
-
* the drop, or one that was never Rebase's, like Supabase's — whose own
|
|
6576
|
-
* policies the checks below would otherwise report as blockers. After, to name
|
|
6577
|
-
* whatever is still there.
|
|
6578
|
-
*/
|
|
6579
|
-
async function dropLegacyAuthSchema(run, report) {
|
|
6580
|
-
let before;
|
|
6581
|
-
try {
|
|
6582
|
-
before = sqlRows(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));
|
|
6583
|
-
} catch {
|
|
6584
|
-
return;
|
|
6585
|
-
}
|
|
6586
|
-
if (!before.some((o) => o.helper !== null)) return;
|
|
6587
|
-
if (!before.some((o) => o.helper === "ours")) {
|
|
6588
|
-
report.warn(describeLegacyAuthLeftovers(before, void 0));
|
|
6589
|
-
return;
|
|
6590
|
-
}
|
|
6591
|
-
let blockers;
|
|
6592
|
-
try {
|
|
6593
|
-
blockers = sqlRows(await run(LEGACY_RLS_DEPENDENTS_SQL));
|
|
6594
|
-
} catch {
|
|
6595
|
-
return;
|
|
6596
|
-
}
|
|
6597
|
-
if (blockers.length > 0) {
|
|
6598
|
-
report.warn(`The pre-1.0 \`${LEGACY_RLS_SCHEMA}\` schema cannot be removed yet: ${blockers.length} ${blockers.length === 1 ? "policy still calls" : "policies still call"} \`${LEGACY_RLS_SCHEMA}.uid()\` and friends, and Postgres will not drop a function a policy depends on. Rebase's own policies are rewritten automatically — anything listed here is hand-written SQL that has to be updated to \`${REBASE_SCHEMA}.uid()\` by hand, after which the schema goes on its own:\n` + blockers.map((b) => ` • ${b.schema}.${b.table} → "${b.policy}"`).join("\n"));
|
|
6599
|
-
return;
|
|
6600
|
-
}
|
|
6601
|
-
let borrowers;
|
|
6602
|
-
try {
|
|
6603
|
-
borrowers = sqlRows(await run(LEGACY_RLS_FUNCTION_DEPENDENTS_SQL));
|
|
6604
|
-
} catch {
|
|
6605
|
-
return;
|
|
6606
|
-
}
|
|
6607
|
-
if (borrowers.length > 0) {
|
|
6608
|
-
report.warn(`The pre-1.0 \`${LEGACY_RLS_SCHEMA}\` schema cannot be removed yet: ${borrowers.length} ${borrowers.length === 1 ? "function calls" : "functions call"} \`${LEGACY_RLS_SCHEMA}.uid()\` and friends from its own body. Postgres records no dependency for that — a SQL body written as a string literal is never parsed — so dropping the helpers would leave these pointing at nothing, and they would fail when a query reached them rather than now. Repoint them at \`${REBASE_SCHEMA}.uid()\`, after which the schema goes on its own:\n` + borrowers.map((b) => ` • ${b.schema}.${b.function}()`).join("\n"));
|
|
6609
|
-
return;
|
|
6610
|
-
}
|
|
6611
|
-
let failure;
|
|
6612
|
-
try {
|
|
6613
|
-
await run(DROP_LEGACY_AUTH_SCHEMA_SQL);
|
|
6614
|
-
} catch (err) {
|
|
6615
|
-
const detail = err instanceof Error && "detail" in err && typeof err.detail === "string" ? err.detail : "";
|
|
6616
|
-
failure = (err instanceof Error ? err.message : String(err)) + (detail ? ` (${detail.replace(/\n/g, "; ")})` : "");
|
|
6617
|
-
}
|
|
6618
|
-
let left;
|
|
6619
|
-
try {
|
|
6620
|
-
left = sqlRows(await run(LEGACY_AUTH_SCHEMA_CONTENTS_SQL));
|
|
6621
|
-
} catch {
|
|
6622
|
-
if (failure) report.info(`Left the \`${LEGACY_RLS_SCHEMA}\` schema in place: ${failure}`);
|
|
6623
|
-
return;
|
|
6624
|
-
}
|
|
6625
|
-
if (left.length === 0) return;
|
|
6626
|
-
report.warn(describeLegacyAuthLeftovers(left, failure));
|
|
6627
|
-
}
|
|
6628
|
-
/** At most this many objects are named; a schema this full is plainly in use. */
|
|
6629
|
-
var MAX_LEFTOVERS_NAMED = 20;
|
|
6630
|
-
/**
|
|
6631
|
-
* The warning for an `auth` schema the drop left standing.
|
|
6632
|
-
*
|
|
6633
|
-
* Said once for objects that are not Rebase's: on the next boot the schema holds
|
|
6634
|
-
* no helper, so {@link dropLegacyAuthSchema} leaves it alone — it is somebody
|
|
6635
|
-
* else's schema by then. A helper that is still there, Rebase's or a lookalike,
|
|
6636
|
-
* keeps it said on every boot until it goes.
|
|
6637
|
-
*/
|
|
6638
|
-
function describeLegacyAuthLeftovers(left, failure) {
|
|
6639
|
-
const schema = LEGACY_RLS_SCHEMA;
|
|
6640
|
-
const objects = left.filter((o) => o.object !== null);
|
|
6641
|
-
if (objects.length === 0) return `The pre-1.0 \`${schema}\` schema is empty, but this connection could not drop it — most likely because it does not own the schema. Run \`DROP SCHEMA ${schema};\` as its owner.`;
|
|
6642
|
-
const why = failure ? `dropping Rebase's old helpers from it failed: ${failure}.` : "`DROP SCHEMA … RESTRICT` refuses a schema that is not empty, and Rebase drops only the helpers it can tell are its own.";
|
|
6643
|
-
const lines = objects.slice(0, MAX_LEFTOVERS_NAMED).map((o) => o.helper === "ours" ? ` • ${o.object} — Rebase's old helper, which could not be dropped` : o.helper === "lookalike" ? ` • ${o.object} — named and typed like Rebase's old helper, but no release wrote this body, so it was left alone; drop it by hand if nothing of yours calls it` : ` • ${o.object}`);
|
|
6644
|
-
if (objects.length > MAX_LEFTOVERS_NAMED) lines.push(` • …and ${objects.length - MAX_LEFTOVERS_NAMED} more`);
|
|
6645
|
-
return `The pre-1.0 \`${schema}\` schema is still here: ${why} Still in it:\n` + lines.join("\n") + `
|
|
6646
|
-
Anything of yours can stay where it is — Rebase no longer uses this schema — or move out with \`ALTER … SET SCHEMA\`. Once the schema is empty, \`DROP SCHEMA ${schema};\` removes it.`;
|
|
6647
|
-
}
|
|
6648
|
-
/**
|
|
6649
|
-
* `rebase.is_request_role(role)` — is `role` one of the roles this database's
|
|
6650
|
-
* requests run as? The predicate `rls.policyTarget: "requestRole"` ANDs into
|
|
6651
|
-
* every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with
|
|
6652
|
-
* `current_user`.
|
|
6653
|
-
*
|
|
6654
|
-
* SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,
|
|
6655
|
-
* which the request roles cannot read. That is also why the caller's role is
|
|
6656
|
-
* an argument: inside the function `current_user` is its owner. The body is
|
|
6657
|
-
* dynamic SQL so the function can be created before the table exists — in
|
|
6658
|
-
* Atlas's replay of the migrations, for one. With nothing recorded the answer
|
|
6659
|
-
* is `rebase_user`, as everywhere else.
|
|
6660
|
-
*
|
|
6661
|
-
* Created only for a project that asks for `policyTarget: "requestRole"`, so
|
|
6662
|
-
* every other project's migrations and boot are exactly what they were.
|
|
6663
|
-
*/
|
|
6664
|
-
var REQUEST_ROLE_FUNCTION_SQL = `CREATE OR REPLACE FUNCTION ${REBASE_SCHEMA}.is_request_role(role_name text) RETURNS boolean AS $$
|
|
6665
|
-
DECLARE
|
|
6666
|
-
request_roles text[];
|
|
6667
|
-
BEGIN
|
|
6668
|
-
IF to_regclass('"${REBASE_SCHEMA}"."schema_meta"') IS NOT NULL THEN
|
|
6669
|
-
EXECUTE 'SELECT string_to_array(value, '','') FROM "${REBASE_SCHEMA}"."schema_meta" WHERE key = ''request_roles'''
|
|
6670
|
-
INTO request_roles;
|
|
6671
|
-
END IF;
|
|
6672
|
-
RETURN role_name = ANY(COALESCE(request_roles, ARRAY['rebase_user']));
|
|
6673
|
-
END
|
|
6674
|
-
$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog`;
|
|
6675
|
-
/**
|
|
6676
|
-
* Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body
|
|
6677
|
-
* differs — replacing an unchanged function would still invalidate every
|
|
6678
|
-
* cached plan of every policy that calls it.
|
|
6679
|
-
*/
|
|
6680
|
-
async function ensureRequestRoleFunction(run) {
|
|
6681
|
-
const body = /AS \$\$([\s\S]*)\$\$ LANGUAGE/.exec(REQUEST_ROLE_FUNCTION_SQL)?.[1];
|
|
6682
|
-
const [live] = await run(`SELECT p.prosrc AS body FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
6683
|
-
WHERE n.nspname = '${REBASE_SCHEMA}' AND p.proname = 'is_request_role'`);
|
|
6684
|
-
if (live && String(live.body) === body) return;
|
|
6685
|
-
const [schema] = await run(`SELECT to_regnamespace('${REBASE_SCHEMA}') IS NOT NULL AS present`);
|
|
6686
|
-
if (schema?.present !== true) await run(`CREATE SCHEMA IF NOT EXISTS ${REBASE_SCHEMA}`);
|
|
6687
|
-
await run(REQUEST_ROLE_FUNCTION_SQL);
|
|
6688
|
-
}
|
|
6689
|
-
//#endregion
|
|
6690
6351
|
//#region src/cli-flags.ts
|
|
6691
6352
|
var import_arg = /* @__PURE__ */ __toESM(require_arg(), 1);
|
|
6692
6353
|
/**
|
|
@@ -7283,6 +6944,6 @@ async function latestRecordedMigration(databaseUrl) {
|
|
|
7283
6944
|
});
|
|
7284
6945
|
}
|
|
7285
6946
|
//#endregion
|
|
7286
|
-
export {
|
|
6947
|
+
export { declaredIndexesIfNotExists as C, readIndexShapes as E, execa as S, planIndexAdoptions as T, closestWord as _, migrationVersionOf as a, parseDriverLine as b, isDriverDbSubcommand as c, branchNameIn as d, branchSourceIn as f, assertKnownFlags as g, RELAYED_FLAGS as h, latestRecordedMigration as i, backupActionOf as l, unexpectedBranchArgs as m, compareMigrationVersions as n, planBaseline as o, resolveBranchSwitches as p, describeBaselinePlan as r, DRIVER_DB_SUBCOMMANDS as s, baselineVersionProblem as t, assertKnownBranchFlags as u, collectionsPathIn as v, indexAdoptionStatement as w, resolveDriverSwitches as x, parseCommandFlags as y };
|
|
7287
6948
|
|
|
7288
|
-
//# sourceMappingURL=migrate-baseline-
|
|
6949
|
+
//# sourceMappingURL=migrate-baseline-CmWXL7qx.js.map
|