@rebasepro/server-postgres 0.29.0-canary.g0e3a0e7 → 0.29.1
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-BPssiD8_.js → BranchService-BIIBF5ZL.js} +3 -3
- package/dist/{BranchService-BPssiD8_.js.map → BranchService-BIIBF5ZL.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +105 -9
- package/dist/PostgresBootstrapper.d.ts +14 -0
- package/dist/{backup-cli-C1wcj-rc.js → backup-cli-QcOpmRpQ.js} +3 -3
- package/dist/{backup-cli-C1wcj-rc.js.map → backup-cli-QcOpmRpQ.js.map} +1 -1
- package/dist/{boot-ddl-CIGoIGcC.js → boot-ddl-BSNpEUOS.js} +2 -2
- package/dist/{boot-ddl-CIGoIGcC.js.map → boot-ddl-BSNpEUOS.js.map} +1 -1
- package/dist/{cli-console-CJLtH58M.js → cli-console-DTsm96lW.js} +6 -6
- package/dist/{cli-console-CJLtH58M.js.map → cli-console-DTsm96lW.js.map} +1 -1
- package/dist/{cli-errors-DYets7cp.js → cli-errors-DwqFRIWz.js} +69 -6
- package/dist/cli-errors-DwqFRIWz.js.map +1 -0
- package/dist/cli-helpers.d.ts +10 -0
- package/dist/cli.js +90 -44
- package/dist/cli.js.map +1 -1
- package/dist/{connection-CcYqncW5.js → connection-COuS5Fm-.js} +15 -2
- package/dist/connection-COuS5Fm-.js.map +1 -0
- package/dist/connection.d.ts +6 -0
- package/dist/database-preflight-D5JtPt8i.js +151 -0
- package/dist/database-preflight-D5JtPt8i.js.map +1 -0
- package/dist/{databasePoolManager-XmhMczz0.js → databasePoolManager-7hXVurmG.js} +2 -2
- package/dist/{databasePoolManager-XmhMczz0.js.map → databasePoolManager-7hXVurmG.js.map} +1 -1
- package/dist/db-subcommands.d.ts +1 -1
- package/dist/{deferred-index-build-BwH6k1Og.js → deferred-index-build-B8feKnUj.js} +12 -8
- package/dist/deferred-index-build-B8feKnUj.js.map +1 -0
- package/dist/{doctor-TJApVglQ.js → doctor-BaR11xUe.js} +20 -6
- package/dist/doctor-BaR11xUe.js.map +1 -0
- package/dist/{ensure-collection-policies-f0LIwiwp.js → ensure-collection-policies-85HiG-k1.js} +8 -8
- package/dist/{ensure-collection-policies-f0LIwiwp.js.map → ensure-collection-policies-85HiG-k1.js.map} +1 -1
- package/dist/{ensure-collection-tables-DvaCEy6X.js → ensure-collection-tables-DR_WcxLA.js} +20 -9
- package/dist/ensure-collection-tables-DR_WcxLA.js.map +1 -0
- package/dist/{ensure-tables-CF-8zgYA.js → ensure-tables-Dh5UP_Zs.js} +4 -4
- package/dist/{ensure-tables-CF-8zgYA.js.map → ensure-tables-Dh5UP_Zs.js.map} +1 -1
- package/dist/{enum-labels-kept-DAbJ_IIl.js → enum-labels-kept-DSU8lAnd.js} +3 -3
- package/dist/{enum-labels-kept-DAbJ_IIl.js.map → enum-labels-kept-DSU8lAnd.js.map} +1 -1
- package/dist/{generate-drizzle-schema-BAIp9nKT.js → generate-drizzle-schema-5spbTyQ6.js} +2 -2
- package/dist/{generate-drizzle-schema-BAIp9nKT.js.map → generate-drizzle-schema-5spbTyQ6.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js → generate-drizzle-schema-logic-C5FB7Fpo.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-CVRmZjP3.js.map → generate-drizzle-schema-logic-C5FB7Fpo.js.map} +1 -1
- package/dist/{generate-files-DutUrsSS.js → generate-files-Bl3_D_oP.js} +11 -4
- package/dist/generate-files-Bl3_D_oP.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js → generate-postgres-ddl-logic-BC3JA93M.js} +11 -4
- package/dist/{generate-postgres-ddl-logic-0rbAqwYT.js.map → generate-postgres-ddl-logic-BC3JA93M.js.map} +1 -1
- package/dist/{generated-schema-diff-ChFg6UxI.js → generated-schema-diff-Jm93vyJB.js} +29 -6
- package/dist/generated-schema-diff-Jm93vyJB.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.es.js +22 -14
- package/dist/index.es.js.map +1 -1
- package/dist/{migrate-baseline-DPawvckr.js → migrate-baseline-BfHmq3vN.js} +49 -4
- package/dist/{migrate-baseline-DPawvckr.js.map → migrate-baseline-BfHmq3vN.js.map} +1 -1
- package/dist/{migrate-policy-stamps-CdljD_y1.js → migrate-policy-stamps-B4k1ggma.js} +7 -7
- package/dist/{migrate-policy-stamps-CdljD_y1.js.map → migrate-policy-stamps-B4k1ggma.js.map} +1 -1
- package/dist/{open-rebase-DvmKIu7q.js → open-rebase-CiO_sjMT.js} +1574 -195
- package/dist/open-rebase-CiO_sjMT.js.map +1 -0
- package/dist/open-rebase.d.ts +6 -1
- package/dist/{pg-error-utils-BIHfsGZL.js → pg-error-utils-D1Nc0UML.js} +2 -2
- package/dist/{pg-error-utils-BIHfsGZL.js.map → pg-error-utils-D1Nc0UML.js.map} +1 -1
- package/dist/pipelined-transaction.d.ts +131 -0
- package/dist/{plan-schema-DMVh77yb.js → plan-schema-BYxOzflz.js} +147 -8
- package/dist/plan-schema-BYxOzflz.js.map +1 -0
- package/dist/{policy-drift-0Cp4Lc0x.js → policy-drift-DKuTJHfc.js} +2 -2
- package/dist/{policy-drift-0Cp4Lc0x.js.map → policy-drift-DKuTJHfc.js.map} +1 -1
- package/dist/{push-index-prebuild-C6wKdjYV.js → push-index-prebuild-bqXimSZz.js} +4 -4
- package/dist/{push-index-prebuild-C6wKdjYV.js.map → push-index-prebuild-bqXimSZz.js.map} +1 -1
- package/dist/{push-kept-defaults-BSqPzp0T.js → push-kept-defaults-CN9R8cHf.js} +2 -2
- package/dist/{push-kept-defaults-BSqPzp0T.js.map → push-kept-defaults-CN9R8cHf.js.map} +1 -1
- package/dist/{push-legacy-renames-BFF72tHG.js → push-legacy-renames-CU_UYPbz.js} +4 -4
- package/dist/{push-legacy-renames-BFF72tHG.js.map → push-legacy-renames-CU_UYPbz.js.map} +1 -1
- package/dist/{push-policy-plan-lOTPeQ1u.js → push-policy-plan-JcyK94bc.js} +4 -4
- package/dist/{push-policy-plan-lOTPeQ1u.js.map → push-policy-plan-JcyK94bc.js.map} +1 -1
- package/dist/{render-ddl-NpPPDACz.js → render-ddl-DCdVP-pQ.js} +95 -4
- package/dist/render-ddl-DCdVP-pQ.js.map +1 -0
- package/dist/request-role-cli-DSdRtvgH.js +260 -0
- package/dist/request-role-cli-DSdRtvgH.js.map +1 -0
- package/dist/request-role-cli.d.ts +86 -0
- package/dist/request-role-migration-D9BZ5Uba.js +150 -0
- package/dist/request-role-migration-D9BZ5Uba.js.map +1 -0
- package/dist/rls-enforcement-BO618rnr.js +992 -0
- package/dist/rls-enforcement-BO618rnr.js.map +1 -0
- package/dist/rls-settings-De5NoHHy.js +211 -0
- package/dist/rls-settings-De5NoHHy.js.map +1 -0
- package/dist/schema/doctor-cli.js +144 -6
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +27 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-files.d.ts +2 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +6 -0
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +2 -2
- package/dist/schema/introspect-runtime.d.ts +10 -1
- package/dist/schema/plan/diff-plan.d.ts +6 -1
- package/dist/schema/plan/plan-schema.d.ts +9 -1
- package/dist/schema/plan/render-ddl.d.ts +32 -1
- package/dist/schema/plan/tenant-keep-trigger.d.ts +9 -0
- package/dist/schema/plan/types.d.ts +39 -0
- package/dist/schema/plan/updated-at-trigger.d.ts +1 -1
- package/dist/schema/plan/view-names.d.ts +6 -0
- package/dist/schema/rls-bootstrap-sql.d.ts +23 -0
- package/dist/security/caller-sql-columns.d.ts +60 -0
- package/dist/security/caller-sql.d.ts +8 -0
- package/dist/security/database-preflight.d.ts +24 -0
- package/dist/security/request-role-migration.d.ts +36 -0
- package/dist/security/rls-enforcement.d.ts +201 -20
- package/dist/security/rls-settings.d.ts +177 -0
- package/dist/services/FetchService.d.ts +12 -12
- package/dist/services/PersistService.d.ts +59 -0
- package/dist/services/collection-helpers.d.ts +3 -1
- package/dist/services/dataService.d.ts +2 -0
- package/dist/services/realtimeService.d.ts +3 -0
- package/dist/services/view-access.d.ts +21 -0
- package/dist/view-names-Dscp6--B.js +24 -0
- package/dist/view-names-Dscp6--B.js.map +1 -0
- package/dist/{websocket-CCJnghvG.js → websocket-B33YjKhs.js} +3 -3
- package/dist/{websocket-CCJnghvG.js.map → websocket-B33YjKhs.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-errors-DYets7cp.js.map +0 -1
- package/dist/connection-CcYqncW5.js.map +0 -1
- package/dist/deferred-index-build-BwH6k1Og.js.map +0 -1
- package/dist/doctor-TJApVglQ.js.map +0 -1
- package/dist/ensure-collection-tables-DvaCEy6X.js.map +0 -1
- package/dist/generate-files-DutUrsSS.js.map +0 -1
- package/dist/generated-schema-diff-ChFg6UxI.js.map +0 -1
- package/dist/open-rebase-DvmKIu7q.js.map +0 -1
- package/dist/plan-schema-DMVh77yb.js.map +0 -1
- package/dist/render-ddl-NpPPDACz.js.map +0 -1
- package/dist/rls-enforcement-BOHuHVlc.js +0 -502
- package/dist/rls-enforcement-BOHuHVlc.js.map +0 -1
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from "module";
|
|
3
3
|
__createRequire(import.meta.url);
|
|
4
4
|
import { a as buildSearchColumnSpec } from "../search-column-BM-GV6vH.js";
|
|
5
|
-
import { a as diagnoseDbError } from "../cli-errors-
|
|
6
|
-
import {
|
|
5
|
+
import { a as diagnoseDbError } from "../cli-errors-DwqFRIWz.js";
|
|
6
|
+
import { b as validatePolicyPgRoles, x as warnOnAnonymousGrants } from "../rls-enforcement-BO618rnr.js";
|
|
7
7
|
import { n as describeFailure, t as chalk } from "../source-fZb92pN8.js";
|
|
8
|
-
import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-
|
|
9
|
-
import { n as loadCollections, r as runDoctor } from "../doctor-
|
|
8
|
+
import { n as formatPolicyDrift, r as hasDrift, t as checkPolicyDrift } from "../policy-drift-DKuTJHfc.js";
|
|
9
|
+
import { n as loadCollections, r as runDoctor } from "../doctor-BaR11xUe.js";
|
|
10
10
|
import { isPostgresCollectionConfig } from "@rebasepro/types";
|
|
11
|
-
import { getTableName, relationalCollections } from "@rebasepro/common";
|
|
11
|
+
import { getTableName, relationalCollections, resolveJunctionSpecs } from "@rebasepro/common";
|
|
12
12
|
import path from "path";
|
|
13
13
|
//#region src/schema/doctor-policy-checks.ts
|
|
14
14
|
/**
|
|
@@ -183,6 +183,140 @@ async function runSearchScaleCheck(collectionsPath, databaseUrl) {
|
|
|
183
183
|
}
|
|
184
184
|
}
|
|
185
185
|
//#endregion
|
|
186
|
+
//#region src/schema/doctor-database.ts
|
|
187
|
+
/**
|
|
188
|
+
* `rebase doctor --database`: whether this database can host Rebase's request
|
|
189
|
+
* role(s) under the project's `rls` settings, read from the catalogue without
|
|
190
|
+
* changing anything.
|
|
191
|
+
*
|
|
192
|
+
* Lives beside `doctor-cli.ts` rather than inside it because that file runs
|
|
193
|
+
* `main()` on import; the rendering and the table list are tested here.
|
|
194
|
+
*/
|
|
195
|
+
/**
|
|
196
|
+
* The tables Rebase serves, as the server would list them: every relational
|
|
197
|
+
* collection's table in its schema (`public` by default), and every junction
|
|
198
|
+
* table a many-to-many declares.
|
|
199
|
+
*/
|
|
200
|
+
function managedTablesOf(collections) {
|
|
201
|
+
const relational = relationalCollections(collections);
|
|
202
|
+
const tables = /* @__PURE__ */ new Map();
|
|
203
|
+
const add = (schema, table) => tables.set(`${schema}.${table}`, {
|
|
204
|
+
schema,
|
|
205
|
+
table
|
|
206
|
+
});
|
|
207
|
+
for (const collection of relational) add(isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public", getTableName(collection));
|
|
208
|
+
for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);
|
|
209
|
+
return [...tables.values()];
|
|
210
|
+
}
|
|
211
|
+
/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
|
|
212
|
+
function preflightSchemasOf(collections) {
|
|
213
|
+
return Array.from(/* @__PURE__ */ new Set([
|
|
214
|
+
"public",
|
|
215
|
+
"rebase",
|
|
216
|
+
...relationalCollections(collections).filter(isPostgresCollectionConfig).map((c) => c.schema).filter((s) => !!s)
|
|
217
|
+
]));
|
|
218
|
+
}
|
|
219
|
+
var LEVEL_ORDER = [
|
|
220
|
+
"fail",
|
|
221
|
+
"warn",
|
|
222
|
+
"ok"
|
|
223
|
+
];
|
|
224
|
+
var LEVEL_TITLE = {
|
|
225
|
+
fail: "Needs fixing before Rebase can serve requests here",
|
|
226
|
+
warn: "Worth a look",
|
|
227
|
+
ok: "Fine"
|
|
228
|
+
};
|
|
229
|
+
var LEVEL_MARK = {
|
|
230
|
+
fail: chalk.red("✗"),
|
|
231
|
+
warn: chalk.yellow("⚠"),
|
|
232
|
+
ok: chalk.green("✓")
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* The report, grouped by level, failures first. Each finding that is not fine
|
|
236
|
+
* shows the SQL to run as an administrator in gray, and the `rls` setting that
|
|
237
|
+
* would fit Rebase to the database instead.
|
|
238
|
+
*/
|
|
239
|
+
function renderPreflightFindings(findings, settings) {
|
|
240
|
+
const lines = [];
|
|
241
|
+
lines.push(chalk.bold(" Database preflight"));
|
|
242
|
+
lines.push(chalk.gray(` Request role(s): ${settings.roles.join(", ")}. ` + (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(", ")}.` : "The other rls settings are at their defaults.")));
|
|
243
|
+
for (const level of LEVEL_ORDER) {
|
|
244
|
+
const group = findings.filter((f) => f.level === level);
|
|
245
|
+
if (group.length === 0) continue;
|
|
246
|
+
lines.push("");
|
|
247
|
+
lines.push(` ${LEVEL_TITLE[level]}`);
|
|
248
|
+
for (const finding of group) {
|
|
249
|
+
lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);
|
|
250
|
+
if (finding.sql) for (const sqlLine of finding.sql.split("\n")) lines.push(chalk.gray(` ${sqlLine}`));
|
|
251
|
+
if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? "or set" : "set"}: ${finding.setting}`));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return lines;
|
|
255
|
+
}
|
|
256
|
+
/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */
|
|
257
|
+
function preflightStatus(findings) {
|
|
258
|
+
return findings.some((f) => f.level === "fail") ? "problems" : "ok";
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* Every table in `schemas` but `rebase`: what a project with no declared
|
|
262
|
+
* collections serves, since its API is introspected from the database.
|
|
263
|
+
*/
|
|
264
|
+
async function everyTableIn(run, schemas) {
|
|
265
|
+
const names = schemas.filter((s) => s !== "rebase").map((s) => `'${s.replace(/'/g, "''")}'`);
|
|
266
|
+
if (names.length === 0) return [];
|
|
267
|
+
return (await run(`
|
|
268
|
+
SELECT n.nspname AS schema, c.relname AS name
|
|
269
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
270
|
+
WHERE n.nspname IN (${names.join(", ")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
271
|
+
ORDER BY 1, 2
|
|
272
|
+
`)).map((r) => ({
|
|
273
|
+
schema: String(r.schema),
|
|
274
|
+
table: String(r.name)
|
|
275
|
+
}));
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Run the preflight against `databaseUrl` with the settings a command outside
|
|
279
|
+
* the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
|
|
280
|
+
* and print it. Never reports `ok` for a check it could not run.
|
|
281
|
+
*/
|
|
282
|
+
async function runDatabasePreflight(collectionsPath, databaseUrl) {
|
|
283
|
+
if (!databaseUrl) {
|
|
284
|
+
console.error(chalk.yellow(" ⚠ No DATABASE_URL — the database preflight did NOT run"));
|
|
285
|
+
return "unchecked";
|
|
286
|
+
}
|
|
287
|
+
const { loadCollections } = await import("../doctor-BaR11xUe.js").then((n) => n.t);
|
|
288
|
+
const { preflightDatabase } = await import("../database-preflight-D5JtPt8i.js");
|
|
289
|
+
const { readRecordedRequestRoles } = await import("../rls-enforcement-BO618rnr.js").then((n) => n.v);
|
|
290
|
+
const { cliRlsSettings } = await import("../rls-settings-De5NoHHy.js").then((n) => n.a);
|
|
291
|
+
const { Pool } = await import("pg");
|
|
292
|
+
const pool = new Pool({ connectionString: databaseUrl });
|
|
293
|
+
try {
|
|
294
|
+
const run = async (text) => (await pool.query(text)).rows;
|
|
295
|
+
const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));
|
|
296
|
+
const existing = new Set((await run("SELECT nspname FROM pg_namespace")).map((row) => String(row.nspname)));
|
|
297
|
+
const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));
|
|
298
|
+
const settings = cliRlsSettings(await readRecordedRequestRoles(run));
|
|
299
|
+
let managedTables = managedTablesOf(collections);
|
|
300
|
+
console.log("");
|
|
301
|
+
if (managedTables.length === 0) {
|
|
302
|
+
managedTables = await everyTableIn(run, schemas);
|
|
303
|
+
console.log(chalk.gray(" No declared collections: every table in public is treated as served, as an introspected project serves them."));
|
|
304
|
+
}
|
|
305
|
+
const findings = await preflightDatabase(run, settings, {
|
|
306
|
+
schemas,
|
|
307
|
+
managedTables
|
|
308
|
+
});
|
|
309
|
+
for (const line of renderPreflightFindings(findings, settings)) console.log(line);
|
|
310
|
+
console.log("");
|
|
311
|
+
return preflightStatus(findings);
|
|
312
|
+
} catch (err) {
|
|
313
|
+
console.error(chalk.red(" ✗ Could not run the database preflight:"), err instanceof Error ? err.message : String(err));
|
|
314
|
+
return "unchecked";
|
|
315
|
+
} finally {
|
|
316
|
+
await pool.end();
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
//#endregion
|
|
186
320
|
//#region src/schema/doctor-cli.ts
|
|
187
321
|
/**
|
|
188
322
|
* CLI entry point for `rebase doctor`.
|
|
@@ -193,6 +327,7 @@ async function main() {
|
|
|
193
327
|
const schemaArg = process.argv.find((a) => a.startsWith("--schema="));
|
|
194
328
|
const sdkArg = process.argv.find((a) => a.startsWith("--sdk="));
|
|
195
329
|
const policiesOnly = process.argv.includes("--policies");
|
|
330
|
+
const databaseOnly = process.argv.includes("--database");
|
|
196
331
|
const collectionsPath = collectionsArg?.split("=")[1] ?? path.join("..", "config", "collections");
|
|
197
332
|
const schemaPath = schemaArg?.split("=")[1] ?? path.join("src", "schema.generated.ts");
|
|
198
333
|
const sdkPath = sdkArg?.split("=")[1] ?? path.join("..", "generated", "sdk", "database.types.ts");
|
|
@@ -206,7 +341,10 @@ async function main() {
|
|
|
206
341
|
else dotenv.config({ quiet: true });
|
|
207
342
|
} catch {}
|
|
208
343
|
const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;
|
|
209
|
-
if (policiesOnly
|
|
344
|
+
if (policiesOnly || databaseOnly) {
|
|
345
|
+
const statuses = [...databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : [], ...policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : []];
|
|
346
|
+
process.exit(statuses.some((status) => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);
|
|
347
|
+
}
|
|
210
348
|
const report = await runDoctor({
|
|
211
349
|
collectionsPath: path.resolve(process.cwd(), collectionsPath),
|
|
212
350
|
schemaPath: path.resolve(process.cwd(), schemaPath),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections as never);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections as never);\n\n const drift = await checkPolicyDrift(pool as never, collections);\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly) {\n // Non-zero so this can gate CI — the whole point of the flag, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n process.exit(exitCodeForPolicyGate(await runPolicyChecks(collectionsPath, databaseUrl)));\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STR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AS,KAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO;EAC5C,aAAa,eAAe,KAAA;CAChC,CAAC;CAED,MAAM,eAAe,MAAM,gBAAgB,iBAAiB,WAAW;CAGvE,MAAM,oBAAoB,iBAAiB,WAAW;CAYtD,MAAM,UAAU;EAAC,OAAO;EAAqB,OAAO;EAAkB,OAAO;CAAgB,CAAC,CACzF,MAAK,UAAS,MAAM,OAAO;CAChC,IAAI,OAAO,QAAQ,SAAS,KAAK,iBAAiB,cAAc,SAC5D,QAAQ,KAAK,CAAC;AAEtB;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAKlB,MAAM,SAAS,gBAAgB,KAAK,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,uBAAuB;CACnG,IAAI,QACA,QAAQ,MAAM,MAAM;MAEpB,QAAQ,MAAM,MAAM,IAAI,sBAAsB,gBAAgB,GAAG,GAAG,CAAC;CAEzE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
|
|
1
|
+
{"version":3,"file":"doctor-cli.js","names":[],"sources":["../../src/schema/doctor-policy-checks.ts","../../src/schema/doctor-search-scale.ts","../../src/schema/doctor-database.ts","../../src/schema/doctor-cli.ts"],"sourcesContent":["/**\n * The RLS half of `rebase doctor`, and the exit code `--policies` gates CI on.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import: a gate whose failure modes cannot be unit-tested is how\n * this one shipped reporting success for work it never did.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { checkPolicyDrift, formatPolicyDrift, hasDrift } from \"../security/policy-drift\";\nimport { validatePolicyPgRoles, warnOnAnonymousGrants } from \"../security/rls-enforcement\";\n\n/**\n * What the RLS checks concluded.\n *\n * `unchecked` exists because \"we could not look\" and \"we looked and it is fine\"\n * used to be reported identically: a collections path that did not resolve made\n * the loader return `[]` (it warns, it does not throw), `checkPolicyDrift`\n * early-returned an empty diff, and the gate printed\n * `✓ RLS policies match your collections` having compared zero policies against\n * zero collections. Any exception at all — a collection file that throws on\n * import, a `pg_policies` read the CI role is not granted, a connection reset —\n * did the same thing through a `warn`, and exited 0.\n */\nexport type PolicyCheckStatus = \"ok\" | \"problems\" | \"unchecked\";\n\n/**\n * The exit code for `rebase doctor --policies`.\n *\n * A gate that could not run has not passed. Only a completed, clean check\n * exits 0 — anything else, including \"we never opened a connection\", is a\n * failure, or the flag certifies a database nobody looked at.\n */\nexport function exitCodeForPolicyGate(status: PolicyCheckStatus): 0 | 1 {\n return status === \"ok\" ? 0 : 1;\n}\n\n/**\n * Policies actually deployed vs the ones the collections describe, plus policy\n * roles this server could never satisfy.\n *\n * Never reports `ok` for work it did not do — see {@link PolicyCheckStatus}.\n */\nexport async function runPolicyChecks(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — RLS policies were NOT checked\"));\n return \"unchecked\";\n }\n\n const resolvedPath = path.resolve(process.cwd(), collectionsPath);\n let problems = false;\n const { Pool } = await import(\"pg\");\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const collections: CollectionConfig[] = await loadCollections(resolvedPath);\n\n // Zero collections is not \"no drift\", it is nothing to compare. The\n // loader returns `[]` for a path that does not exist, so the commonest\n // way to get here is a `--collections` path resolved against the wrong\n // directory — which used to render as a green tick.\n if (collections.length === 0) {\n console.error(chalk.red(` ✗ No collections found in ${resolvedPath}`));\n console.error(chalk.gray(\" RLS policies were NOT checked. Pass --collections=<dir> if your collections live elsewhere.\"));\n return \"unchecked\";\n }\n\n const runSql = async (text: string) => (await pool.query(text)).rows as Record<string, unknown>[];\n\n // Prove the connection before anything is ticked.\n //\n // `validatePolicyPgRoles` returns without a query when no collection\n // names a `pgRoles` — which is most projects — so it \"passed\" against a\n // database that was never reached, and the tick printed above an\n // ECONNREFUSED that only surfaced two checks later. Ten lines up, this\n // file says that reporting success for work it never did is the reason\n // it exists. This is the same shape, one function along.\n try {\n await runSql(\"SELECT 1\");\n } catch (err) {\n console.error(chalk.gray(\" ⏭ Policy roles: not checked\"));\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n }\n\n // A policy naming a role the server never runs as filters every row, so\n // the collection reads as empty. Report it without booting a server.\n try {\n await validatePolicyPgRoles(runSql, collections as never);\n console.log(chalk.green(\" ✓ Policy roles are usable by this server\"));\n } catch (err) {\n problems = true;\n console.log(\"\");\n console.error(chalk.red(err instanceof Error ? err.message : String(err)));\n }\n\n // A rule that reads as a lockdown but is true for every caller compiles\n // to a grant. Report it without booting a server.\n warnOnAnonymousGrants(collections as never);\n\n const drift = await checkPolicyDrift(pool as never, collections);\n console.log(\"\");\n if (hasDrift(drift)) {\n problems = true;\n console.log(chalk.yellow(\" RLS policies: database does not match your collections\"));\n console.log(formatPolicyDrift(drift));\n } else {\n console.log(chalk.green(` ✓ RLS policies match your collections (${collections.length} collection(s) checked)`));\n }\n } catch (err) {\n // Fail closed. This catch covers every query and every collection import\n // above, so returning the pre-catch verdict made the documented CI gate\n // green on exactly the runs it exists to catch.\n console.error(chalk.red(\" ✗ Could not check RLS policies:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n return problems ? \"problems\" : \"ok\";\n}\n","/**\n * `rebase doctor`: collections searched by a full scan of a large table.\n *\n * Without a `search` block, a search — the admin's search box, `?searchString=`,\n * `.search()` — is `ILIKE '%term%'` over every text column. A leading `%`\n * defeats a B-tree, so each one reads the whole table: on 100k posts a search\n * took 326 ms, half for the page and half for its count. Nothing reports it;\n * the box just gets slower as the table grows. This names the collections\n * where that has started to matter, and points at the block that fixes it.\n *\n * A hint, not a failure: it never changes doctor's exit code, and the database\n * is not changed — Rebase does not add a search index on its own.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { getTableName, relationalCollections } from \"@rebasepro/common\";\nimport { isPostgresCollectionConfig, type CollectionConfig } from \"@rebasepro/types\";\nimport { loadCollections } from \"./doctor\";\nimport { buildSearchColumnSpec } from \"./search-column\";\n\n/** Above this many rows an unindexed search is worth a word. */\nexport const UNINDEXED_SEARCH_ROWS = 10_000;\n\n/** A collection whose search would be `ILIKE` over these fields. */\nexport interface IlikeSearchedCollection {\n slug: string;\n schema: string;\n table: string;\n /** The string properties the search reads. */\n fields: string[];\n}\n\n/**\n * The collections a search reaches without an index: no `search` block (or\n * one that does not build), and at least one property the default search\n * reads — a `string`, not an enum, not a uuid key (the rule in\n * `DrizzleConditionBuilder.buildSearchConditions`).\n */\nexport function ilikeSearchedCollections(collections: CollectionConfig[]): IlikeSearchedCollection[] {\n const found: IlikeSearchedCollection[] = [];\n for (const collection of relationalCollections(collections)) {\n if (!isPostgresCollectionConfig(collection)) continue;\n let indexed: boolean;\n try {\n indexed = buildSearchColumnSpec(collection) !== undefined;\n } catch {\n // A block that does not build is reported by the boot; the search\n // falls back to ILIKE meanwhile, so it counts as none here.\n indexed = false;\n }\n if (indexed) continue;\n const fields = Object.entries(collection.properties ?? {})\n .filter(([, property]) => property.type === \"string\" && !property.enum && property.isId !== \"uuid\")\n .map(([key]) => key);\n const table = getTableName(collection);\n if (fields.length === 0 || !table) continue;\n found.push({ slug: collection.slug, schema: collection.schema ?? \"public\", table, fields });\n }\n return found;\n}\n\n/** Those of `candidates` whose table holds more than `threshold` rows, by estimate. */\nexport function unindexedSearchFindings(\n candidates: IlikeSearchedCollection[],\n rowEstimates: ReadonlyMap<string, number>,\n threshold: number = UNINDEXED_SEARCH_ROWS\n): (IlikeSearchedCollection & { rows: number })[] {\n return candidates\n .map(candidate => ({ ...candidate, rows: rowEstimates.get(`${candidate.schema}.${candidate.table}`) ?? 0 }))\n .filter(candidate => candidate.rows > threshold);\n}\n\n/**\n * Row counts by `schema.table`, estimated — `pg_class.reltuples`, or the\n * statistics collector's live-tuple count when the table was never analysed.\n * Nothing is scanned: counting the tables this is about would be the cost it\n * warns of.\n */\nexport async function estimateRowCounts(\n query: (text: string, values: unknown[]) => Promise<{ rows: { schema: string; table: string; rows: string | number }[] }>,\n schemas: string[]\n): Promise<Map<string, number>> {\n const { rows } = await query(\n `SELECT n.nspname AS schema, c.relname AS table,\n GREATEST(c.reltuples, COALESCE(s.n_live_tup, 0), 0)::bigint AS rows\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_stat_user_tables s ON s.relid = c.oid\n WHERE c.relkind IN ('r', 'p') AND n.nspname = ANY($1)`,\n [schemas]\n );\n return new Map(rows.map(row => [`${row.schema}.${row.table}`, Number(row.rows)]));\n}\n\n/** The report, one warning per collection. */\nexport function formatUnindexedSearches(findings: (IlikeSearchedCollection & { rows: number })[]): string[] {\n if (findings.length === 0) return [];\n const lines = [\"\", chalk.yellow(` ⚠ ${findings.length} collection(s) searched by reading the whole table:`)];\n for (const finding of findings) {\n lines.push(chalk.yellow(\n ` • ${finding.slug} — about ${finding.rows.toLocaleString(\"en-US\")} rows, no \\`search\\` block: a search is ` +\n `ILIKE '%term%' over ${finding.fields.join(\", \")}`\n ));\n }\n lines.push(chalk.gray(\n \" Each search reads every row, and its count reads them again. A `search` block indexes it\\n\" +\n \" (full-text, or `mode: \\\"hybrid\\\"` for substrings too): https://rebase.pro/docs/backend/search\"\n ));\n return lines;\n}\n\n/**\n * Print the warning for the project at `collectionsPath`, against\n * `databaseUrl`. Never throws and never fails the run: it is a hint, and a\n * check that could not run says so in one grey line.\n */\nexport async function runSearchScaleCheck(collectionsPath: string, databaseUrl?: string): Promise<void> {\n if (!databaseUrl) return;\n const { Client } = await import(\"pg\");\n const client = new Client({ connectionString: databaseUrl });\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n const candidates = ilikeSearchedCollections(collections);\n if (candidates.length === 0) return;\n await client.connect();\n const estimates = await estimateRowCounts(\n (text, values) => client.query(text, values),\n [...new Set(candidates.map(candidate => candidate.schema))]\n );\n for (const line of formatUnindexedSearches(unindexedSearchFindings(candidates, estimates))) console.log(line);\n } catch (err) {\n console.log(chalk.gray(` ⏭ Search on large tables: not checked (${err instanceof Error ? err.message : String(err)})`));\n } finally {\n await client.end().catch(() => undefined);\n }\n}\n","/**\n * `rebase doctor --database`: whether this database can host Rebase's request\n * role(s) under the project's `rls` settings, read from the catalogue without\n * changing anything.\n *\n * Lives beside `doctor-cli.ts` rather than inside it because that file runs\n * `main()` on import; the rendering and the table list are tested here.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport { isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName, relationalCollections, resolveJunctionSpecs } from \"@rebasepro/common\";\nimport type { PreflightFinding } from \"../security/database-preflight\";\nimport type { ManagedTable, RawSqlRunner } from \"../security/rls-enforcement\";\nimport type { RlsSettings } from \"../security/rls-settings\";\nimport type { PolicyCheckStatus } from \"./doctor-policy-checks\";\n\n/**\n * The tables Rebase serves, as the server would list them: every relational\n * collection's table in its schema (`public` by default), and every junction\n * table a many-to-many declares.\n */\nexport function managedTablesOf(collections: CollectionConfig[]): ManagedTable[] {\n const relational = relationalCollections(collections);\n const tables = new Map<string, ManagedTable>();\n const add = (schema: string, table: string) => tables.set(`${schema}.${table}`, { schema, table });\n for (const collection of relational) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n add(schema, getTableName(collection));\n }\n for (const spec of resolveJunctionSpecs(relational).values()) add(spec.schema, spec.table);\n return [...tables.values()];\n}\n\n/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */\nexport function preflightSchemasOf(collections: CollectionConfig[]): string[] {\n return Array.from(new Set([\n \"public\",\n \"rebase\",\n ...relationalCollections(collections)\n .filter(isPostgresCollectionConfig)\n .map((c) => c.schema)\n .filter((s): s is string => !!s)\n ]));\n}\n\nconst LEVEL_ORDER: PreflightFinding[\"level\"][] = [\"fail\", \"warn\", \"ok\"];\nconst LEVEL_TITLE: Record<PreflightFinding[\"level\"], string> = {\n fail: \"Needs fixing before Rebase can serve requests here\",\n warn: \"Worth a look\",\n ok: \"Fine\"\n};\nconst LEVEL_MARK: Record<PreflightFinding[\"level\"], string> = {\n fail: chalk.red(\"✗\"),\n warn: chalk.yellow(\"⚠\"),\n ok: chalk.green(\"✓\")\n};\n\n/**\n * The report, grouped by level, failures first. Each finding that is not fine\n * shows the SQL to run as an administrator in gray, and the `rls` setting that\n * would fit Rebase to the database instead.\n */\nexport function renderPreflightFindings(\n findings: readonly PreflightFinding[],\n settings: Pick<RlsSettings, \"roles\" | \"nonDefaults\">\n): string[] {\n const lines: string[] = [];\n lines.push(chalk.bold(\" Database preflight\"));\n lines.push(chalk.gray(\n ` Request role(s): ${settings.roles.join(\", \")}. ` +\n (settings.nonDefaults.length > 0 ? `Non-default settings: ${settings.nonDefaults.join(\", \")}.` : \"The other rls settings are at their defaults.\")\n ));\n for (const level of LEVEL_ORDER) {\n const group = findings.filter((f) => f.level === level);\n if (group.length === 0) continue;\n lines.push(\"\");\n lines.push(` ${LEVEL_TITLE[level]}`);\n for (const finding of group) {\n lines.push(` ${LEVEL_MARK[level]} ${finding.check}: ${finding.detail}`);\n if (finding.sql) {\n for (const sqlLine of finding.sql.split(\"\\n\")) lines.push(chalk.gray(` ${sqlLine}`));\n }\n if (finding.setting) lines.push(chalk.cyan(` ${finding.sql ? \"or set\" : \"set\"}: ${finding.setting}`));\n }\n }\n return lines;\n}\n\n/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */\nexport function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus {\n return findings.some((f) => f.level === \"fail\") ? \"problems\" : \"ok\";\n}\n\n/**\n * Every table in `schemas` but `rebase`: what a project with no declared\n * collections serves, since its API is introspected from the database.\n */\nasync function everyTableIn(run: RawSqlRunner, schemas: readonly string[]): Promise<ManagedTable[]> {\n const names = schemas.filter((s) => s !== \"rebase\").map((s) => `'${s.replace(/'/g, \"''\")}'`);\n if (names.length === 0) return [];\n const rows = await run(`\n SELECT n.nspname AS schema, c.relname AS name\n FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE n.nspname IN (${names.join(\", \")}) AND c.relkind IN ('r', 'p', 'v', 'm', 'f')\n ORDER BY 1, 2\n `);\n return rows.map((r) => ({ schema: String(r.schema), table: String(r.name) }));\n}\n\n/**\n * Run the preflight against `databaseUrl` with the settings a command outside\n * the server sees (`REBASE_RLS_*`, else the roles recorded in the database),\n * and print it. Never reports `ok` for a check it could not run.\n */\nexport async function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus> {\n if (!databaseUrl) {\n console.error(chalk.yellow(\" ⚠ No DATABASE_URL — the database preflight did NOT run\"));\n return \"unchecked\";\n }\n\n const { loadCollections } = await import(\"./doctor\");\n const { preflightDatabase } = await import(\"../security/database-preflight\");\n const { readRecordedRequestRoles } = await import(\"../security/rls-enforcement\");\n const { cliRlsSettings } = await import(\"../security/rls-settings\");\n const { Pool } = await import(\"pg\");\n\n const pool = new Pool({ connectionString: databaseUrl });\n try {\n const run: RawSqlRunner = async (text) => (await pool.query(text)).rows as Record<string, unknown>[];\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n // Only the schemas that exist: the SQL a finding carries grants on each\n // one, and a GRANT on a missing schema fails the whole script. A boot\n // grants on the ones it creates itself.\n const existing = new Set((await run(\"SELECT nspname FROM pg_namespace\")).map((row) => String(row.nspname)));\n const schemas = preflightSchemasOf(collections).filter((schema) => existing.has(schema));\n const settings = cliRlsSettings(await readRecordedRequestRoles(run));\n\n let managedTables = managedTablesOf(collections);\n console.log(\"\");\n if (managedTables.length === 0) {\n managedTables = await everyTableIn(run, schemas);\n console.log(chalk.gray(\" No declared collections: every table in public is treated as served, as an introspected project serves them.\"));\n }\n\n const findings = await preflightDatabase(run, settings, { schemas, managedTables });\n for (const line of renderPreflightFindings(findings, settings)) console.log(line);\n console.log(\"\");\n return preflightStatus(findings);\n } catch (err) {\n console.error(chalk.red(\" ✗ Could not run the database preflight:\"), err instanceof Error ? err.message : String(err));\n return \"unchecked\";\n } finally {\n await pool.end();\n }\n}\n","#!/usr/bin/env node\n/**\n * CLI entry point for `rebase doctor`.\n * Invoked via tsx by the server-postgres CLI plugin.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { runDoctor } from \"./doctor\";\nimport { exitCodeForPolicyGate, runPolicyChecks } from \"./doctor-policy-checks\";\nimport { runSearchScaleCheck } from \"./doctor-search-scale\";\nimport { runDatabasePreflight } from \"./doctor-database\";\nimport { diagnoseDbError } from \"../cli-errors\";\nimport { describeFailure } from \"../cli-output\";\n\nasync function main() {\n const collectionsArg = process.argv.find((a) => a.startsWith(\"--collections=\"));\n const schemaArg = process.argv.find((a) => a.startsWith(\"--schema=\"));\n const sdkArg = process.argv.find((a) => a.startsWith(\"--sdk=\"));\n // --policies runs only the RLS checks: no schema diff, no SDK types. Useful\n // as a CI gate against a deployed database, where the collection files and\n // generated schema are not what you are asking about.\n const policiesOnly = process.argv.includes(\"--policies\");\n // --database runs only the preflight of the database itself: whether the\n // request role(s) can be set up and used here under the project's `rls`\n // settings. Read-only, and a gate like --policies.\n const databaseOnly = process.argv.includes(\"--database\");\n\n const collectionsPath = collectionsArg?.split(\"=\")[1] ?? path.join(\"..\", \"config\", \"collections\");\n const schemaPath = schemaArg?.split(\"=\")[1] ?? path.join(\"src\", \"schema.generated.ts\");\n const sdkPath = sdkArg?.split(\"=\")[1] ?? path.join(\"..\", \"generated\", \"sdk\", \"database.types.ts\");\n\n // Load .env\n try {\n const dotenv = await import(\"dotenv\");\n const envPath = process.env.DOTENV_CONFIG_PATH;\n if (envPath) {\n dotenv.config({ path: envPath, quiet: true });\n } else {\n dotenv.config({ quiet: true });\n }\n } catch {\n // dotenv may not be installed\n }\n\n const databaseUrl = process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING;\n\n if (policiesOnly || databaseOnly) {\n // Non-zero so this can gate CI — the whole point of the flags, and a\n // check that could not run has not passed. See exitCodeForPolicyGate.\n const statuses = [\n ...(databaseOnly ? [await runDatabasePreflight(collectionsPath, databaseUrl)] : []),\n ...(policiesOnly ? [await runPolicyChecks(collectionsPath, databaseUrl)] : [])\n ];\n process.exit(statuses.some(status => exitCodeForPolicyGate(status) !== 0) ? 1 : 0);\n }\n\n const report = await runDoctor({\n collectionsPath: path.resolve(process.cwd(), collectionsPath),\n schemaPath: path.resolve(process.cwd(), schemaPath),\n sdkPath: path.resolve(process.cwd(), sdkPath),\n databaseUrl: databaseUrl ?? undefined\n });\n\n const policyStatus = await runPolicyChecks(collectionsPath, databaseUrl);\n\n // A hint about speed, not drift: it never changes the exit code.\n await runSearchScaleCheck(collectionsPath, databaseUrl);\n\n // Exit non-zero if there are errors. A policy run that could not happen is\n // reported loudly above but does not fail the interactive command — the\n // same treatment the *chosen* skip of the database phase gets. `--policies`\n // is the gate, and that one fails closed.\n //\n // A phase that was skipped by a fault is different, and `blocked` is what\n // separates the two: \"no DATABASE_URL\" is a local situation somebody may be\n // content with, while \"the DATABASE_URL you set refuses connections\" would\n // otherwise let `rebase doctor` go green in CI against a database it never\n // reached.\n const blocked = [report.collectionsToSchema, report.schemaToDatabase, report.collectionsToSdk]\n .some(phase => phase.blocked);\n if (report.summary.errors > 0 || policyStatus === \"problems\" || blocked) {\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n // A known database failure has a diagnosis; a stack trace through pg and\n // drizzle internals is not it. This is the last resort — `runDoctor`\n // already catches the connection failure it can name — so it exists for\n // everything reached after the report, the policy checks in particular.\n const banner = diagnoseDbError(err, process.env.DATABASE_URL || process.env.ADMIN_CONNECTION_STRING);\n if (banner) {\n console.error(banner);\n } else {\n console.error(chalk.red(` ✗ Doctor failed: ${describeFailure(err)}`));\n }\n process.exit(1);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;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AU;EAClD,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,OAAO;EAC5C,aAAa,eAAe,KAAA;CAChC,CAAC;CAED,MAAM,eAAe,MAAM,gBAAgB,iBAAiB,WAAW;CAGvE,MAAM,oBAAoB,iBAAiB,WAAW;CAYtD,MAAM,UAAU;EAAC,OAAO;EAAqB,OAAO;EAAkB,OAAO;CAAgB,CAAC,CACzF,MAAK,UAAS,MAAM,OAAO;CAChC,IAAI,OAAO,QAAQ,SAAS,KAAK,iBAAiB,cAAc,SAC5D,QAAQ,KAAK,CAAC;AAEtB;AAEA,KAAK,CAAC,CAAC,OAAO,QAAQ;CAKlB,MAAM,SAAS,gBAAgB,KAAK,QAAQ,IAAI,gBAAgB,QAAQ,IAAI,uBAAuB;CACnG,IAAI,QACA,QAAQ,MAAM,MAAM;MAEpB,QAAQ,MAAM,MAAM,IAAI,sBAAsB,gBAAgB,GAAG,GAAG,CAAC;CAEzE,QAAQ,KAAK,CAAC;AAClB,CAAC"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { CollectionConfig } from "@rebasepro/types";
|
|
2
|
+
import type { PreflightFinding } from "../security/database-preflight.js";
|
|
3
|
+
import type { ManagedTable } from "../security/rls-enforcement.js";
|
|
4
|
+
import type { RlsSettings } from "../security/rls-settings.js";
|
|
5
|
+
import type { PolicyCheckStatus } from "./doctor-policy-checks.js";
|
|
6
|
+
/**
|
|
7
|
+
* The tables Rebase serves, as the server would list them: every relational
|
|
8
|
+
* collection's table in its schema (`public` by default), and every junction
|
|
9
|
+
* table a many-to-many declares.
|
|
10
|
+
*/
|
|
11
|
+
export declare function managedTablesOf(collections: CollectionConfig[]): ManagedTable[];
|
|
12
|
+
/** The schemas Rebase writes to: `public`, `rebase`, and every schema a collection names. */
|
|
13
|
+
export declare function preflightSchemasOf(collections: CollectionConfig[]): string[];
|
|
14
|
+
/**
|
|
15
|
+
* The report, grouped by level, failures first. Each finding that is not fine
|
|
16
|
+
* shows the SQL to run as an administrator in gray, and the `rls` setting that
|
|
17
|
+
* would fit Rebase to the database instead.
|
|
18
|
+
*/
|
|
19
|
+
export declare function renderPreflightFindings(findings: readonly PreflightFinding[], settings: Pick<RlsSettings, "roles" | "nonDefaults">): string[];
|
|
20
|
+
/** `ok` when nothing failed; `problems` when a finding is a failure. Warnings do not fail the run. */
|
|
21
|
+
export declare function preflightStatus(findings: readonly PreflightFinding[]): PolicyCheckStatus;
|
|
22
|
+
/**
|
|
23
|
+
* Run the preflight against `databaseUrl` with the settings a command outside
|
|
24
|
+
* the server sees (`REBASE_RLS_*`, else the roles recorded in the database),
|
|
25
|
+
* and print it. Never reports `ok` for a check it could not run.
|
|
26
|
+
*/
|
|
27
|
+
export declare function runDatabasePreflight(collectionsPath: string, databaseUrl?: string): Promise<PolicyCheckStatus>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { t as main } from "../generate-drizzle-schema-
|
|
3
|
+
import { t as main } from "../generate-drizzle-schema-5spbTyQ6.js";
|
|
4
4
|
//#region src/schema/bin/generate-drizzle-schema.ts
|
|
5
5
|
/**
|
|
6
6
|
* The built entry point for `generate-drizzle-schema`.
|
|
@@ -39,6 +39,7 @@ export interface GenerateFileOptions {
|
|
|
39
39
|
export declare function writeDrizzleSchema(options: GenerateFileOptions): Promise<void>;
|
|
40
40
|
/**
|
|
41
41
|
* `schema.sql` (Atlas's desired state) and, beside it, `policies.sql`,
|
|
42
|
-
* `search.sql`, `vector.sql` and `
|
|
42
|
+
* `search.sql`, `vector.sql`, `triggers.sql` and `views.sql` — the parts Atlas
|
|
43
|
+
* does not own.
|
|
43
44
|
*/
|
|
44
45
|
export declare function writePostgresDdl(options: GenerateFileOptions): Promise<void>;
|
|
@@ -94,6 +94,12 @@ export declare const vectorExcludePatterns: (allCollections: CollectionConfig[])
|
|
|
94
94
|
* `on_update` — the caller writes no file then, and removes a stale one.
|
|
95
95
|
*/
|
|
96
96
|
export declare const generatePostgresTriggersDdl: (allCollections: CollectionConfig[]) => string;
|
|
97
|
+
/**
|
|
98
|
+
* `.rebase/sql/views.sql` — the views of the collections that declare `view`,
|
|
99
|
+
* which Atlas's free tier does not manage. Empty when none does — the caller
|
|
100
|
+
* writes no file then, and removes a stale one.
|
|
101
|
+
*/
|
|
102
|
+
export declare const generatePostgresViewsDdl: (allCollections: CollectionConfig[]) => string;
|
|
97
103
|
/** @see searchExcludePatterns */
|
|
98
104
|
export declare const triggerExcludePatterns: (allCollections: CollectionConfig[]) => string[];
|
|
99
105
|
/** A column a `relation` or `reference` property owns on its own table. */
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { r as out } from "../source-fZb92pN8.js";
|
|
4
|
-
import { r as writePostgresDdl } from "../generate-files-
|
|
4
|
+
import { r as writePostgresDdl } from "../generate-files-Bl3_D_oP.js";
|
|
5
5
|
import path from "path";
|
|
6
6
|
//#region src/schema/generate-postgres-ddl.ts
|
|
7
7
|
/**
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { n as require_arg, o as __toESM, t as promptConfirm } from "../cli-prompt-DXG0yk-h.js";
|
|
4
|
-
import { u as pinSearchPath } from "../connection-
|
|
5
|
-
import { a as diagnoseDbError } from "../cli-errors-
|
|
4
|
+
import { u as pinSearchPath } from "../connection-COuS5Fm-.js";
|
|
5
|
+
import { a as diagnoseDbError } from "../cli-errors-DwqFRIWz.js";
|
|
6
6
|
import { a as outWarn, i as outError, r as out, t as chalk } from "../source-fZb92pN8.js";
|
|
7
7
|
import { i as readSchemaMetadata, n as isUsableFileName, r as quoteRelation, t as countRowsUpTo } from "../introspect-db-queries-DevUrzll.js";
|
|
8
8
|
import { a as compositeKeySkipReason, c as generateIndexContent, d as mergeIndexContent, f as safeHostFromUrl, h as lookupCandidates, i as buildTablesMap, m as classifyTables, o as describeRlsOffTables, r as buildEnumMap, s as generateCollectionFile } from "../introspect-db-logic-DgQVzccW.js";
|
|
@@ -45,7 +45,16 @@ export interface Queryable {
|
|
|
45
45
|
* Read tables, columns, enums, primary keys and foreign keys for a schema.
|
|
46
46
|
* Mirrors the queries in introspect-db.ts.
|
|
47
47
|
*/
|
|
48
|
-
export declare function introspectSchema(client: Queryable, pgSchema: string
|
|
48
|
+
export declare function introspectSchema(client: Queryable, pgSchema: string,
|
|
49
|
+
/**
|
|
50
|
+
* Read views and materialized views too, as tables to read from — what
|
|
51
|
+
* the runtime catalogue needs for collections that declare `view`. Off
|
|
52
|
+
* for introspection that turns relations into collections, where a view
|
|
53
|
+
* is not one.
|
|
54
|
+
*/
|
|
55
|
+
options?: {
|
|
56
|
+
views?: boolean;
|
|
57
|
+
}): Promise<IntrospectedSchema>;
|
|
49
58
|
/**
|
|
50
59
|
* Turn an introspected schema into collections.
|
|
51
60
|
*
|
|
@@ -79,7 +79,10 @@ export interface ExistingSchema {
|
|
|
79
79
|
* `numeric(10,2)`).
|
|
80
80
|
*/
|
|
81
81
|
columnTypes?: Map<string, string>;
|
|
82
|
-
/**
|
|
82
|
+
/**
|
|
83
|
+
* `schema.table.trigger` of every trigger that already exists, and the
|
|
84
|
+
* same with its arguments — {@link triggerArgumentsKey}.
|
|
85
|
+
*/
|
|
83
86
|
triggers?: Set<string>;
|
|
84
87
|
/**
|
|
85
88
|
* `schema.name` of every index (any relation of kind `i`/`I`) that already
|
|
@@ -116,6 +119,8 @@ export interface ExistingSchema {
|
|
|
116
119
|
* which is what all of them were before.
|
|
117
120
|
*/
|
|
118
121
|
export declare const HELPER_FUNCTIONS: readonly string[];
|
|
122
|
+
/** A trigger's catalogue key with the arguments it is bound with. */
|
|
123
|
+
export declare const triggerArgumentsKey: (key: string, args: readonly string[]) => string;
|
|
119
124
|
/**
|
|
120
125
|
* Everything `CREATE OR REPLACE FUNCTION` sets on a function, as one string.
|
|
121
126
|
*
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
*/
|
|
22
22
|
import { type CollectionConfig, type Property, type SecurityRule } from "@rebasepro/types";
|
|
23
23
|
import { SET_UPDATED_AT_FN } from "./updated-at-trigger.js";
|
|
24
|
-
import type { PgType, PlanOptions, PolicyPlan, SchemaPlan } from "./types.js";
|
|
24
|
+
import type { PgType, PlanOptions, PolicyPlan, SchemaPlan, ViewPlan } from "./types.js";
|
|
25
25
|
type ResolveCollection = (slug: string) => CollectionConfig | undefined;
|
|
26
26
|
/**
|
|
27
27
|
* Single-quote escaping for a SQL string literal (PostgreSQL doubles the
|
|
@@ -96,4 +96,12 @@ export declare const columnPgType: (propName: string, prop: Property, collection
|
|
|
96
96
|
*/
|
|
97
97
|
export declare const compileSecurityRule: (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection, injected: boolean, ruleKey?: string) => PolicyPlan[];
|
|
98
98
|
export declare function planSchema(allCollections: CollectionConfig[], options?: PlanOptions): SchemaPlan;
|
|
99
|
+
/**
|
|
100
|
+
* The view collections' views, each after the views its query names.
|
|
101
|
+
*
|
|
102
|
+
* Which views a query reads is read off its text — a planned view's name as a
|
|
103
|
+
* whole word — which is enough to order them: a name that appears in a string
|
|
104
|
+
* literal only orders two views that did not need it, never the other way.
|
|
105
|
+
*/
|
|
106
|
+
export declare function planViews(collections: CollectionConfig[]): ViewPlan[];
|
|
99
107
|
export { SET_UPDATED_AT_FN };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan } from "./types.js";
|
|
1
|
+
import type { ColumnPlan, PgType, PolicyPlan, SchemaPlan, TablePlan, ViewPlan } from "./types.js";
|
|
2
2
|
/** What `schema.sql` may leave out, because another file owns it. */
|
|
3
3
|
export interface DdlRenderOptions {
|
|
4
4
|
/** RLS policies. `false` puts them in `policies.sql` alone. */
|
|
@@ -78,3 +78,34 @@ export declare const vectorExcludePatternsOf: (plan: SchemaPlan) => string[];
|
|
|
78
78
|
export declare function renderTriggersDdl(plan: SchemaPlan): string;
|
|
79
79
|
/** @see searchExcludePatternsOf */
|
|
80
80
|
export declare const triggerExcludePatternsOf: (plan: SchemaPlan) => string[];
|
|
81
|
+
/** The comment a view Rebase created carries: `rebase:view:<hash>`. */
|
|
82
|
+
export declare const viewComment: (view: ViewPlan) => string;
|
|
83
|
+
/**
|
|
84
|
+
* The statements that create one view as planned, comment included, for
|
|
85
|
+
* `EXECUTE`. A plain view runs as the caller (`security_invoker`), so the
|
|
86
|
+
* policies of the tables it reads decide what each caller sees.
|
|
87
|
+
*
|
|
88
|
+
* A materialized view is two objects (see `view-names.ts`): its rows, stored
|
|
89
|
+
* under {@link viewRowsName} with a unique index on the id columns (which
|
|
90
|
+
* `REFRESH … CONCURRENTLY` needs), and the gate under the collection's name —
|
|
91
|
+
* a `security_barrier` view that reads them with the owner's rights and serves
|
|
92
|
+
* them to the collection's roles and to the server (no uid). It reads the
|
|
93
|
+
* settings directly rather than through `rebase.roles()`, which a first boot
|
|
94
|
+
* creates after the views. It carries each row's `xmin`, for `fingerprint()`;
|
|
95
|
+
* the catalogue reader leaves that column out of the collection.
|
|
96
|
+
*/
|
|
97
|
+
export declare function viewCreateStatements(view: ViewPlan): string[];
|
|
98
|
+
/**
|
|
99
|
+
* `views.sql`: the views of the collections that declare one, as the file
|
|
100
|
+
* Rebase applies itself — Atlas manages no views on its free tier.
|
|
101
|
+
*
|
|
102
|
+
* Idempotent, in two passes. The first drops, last first, every view whose
|
|
103
|
+
* comment no longer matches its plan and every view that reads one of those
|
|
104
|
+
* (Postgres will not drop a view another still reads, and will not change a
|
|
105
|
+
* view's columns in place); the second creates, in order, every view that is
|
|
106
|
+
* not there. A view that is up to date is left alone, rows and all. A table or
|
|
107
|
+
* a view Rebase did not create under the same name is refused, never dropped.
|
|
108
|
+
*
|
|
109
|
+
* Empty when no collection declares a view.
|
|
110
|
+
*/
|
|
111
|
+
export declare function renderViewsDdl(plan: SchemaPlan): string;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { TriggerPlan } from "./types.js";
|
|
2
|
+
/** The one trigger function, qualified. A frozen derived name. */
|
|
3
|
+
export declare const KEEP_TENANT_FN = "rebase.keep_tenant";
|
|
4
|
+
/** The trigger's name on `table`. A frozen derived name. */
|
|
5
|
+
export declare const keepTenantTriggerName: (table: string) => string;
|
|
6
|
+
export declare const keepTenantFunction: () => string;
|
|
7
|
+
/** The arguments the binding passes: the column, then each bypass role. */
|
|
8
|
+
export declare const keepTenantArguments: (plan: TriggerPlan) => string[];
|
|
9
|
+
export declare const createKeepTenantStatement: (plan: TriggerPlan) => string;
|
|
@@ -297,6 +297,14 @@ export interface TriggerPlan {
|
|
|
297
297
|
column: string;
|
|
298
298
|
/** Frozen derived name — see `contracts/derived-names.txt`. */
|
|
299
299
|
name: string;
|
|
300
|
+
/**
|
|
301
|
+
* What the trigger does: `touch` stamps `column` with `now()` on every
|
|
302
|
+
* update (`autoValue: "on_update"`, the default); `keep-tenant` refuses an
|
|
303
|
+
* update that changes the tenant `column` (see `tenant-keep-trigger.ts`).
|
|
304
|
+
*/
|
|
305
|
+
kind?: "touch" | "keep-tenant";
|
|
306
|
+
/** `keep-tenant` only: the roles that may move a row between tenants. */
|
|
307
|
+
bypassRoles?: string[];
|
|
300
308
|
}
|
|
301
309
|
/** A Postgres enum type one or more columns reference. */
|
|
302
310
|
export interface EnumPlan {
|
|
@@ -414,6 +422,31 @@ export interface PlanOptions {
|
|
|
414
422
|
*/
|
|
415
423
|
databaseExtensions?: readonly string[];
|
|
416
424
|
}
|
|
425
|
+
/** A collection's SQL view, as `views.sql` creates it. See `PostgresCollectionConfig.view`. */
|
|
426
|
+
export interface ViewPlan {
|
|
427
|
+
schema: string;
|
|
428
|
+
name: string;
|
|
429
|
+
/** `schema.name`, unquoted. */
|
|
430
|
+
qualified: string;
|
|
431
|
+
query: string;
|
|
432
|
+
materialized: boolean;
|
|
433
|
+
/**
|
|
434
|
+
* Materialized only: the roles its gate serves (`view.roles`, default
|
|
435
|
+
* `["admin"]`). See `viewRowsName`.
|
|
436
|
+
*/
|
|
437
|
+
roles: string[];
|
|
438
|
+
/** The `isId` columns: a materialized view gets a unique index on them, which `REFRESH … CONCURRENTLY` needs. */
|
|
439
|
+
idColumns: string[];
|
|
440
|
+
/** Materialized only: the `CREATE INDEX` of each declared index, on the stored rows. */
|
|
441
|
+
indexes: string[];
|
|
442
|
+
/** The other planned views this one's query names, which must exist first. */
|
|
443
|
+
dependsOn: string[];
|
|
444
|
+
/**
|
|
445
|
+
* A hash of everything above, kept as the view's comment
|
|
446
|
+
* (`rebase:view:<hash>`): a view whose comment differs is recreated.
|
|
447
|
+
*/
|
|
448
|
+
hash: string;
|
|
449
|
+
}
|
|
417
450
|
/**
|
|
418
451
|
* Everything a set of collections asks the database for.
|
|
419
452
|
*
|
|
@@ -437,6 +470,12 @@ export interface SchemaPlan {
|
|
|
437
470
|
declaredSchemas: string[];
|
|
438
471
|
enums: EnumPlan[];
|
|
439
472
|
tables: TablePlan[];
|
|
473
|
+
/**
|
|
474
|
+
* The collections that serve a SQL view (`view`), in creation order: a
|
|
475
|
+
* view whose query names another comes after it. No table, policy or enum
|
|
476
|
+
* is planned for them.
|
|
477
|
+
*/
|
|
478
|
+
views: ViewPlan[];
|
|
440
479
|
relations: RelationPlan[];
|
|
441
480
|
/** `CREATE EXTENSION IF NOT EXISTS …;` statements, deduplicated. */
|
|
442
481
|
extensions: string[];
|
|
@@ -18,5 +18,5 @@ export declare const setUpdatedAtFunction: () => string;
|
|
|
18
18
|
*/
|
|
19
19
|
export declare const dropTriggerStatement: (plan: TriggerPlan) => string;
|
|
20
20
|
export declare const createTriggerStatement: (plan: TriggerPlan) => string;
|
|
21
|
-
/** Both statements, in the order they must run. */
|
|
21
|
+
/** Both statements, in the order they must run — for either kind of trigger. */
|
|
22
22
|
export declare const triggerStatements: (plan: TriggerPlan) => string[];
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** The roles a materialized view is served to when it names none. */
|
|
2
|
+
export declare const DEFAULT_VIEW_ROLES: readonly string[];
|
|
3
|
+
/** Where a materialized view's rows are stored. A frozen derived name. */
|
|
4
|
+
export declare const viewRowsName: (name: string) => string;
|
|
5
|
+
/** The comment the stored rows carry, beside the gate's `rebase:view:<hash>`. */
|
|
6
|
+
export declare const VIEW_ROWS_COMMENT_PREFIX = "rebase:view-rows:";
|
|
@@ -185,3 +185,26 @@ export declare function dropLegacyAuthSchema(run: (sql: string) => Promise<Recor
|
|
|
185
185
|
info: (m: string) => void;
|
|
186
186
|
warn: (m: string) => void;
|
|
187
187
|
}): Promise<void>;
|
|
188
|
+
/**
|
|
189
|
+
* `rebase.is_request_role(role)` — is `role` one of the roles this database's
|
|
190
|
+
* requests run as? The predicate `rls.policyTarget: "requestRole"` ANDs into
|
|
191
|
+
* every permissive policy (`RLS_IS_REQUEST_ROLE_SQL`), called with
|
|
192
|
+
* `current_user`.
|
|
193
|
+
*
|
|
194
|
+
* SECURITY DEFINER because the recorded roles live in `rebase.schema_meta`,
|
|
195
|
+
* which the request roles cannot read. That is also why the caller's role is
|
|
196
|
+
* an argument: inside the function `current_user` is its owner. The body is
|
|
197
|
+
* dynamic SQL so the function can be created before the table exists — in
|
|
198
|
+
* Atlas's replay of the migrations, for one. With nothing recorded the answer
|
|
199
|
+
* is `rebase_user`, as everywhere else.
|
|
200
|
+
*
|
|
201
|
+
* Created only for a project that asks for `policyTarget: "requestRole"`, so
|
|
202
|
+
* every other project's migrations and boot are exactly what they were.
|
|
203
|
+
*/
|
|
204
|
+
export declare const REQUEST_ROLE_FUNCTION_SQL = "CREATE OR REPLACE FUNCTION rebase.is_request_role(role_name text) RETURNS boolean AS $$\nDECLARE\n request_roles text[];\nBEGIN\n IF to_regclass('\"rebase\".\"schema_meta\"') IS NOT NULL THEN\n EXECUTE 'SELECT string_to_array(value, '','') FROM \"rebase\".\"schema_meta\" WHERE key = ''request_roles'''\n INTO request_roles;\n END IF;\n RETURN role_name = ANY(COALESCE(request_roles, ARRAY['rebase_user']));\nEND\n$$ LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path = pg_catalog";
|
|
205
|
+
/**
|
|
206
|
+
* Create {@link REQUEST_ROLE_FUNCTION_SQL} when it is missing or its body
|
|
207
|
+
* differs — replacing an unchanged function would still invalidate every
|
|
208
|
+
* cached plan of every policy that calls it.
|
|
209
|
+
*/
|
|
210
|
+
export declare function ensureRequestRoleFunction(run: (sql: string) => Promise<Record<string, unknown>[]>): Promise<void>;
|