@rebasepro/server-postgres 0.30.0 → 0.31.0-canary.g59cd6fd
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/README.md +11 -8
- package/dist/{BranchService-CrXvcES2.js → BranchService-USp1AvZB.js} +3 -3
- package/dist/{BranchService-CrXvcES2.js.map → BranchService-USp1AvZB.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +99 -54
- package/dist/PostgresBootstrapper.d.ts +12 -27
- package/dist/auth/ensure-tables.d.ts +16 -5
- package/dist/auth/schema-version.d.ts +2 -2
- package/dist/auth/services.d.ts +2 -3
- package/dist/{auth-users-columns-C72EMoDJ.js → auth-users-columns-BpfgbkxZ.js} +2 -16
- package/dist/auth-users-columns-BpfgbkxZ.js.map +1 -0
- package/dist/{backup-cli-CTKCOLpX.js → backup-cli-DbKyEj6c.js} +4 -4
- package/dist/{backup-cli-CTKCOLpX.js.map → backup-cli-DbKyEj6c.js.map} +1 -1
- package/dist/{boot-ddl-CqGIwSYx.js → boot-ddl-5H2bL_80.js} +2 -2
- package/dist/{boot-ddl-CqGIwSYx.js.map → boot-ddl-5H2bL_80.js.map} +1 -1
- package/dist/{cli-console-DBPw-oAz.js → cli-console-DsRgGSBR.js} +65 -39
- package/dist/cli-console-DsRgGSBR.js.map +1 -0
- package/dist/cli-console.d.ts +16 -13
- package/dist/cli-flags.d.ts +8 -9
- package/dist/cli-helpers.d.ts +15 -11
- package/dist/{cli-errors-DYTxnLbW.js → cli-schema-dir-CiN0ephV.js} +184 -70
- package/dist/cli-schema-dir-CiN0ephV.js.map +1 -0
- package/dist/cli-schema-dir.d.ts +64 -0
- package/dist/cli.js +192 -257
- package/dist/cli.js.map +1 -1
- package/dist/data-transformer.d.ts +50 -19
- package/dist/{database-preflight-iBpT7-vv.js → database-preflight-bfnIBnjM.js} +5 -5
- package/dist/database-preflight-bfnIBnjM.js.map +1 -0
- package/dist/{deferred-index-build-BCU9RoHK.js → deferred-index-build-CcSDA7wE.js} +69 -13
- package/dist/deferred-index-build-CcSDA7wE.js.map +1 -0
- package/dist/{ensure-collection-policies-Bo-_fDAy.js → ensure-policies-rRmXb5bt.js} +31 -31
- package/dist/ensure-policies-rRmXb5bt.js.map +1 -0
- package/dist/{ensure-collection-tables-DCJINkT_.js → ensure-tables-Bvm-F2wW.js} +44 -37
- package/dist/ensure-tables-Bvm-F2wW.js.map +1 -0
- package/dist/{ensure-tables-BPGaGh0y.js → ensure-tables-CC8p_AK3.js} +34 -29
- package/dist/ensure-tables-CC8p_AK3.js.map +1 -0
- package/dist/{enum-labels-kept-YAgOZS4I.js → enum-labels-kept-FlX9SHdf.js} +8 -8
- package/dist/enum-labels-kept-FlX9SHdf.js.map +1 -0
- package/dist/{generate-drizzle-schema-DcrFr7YX.js → generate-drizzle-schema-SJMXxzPI.js} +12 -12
- package/dist/generate-drizzle-schema-SJMXxzPI.js.map +1 -0
- package/dist/{generate-drizzle-schema-logic-LTLZvt6r.js → generate-drizzle-schema-logic-DL7R1rAF.js} +15 -8
- package/dist/generate-drizzle-schema-logic-DL7R1rAF.js.map +1 -0
- package/dist/{generate-files-CsaVzatS.js → generate-files-tlJ9_lGI.js} +23 -30
- package/dist/generate-files-tlJ9_lGI.js.map +1 -0
- package/dist/{generate-next-step-DgK5BlBn.js → generate-next-step-CO09dovd.js} +3 -3
- package/dist/generate-next-step-CO09dovd.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-Dg0bcENZ.js → generate-postgres-ddl-logic-B8huc03c.js} +51 -21
- package/dist/generate-postgres-ddl-logic-B8huc03c.js.map +1 -0
- package/dist/{generated-schema-diff-By4dxyTH.js → generated-schema-diff-DoT2dYDe.js} +297 -279
- package/dist/generated-schema-diff-DoT2dYDe.js.map +1 -0
- package/dist/{generated-schema-staleness-BvNF3i-s.js → generated-schema-staleness-YBVq2kTn.js} +21 -29
- package/dist/generated-schema-staleness-YBVq2kTn.js.map +1 -0
- package/dist/history/ensure-history-table.d.ts +22 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.es.js +201 -25
- package/dist/index.es.js.map +1 -1
- package/dist/interfaces.d.ts +3 -4
- package/dist/{introspect-db-queries-DevUrzll.js → introspect-db-queries-BgiRQqtR.js} +7 -2
- package/dist/introspect-db-queries-BgiRQqtR.js.map +1 -0
- package/dist/introspect-tables-Cw_A-kk4.js +2086 -0
- package/dist/introspect-tables-Cw_A-kk4.js.map +1 -0
- package/dist/load-tables-B1Re74ng.js +92 -0
- package/dist/load-tables-B1Re74ng.js.map +1 -0
- package/dist/{migrate-baseline-CmWXL7qx.js → migrate-baseline-DZmekgpD.js} +19 -32
- package/dist/migrate-baseline-DZmekgpD.js.map +1 -0
- package/dist/{migrate-policy-stamps-BN_Qad6c.js → migrate-policy-stamps-B_acrUQB.js} +18 -19
- package/dist/migrate-policy-stamps-B_acrUQB.js.map +1 -0
- package/dist/model/PostgresTableRegistry.d.ts +159 -0
- package/dist/model/build-registry.d.ts +25 -0
- package/dist/model/refresh-relational-schema.d.ts +24 -0
- package/dist/model/runtime-table.d.ts +53 -0
- package/dist/{collections → model}/validate-relations.d.ts +15 -21
- package/dist/{open-rebase-40paQfVW.js → open-rebase-4kisUF_k.js} +3946 -3870
- package/dist/open-rebase-4kisUF_k.js.map +1 -0
- package/dist/open-rebase.d.ts +16 -15
- package/dist/{pg-error-utils-DJHjCF7-.js → pg-error-utils-BT5NzGFZ.js} +17 -20
- package/dist/pg-error-utils-BT5NzGFZ.js.map +1 -0
- package/dist/plan-schema-Hbtjhge3.js +1633 -0
- package/dist/plan-schema-Hbtjhge3.js.map +1 -0
- package/dist/{policy-drift-C-m0uWHH.js → policy-drift-BVMyqHSa.js} +29 -29
- package/dist/policy-drift-BVMyqHSa.js.map +1 -0
- package/dist/{push-index-adoption-Cp7oZxSl.js → push-index-adoption-hpHTyXMR.js} +7 -7
- package/dist/push-index-adoption-hpHTyXMR.js.map +1 -0
- package/dist/{push-index-prebuild-DbwKGtQT.js → push-index-prebuild-Bty9F7bD.js} +6 -6
- package/dist/push-index-prebuild-Bty9F7bD.js.map +1 -0
- package/dist/{push-kept-defaults-CLcgsEPt.js → push-kept-defaults-Bst4MDup.js} +13 -16
- package/dist/push-kept-defaults-Bst4MDup.js.map +1 -0
- package/dist/{push-legacy-renames-BthD0E9W.js → push-legacy-renames-bB4bM6br.js} +6 -6
- package/dist/push-legacy-renames-bB4bM6br.js.map +1 -0
- package/dist/{push-policy-plan-BgcrroxQ.js → push-policy-plan-BI8U4BOD.js} +11 -11
- package/dist/push-policy-plan-BI8U4BOD.js.map +1 -0
- package/dist/{render-ddl-Ci3S_SoI.js → render-ddl-D4n86NHz.js} +14 -7
- package/dist/render-ddl-D4n86NHz.js.map +1 -0
- package/dist/{request-role-cli-Dy1EgJU9.js → request-role-cli-BdRzdE87.js} +11 -11
- package/dist/{request-role-cli-Dy1EgJU9.js.map → request-role-cli-BdRzdE87.js.map} +1 -1
- package/dist/{request-role-migration-GHTJnPMV.js → request-role-migration-C8aq_TO3.js} +2 -2
- package/dist/{request-role-migration-GHTJnPMV.js.map → request-role-migration-C8aq_TO3.js.map} +1 -1
- package/dist/{rls-enforcement-Cc_UhOxb.js → rls-enforcement-DB5HHj96.js} +19 -19
- package/dist/rls-enforcement-DB5HHj96.js.map +1 -0
- package/dist/{rls-settings-BCGMIig3.js → rls-settings-CmGK2U0a.js} +2 -2
- package/dist/rls-settings-CmGK2U0a.js.map +1 -0
- package/dist/schema/auth-users-columns.d.ts +1 -11
- package/dist/schema/catalogue-schema.d.ts +33 -29
- package/dist/schema/classify-change.d.ts +23 -16
- package/dist/schema/column-type-drift.d.ts +16 -0
- package/dist/schema/config-relations.d.ts +10 -9
- package/dist/schema/deferred-index-build.d.ts +1 -1
- package/dist/schema/doctor-cli.js +1544 -66
- package/dist/schema/doctor-cli.js.map +1 -1
- package/dist/schema/doctor-database.d.ts +7 -7
- package/dist/schema/doctor-policy-checks.d.ts +4 -4
- package/dist/schema/doctor-search-scale.d.ts +14 -14
- package/dist/schema/doctor.d.ts +27 -27
- package/dist/schema/dynamic-tables.d.ts +6 -5
- package/dist/schema/{ensure-collection-policies.d.ts → ensure-policies.d.ts} +20 -20
- package/dist/schema/{ensure-collection-tables.d.ts → ensure-tables.d.ts} +11 -11
- package/dist/schema/enum-labels-kept.d.ts +6 -6
- package/dist/schema/generate-drizzle-schema-logic.d.ts +3 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-files.d.ts +6 -6
- package/dist/schema/generate-postgres-ddl-logic.d.ts +23 -20
- package/dist/schema/generate-postgres-ddl.js +11 -11
- package/dist/schema/generate-postgres-ddl.js.map +1 -1
- package/dist/schema/generate-schema-commit.d.ts +13 -8
- package/dist/schema/generated-schema-diff.d.ts +16 -16
- package/dist/schema/generated-schema-staleness.d.ts +11 -11
- package/dist/schema/index-adoption.d.ts +4 -4
- package/dist/schema/introspect-db-customization.d.ts +47 -0
- package/dist/schema/introspect-db-inference.d.ts +30 -9
- package/dist/schema/introspect-db-logic.d.ts +79 -110
- package/dist/schema/introspect-db-project.d.ts +15 -18
- package/dist/schema/introspect-db-queries.d.ts +1 -1
- package/dist/schema/introspect-db-search.d.ts +25 -4
- package/dist/schema/introspect-db-storage.d.ts +4 -74
- package/dist/schema/introspect-db.js +102 -90
- package/dist/schema/introspect-db.js.map +1 -1
- package/dist/schema/introspect-runtime.d.ts +47 -36
- package/dist/schema/introspect-tables.d.ts +182 -0
- package/dist/schema/load-tables.d.ts +55 -0
- package/dist/schema/migrate-policy-stamps.d.ts +4 -4
- package/dist/schema/migration-freshness.d.ts +13 -13
- package/dist/schema/plan/column-order.d.ts +82 -0
- package/dist/schema/plan/diff-plan.d.ts +9 -3
- package/dist/schema/plan/plan-schema.d.ts +55 -52
- package/dist/schema/plan/render-drizzle.d.ts +1 -1
- package/dist/schema/plan/types.d.ts +24 -15
- package/dist/schema/push-index-adoption.d.ts +3 -3
- package/dist/schema/push-index-prebuild.d.ts +3 -3
- package/dist/schema/push-kept-defaults.d.ts +7 -7
- package/dist/schema/push-legacy-renames.d.ts +3 -3
- package/dist/schema/push-policy-plan.d.ts +5 -5
- package/dist/schema/reconcile-schema.d.ts +5 -5
- package/dist/schema/relation-names.d.ts +15 -20
- package/dist/schema/render-outputs.d.ts +76 -0
- package/dist/schema/search-column.d.ts +11 -43
- package/dist/schema/{collection-index.d.ts → table-index.d.ts} +21 -42
- package/dist/schema/{collections-schema-version.d.ts → tables-schema-version.d.ts} +8 -2
- package/dist/schema/vector-index.d.ts +24 -28
- package/dist/{search-column-BM-GV6vH.js → search-column-BO-WND-B.js} +86 -149
- package/dist/search-column-BO-WND-B.js.map +1 -0
- package/dist/security/caller-sql-columns.d.ts +9 -6
- package/dist/security/policy-drift.d.ts +14 -14
- package/dist/security/rls-enforcement.d.ts +19 -25
- package/dist/security/rls-settings.d.ts +2 -2
- package/dist/security/served-table-protection.d.ts +125 -0
- package/dist/services/FetchService.d.ts +22 -133
- package/dist/services/PersistService.d.ts +6 -17
- package/dist/services/RelationService.d.ts +57 -106
- package/dist/services/RelationWriteService.d.ts +59 -66
- package/dist/services/cdc/identity-columns.d.ts +7 -5
- package/dist/services/cdc/junction-tables.d.ts +14 -14
- package/dist/services/collection-helpers.d.ts +52 -95
- package/dist/services/dataService.d.ts +15 -12
- package/dist/services/field-op-sql.d.ts +11 -9
- package/dist/services/field-viewer.d.ts +12 -11
- package/dist/services/hidden-columns.d.ts +30 -0
- package/dist/services/index.d.ts +1 -1
- package/dist/services/junction-writes.d.ts +37 -18
- package/dist/services/nested-path.d.ts +18 -18
- package/dist/services/read-field-access.d.ts +23 -7
- package/dist/services/read-scope.d.ts +10 -9
- package/dist/services/realtimeService.d.ts +25 -10
- package/dist/services/relation-tables.d.ts +97 -0
- package/dist/services/row-pipeline.d.ts +50 -69
- package/dist/services/soft-delete.d.ts +25 -24
- package/dist/services/table-hooks.d.ts +146 -0
- package/dist/services/view-access.d.ts +7 -7
- package/dist/services/write-transaction-scope.d.ts +1 -1
- package/dist/{source-fZb92pN8.js → source-VxbrQojV.js} +111 -79
- package/dist/source-VxbrQojV.js.map +1 -0
- package/dist/{collections-schema-version-D7bDI0PJ.js → tables-schema-version-YvZIBlOP.js} +12 -6
- package/dist/tables-schema-version-YvZIBlOP.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +70 -84
- package/dist/utils/pg-array-null-patch.d.ts +27 -10
- package/dist/utils/pg-error-utils.d.ts +4 -4
- package/dist/{vector-index-DsQ3V2d2.js → vector-index-VSh3ufTd.js} +62 -54
- package/dist/vector-index-VSh3ufTd.js.map +1 -0
- package/dist/{websocket-B7ex6AQM.js → websocket-BevXvwfo.js} +51 -40
- package/dist/websocket-BevXvwfo.js.map +1 -0
- package/dist/websocket.d.ts +2 -2
- package/package.json +7 -7
- package/dist/auth-users-columns-C72EMoDJ.js.map +0 -1
- package/dist/cli-collections-path.d.ts +0 -31
- package/dist/cli-console-DBPw-oAz.js.map +0 -1
- package/dist/cli-errors-DYTxnLbW.js.map +0 -1
- package/dist/collections/PostgresCollectionRegistry.d.ts +0 -47
- package/dist/collections/buildRegistry.d.ts +0 -27
- package/dist/collections-schema-version-D7bDI0PJ.js.map +0 -1
- package/dist/column-plan-helpers-BeSztMor.js +0 -161
- package/dist/column-plan-helpers-BeSztMor.js.map +0 -1
- package/dist/database-preflight-iBpT7-vv.js.map +0 -1
- package/dist/deferred-index-build-BCU9RoHK.js.map +0 -1
- package/dist/doctor-Kg1oUK0Q.js +0 -1458
- package/dist/doctor-Kg1oUK0Q.js.map +0 -1
- package/dist/ensure-collection-policies-Bo-_fDAy.js.map +0 -1
- package/dist/ensure-collection-tables-DCJINkT_.js.map +0 -1
- package/dist/ensure-tables-BPGaGh0y.js.map +0 -1
- package/dist/enum-labels-kept-YAgOZS4I.js.map +0 -1
- package/dist/generate-drizzle-schema-DcrFr7YX.js.map +0 -1
- package/dist/generate-drizzle-schema-logic-LTLZvt6r.js.map +0 -1
- package/dist/generate-files-CsaVzatS.js.map +0 -1
- package/dist/generate-next-step-DgK5BlBn.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-Dg0bcENZ.js.map +0 -1
- package/dist/generated-schema-diff-By4dxyTH.js.map +0 -1
- package/dist/generated-schema-staleness-BvNF3i-s.js.map +0 -1
- package/dist/introspect-db-logic-DWqAEURB.js +0 -2047
- package/dist/introspect-db-logic-DWqAEURB.js.map +0 -1
- package/dist/introspect-db-queries-DevUrzll.js.map +0 -1
- package/dist/migrate-baseline-CmWXL7qx.js.map +0 -1
- package/dist/migrate-policy-stamps-BN_Qad6c.js.map +0 -1
- package/dist/open-rebase-40paQfVW.js.map +0 -1
- package/dist/pg-error-utils-DJHjCF7-.js.map +0 -1
- package/dist/plan-schema-vJd3UEmT.js +0 -1604
- package/dist/plan-schema-vJd3UEmT.js.map +0 -1
- package/dist/policy-drift-C-m0uWHH.js.map +0 -1
- package/dist/push-index-adoption-Cp7oZxSl.js.map +0 -1
- package/dist/push-index-prebuild-DbwKGtQT.js.map +0 -1
- package/dist/push-kept-defaults-CLcgsEPt.js.map +0 -1
- package/dist/push-legacy-renames-BthD0E9W.js.map +0 -1
- package/dist/push-policy-plan-BgcrroxQ.js.map +0 -1
- package/dist/render-ddl-Ci3S_SoI.js.map +0 -1
- package/dist/rls-enforcement-Cc_UhOxb.js.map +0 -1
- package/dist/rls-settings-BCGMIig3.js.map +0 -1
- package/dist/schema/column-plan-helpers.d.ts +0 -161
- package/dist/schema/introspect-db-naming.d.ts +0 -10
- package/dist/search-column-BM-GV6vH.js.map +0 -1
- package/dist/source-fZb92pN8.js.map +0 -1
- package/dist/vector-index-DsQ3V2d2.js.map +0 -1
- package/dist/websocket-B7ex6AQM.js.map +0 -1
|
@@ -0,0 +1,2086 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from "module";
|
|
2
|
+
__createRequire(import.meta.url);
|
|
3
|
+
import { c as searchColumnStamps, i as buildTableSearchColumnSpec } from "./search-column-BO-WND-B.js";
|
|
4
|
+
import { u as foreignKeyIndexSpec } from "./source-VxbrQojV.js";
|
|
5
|
+
import { i as readSchemaMetadata } from "./introspect-db-queries-BgiRQqtR.js";
|
|
6
|
+
import { DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, columnTypeLabel } from "@rebasepro/types";
|
|
7
|
+
import { classifyTable, policyToSecurityRule, printIndexModule, printTableModule, tableGeneratedPolicyNames, tableIdentifier } from "@rebasepro/common";
|
|
8
|
+
import { firstFreeKey, toWireKey } from "@rebasepro/utils";
|
|
9
|
+
//#region src/schema/introspect-db-inference.ts
|
|
10
|
+
var MARKDOWN = [
|
|
11
|
+
/^#{1,6}\s+.+/m,
|
|
12
|
+
/\*\*.+\*\*/,
|
|
13
|
+
/\[.+\]\(.+\)/,
|
|
14
|
+
/^\s*[-*]\s+.+/m
|
|
15
|
+
];
|
|
16
|
+
var IMAGE_FILE = /\.(jpeg|jpg|gif|png|webp|svg)(\?|$)/i;
|
|
17
|
+
var MEDIA_NAME = /image|avatar|photo|logo|cover/;
|
|
18
|
+
var isNumericType = (type) => [
|
|
19
|
+
"smallint",
|
|
20
|
+
"integer",
|
|
21
|
+
"bigint",
|
|
22
|
+
"real",
|
|
23
|
+
"doublePrecision",
|
|
24
|
+
"numeric"
|
|
25
|
+
].includes(type.kind);
|
|
26
|
+
var isTextType = (type) => type.kind === "text" || type.kind === "varchar" || type.kind === "char";
|
|
27
|
+
/**
|
|
28
|
+
* Read a column's sampled values for what they add to its declared type.
|
|
29
|
+
*
|
|
30
|
+
* - a number column named like a percentage (`*percent*`, `*rate*`, `*score*`)
|
|
31
|
+
* whose values lie in 0–100 is validated to that range; one named like a
|
|
32
|
+
* quantity (`*count*`, `*total*`, `*amount*`) with no negative value, to `min: 0`;
|
|
33
|
+
* - a text column whose every value is an absolute URL is validated as one,
|
|
34
|
+
* and previewed as an image when the values (or the name) say so;
|
|
35
|
+
* - a text column holding markdown is edited as markdown, one holding line
|
|
36
|
+
* breaks or long values in a multi-line box.
|
|
37
|
+
*/
|
|
38
|
+
function inferColumnHints(columnName, type, sampleValues) {
|
|
39
|
+
const values = sampleValues.filter((value) => value !== null && value !== void 0 && value !== "");
|
|
40
|
+
if (values.length === 0) return {};
|
|
41
|
+
const name = columnName.toLowerCase();
|
|
42
|
+
if (isNumericType(type)) {
|
|
43
|
+
const numbers = values.map(Number).filter((value) => !Number.isNaN(value));
|
|
44
|
+
if (numbers.length !== values.length) return {};
|
|
45
|
+
const min = Math.min(...numbers);
|
|
46
|
+
const max = Math.max(...numbers);
|
|
47
|
+
if (min >= 0 && max <= 100 && /percent|rate|score/.test(name)) return { validate: {
|
|
48
|
+
min: 0,
|
|
49
|
+
max: 100
|
|
50
|
+
} };
|
|
51
|
+
if (min >= 0 && /count|total|amount/.test(name)) return { validate: { min: 0 } };
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
if (!isTextType(type) || !values.every((value) => typeof value === "string")) return {};
|
|
55
|
+
const strings = values.filter((value) => typeof value === "string");
|
|
56
|
+
const hints = {};
|
|
57
|
+
if (strings.every((value) => value.startsWith("http://") || value.startsWith("https://"))) {
|
|
58
|
+
hints.validate = { url: true };
|
|
59
|
+
if (strings.some((value) => IMAGE_FILE.test(value)) || MEDIA_NAME.test(name)) hints.field = { urlPreview: "image" };
|
|
60
|
+
return hints;
|
|
61
|
+
}
|
|
62
|
+
const longest = Math.max(...strings.map((value) => value.length));
|
|
63
|
+
if (strings.some((value) => MARKDOWN.some((pattern) => pattern.test(value)))) hints.field = {
|
|
64
|
+
multiline: true,
|
|
65
|
+
markdown: true
|
|
66
|
+
};
|
|
67
|
+
else if (strings.some((value) => value.includes("\n")) || longest > 100) hints.field = { multiline: true };
|
|
68
|
+
return hints;
|
|
69
|
+
}
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region src/schema/introspect-db-types.ts
|
|
72
|
+
/**
|
|
73
|
+
* The PostgreSQL type → Rebase property type mapping.
|
|
74
|
+
*
|
|
75
|
+
* Split out of `introspect-db-logic` so that the structural analysis can use it
|
|
76
|
+
* without importing the generator, which imports the analysis. Re-exported from
|
|
77
|
+
* `introspect-db-logic` so existing callers keep their import path.
|
|
78
|
+
*/
|
|
79
|
+
/**
|
|
80
|
+
* Map a PostgreSQL data type to a Rebase property type.
|
|
81
|
+
*/
|
|
82
|
+
function mapPgType(dataType) {
|
|
83
|
+
const dt = dataType.toLowerCase();
|
|
84
|
+
if (dt === "interval") return "string";
|
|
85
|
+
if (dt === "array" || dt.startsWith("_")) return "array";
|
|
86
|
+
if (dt.includes("int") || dt.includes("numeric") || dt.includes("decimal") || dt.includes("serial") || dt === "real" || dt === "float4" || dt === "float8" || dt === "double precision" || dt === "money") return "number";
|
|
87
|
+
if (dt.includes("bool")) return "boolean";
|
|
88
|
+
if (dt.includes("time") || dt.includes("date")) return "date";
|
|
89
|
+
if (dt === "json" || dt === "jsonb") return "map";
|
|
90
|
+
if (dt === "bytea") return "binary";
|
|
91
|
+
if (dt === "inet" || dt === "cidr" || dt === "macaddr" || dt === "macaddr8") return "string";
|
|
92
|
+
if (dt === "uuid") return "string";
|
|
93
|
+
return "string";
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/schema/introspect-db-customization.ts
|
|
97
|
+
/** The package `customizeTable` is imported from. */
|
|
98
|
+
var CMS_PACKAGE = "@rebasepro/cms";
|
|
99
|
+
var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
100
|
+
var key = (name) => IDENTIFIER.test(name) ? name : JSON.stringify(name);
|
|
101
|
+
/** One value as source, four-space indented, `depth` levels in. Short scalar arrays stay on one line. */
|
|
102
|
+
function printCustomizationValue(value, depth = 0) {
|
|
103
|
+
const pad = " ".repeat(depth + 1);
|
|
104
|
+
const close = " ".repeat(depth);
|
|
105
|
+
if (typeof value === "string") return JSON.stringify(value);
|
|
106
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
107
|
+
if (Array.isArray(value)) {
|
|
108
|
+
const items = value;
|
|
109
|
+
if (items.length === 0) return "[]";
|
|
110
|
+
const scalars = items.every((item) => typeof item !== "object");
|
|
111
|
+
const inline = `[${items.map((item) => printCustomizationValue(item, depth)).join(", ")}]`;
|
|
112
|
+
if (scalars && inline.length <= 80) return inline;
|
|
113
|
+
return `[\n${items.map((item) => `${pad}${printCustomizationValue(item, depth + 1)}`).join(",\n")}\n${close}]`;
|
|
114
|
+
}
|
|
115
|
+
const entries = Object.entries(value).filter((entry) => entry[1] !== void 0);
|
|
116
|
+
if (entries.length === 0) return "{}";
|
|
117
|
+
return `{\n${entries.map(([name, item]) => `${pad}${key(name)}: ${printCustomizationValue(item, depth + 1)}`).join(",\n")}\n${close}}`;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* The whole module:
|
|
121
|
+
*
|
|
122
|
+
* ```ts
|
|
123
|
+
* import { customizeTable } from "@rebasepro/cms";
|
|
124
|
+
* import type { film } from "../../../backend/schema/film";
|
|
125
|
+
*
|
|
126
|
+
* export const filmCms = customizeTable<typeof film>("film", { … });
|
|
127
|
+
* ```
|
|
128
|
+
*/
|
|
129
|
+
function printCustomizationModule(module) {
|
|
130
|
+
const comments = (module.comments ?? []).map((line) => `// ${line.replace(/\s*[\r\n]+\s*/g, " ")}`);
|
|
131
|
+
return [
|
|
132
|
+
`import { customizeTable } from ${JSON.stringify(CMS_PACKAGE)};`,
|
|
133
|
+
`import type { ${module.tableIdentifier} } from ${JSON.stringify(module.tableImport)};`,
|
|
134
|
+
"",
|
|
135
|
+
...comments,
|
|
136
|
+
`export const ${module.tableIdentifier}Cms = customizeTable<typeof ${module.tableIdentifier}>(${JSON.stringify(module.slug)}, ${printCustomizationValue(module.options)});`,
|
|
137
|
+
""
|
|
138
|
+
].join("\n");
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* A timestamp the database maintains: a temporal column defaulting to the
|
|
142
|
+
* transaction clock.
|
|
143
|
+
*
|
|
144
|
+
* This is the structural stand-in for the `created_at`/`updated_at` name check.
|
|
145
|
+
* It is strictly better than the name: it catches `fecha_creacion` and
|
|
146
|
+
* `last_update` (pagila's spelling, which the name list misses), and it does not
|
|
147
|
+
* fire on a user-editable `created_at date` column that has no default and which
|
|
148
|
+
* the name check would wrongly make read-only.
|
|
149
|
+
*/
|
|
150
|
+
function isAutoTimestamp(column) {
|
|
151
|
+
if (mapPgType(column.data_type) !== "date") return false;
|
|
152
|
+
const columnDefault = (column.column_default ?? "").toLowerCase();
|
|
153
|
+
if (!columnDefault) return false;
|
|
154
|
+
return /\b(now\(\)|current_timestamp|current_date|current_time|localtimestamp|localtime|transaction_timestamp\(\)|statement_timestamp\(\)|clock_timestamp\(\))/.test(columnDefault);
|
|
155
|
+
}
|
|
156
|
+
/** A column Postgres computes; writing to it is an error. */
|
|
157
|
+
function isGeneratedColumn(column) {
|
|
158
|
+
return column.is_generated === "ALWAYS";
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Types that exist to be searched or indexed, never to be typed into.
|
|
162
|
+
*
|
|
163
|
+
* A `tsvector` column is a derived search index — maintained by a trigger, a
|
|
164
|
+
* generated expression, or an application job — and its contents are lexeme
|
|
165
|
+
* positions, not text. Pagila's `film.fulltext` is one, and introspection used
|
|
166
|
+
* to emit it as an ordinary required string: a mandatory form field whose
|
|
167
|
+
* correct value no user can produce, on the sixth column of the list view.
|
|
168
|
+
*/
|
|
169
|
+
function isDerivedIndexColumn(column) {
|
|
170
|
+
return column.udt_name === "tsvector" || column.udt_name === "tsquery";
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* A string column with a declared maximum length.
|
|
174
|
+
*
|
|
175
|
+
* `varchar(50)` and `text` are the same type to an application but not to the
|
|
176
|
+
* author: choosing a bound is a statement that the value is short and
|
|
177
|
+
* label-like, which is what makes this usable for picking a display column.
|
|
178
|
+
*/
|
|
179
|
+
function isBoundedString(column) {
|
|
180
|
+
return mapPgType(column.data_type) === "string" && typeof column.character_maximum_length === "number" && column.character_maximum_length > 0;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* A column carrying data rather than structure: not a key, not a foreign key,
|
|
184
|
+
* not a database-maintained timestamp, not computed.
|
|
185
|
+
*
|
|
186
|
+
* The count of these is what tells a pure join table from an association that
|
|
187
|
+
* carries its own attributes — `northwind.order_details` has the key shape of a
|
|
188
|
+
* junction and three payload columns, so it is not one.
|
|
189
|
+
*/
|
|
190
|
+
function isPayloadColumn(column, pks, fkColumns) {
|
|
191
|
+
if (pks.includes(column.column_name)) return false;
|
|
192
|
+
if (fkColumns.has(column.column_name)) return false;
|
|
193
|
+
if (isAutoTimestamp(column)) return false;
|
|
194
|
+
if (isGeneratedColumn(column)) return false;
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Groups per-column foreign key rows back into constraints.
|
|
199
|
+
*
|
|
200
|
+
* Rows arrive one per referencing column. A composite key looks exactly like two
|
|
201
|
+
* separate keys until they are grouped by constraint name, and the difference
|
|
202
|
+
* matters: two single-column keys to two tables can be a junction, one
|
|
203
|
+
* two-column key never is.
|
|
204
|
+
*/
|
|
205
|
+
function groupForeignKeys(fks) {
|
|
206
|
+
const byName = /* @__PURE__ */ new Map();
|
|
207
|
+
for (const fk of fks) {
|
|
208
|
+
const key = `${fk.table_name}::${fk.constraint_name ?? `${fk.column_name}->${fk.foreign_table_name}`}`;
|
|
209
|
+
const existing = byName.get(key);
|
|
210
|
+
if (existing) {
|
|
211
|
+
existing.columns.push(fk.column_name);
|
|
212
|
+
existing.foreignColumns.push(fk.foreign_column_name);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
byName.set(key, {
|
|
216
|
+
name: fk.constraint_name ?? `${fk.table_name}_${fk.column_name}_fkey`,
|
|
217
|
+
table: fk.table_name,
|
|
218
|
+
columns: [fk.column_name],
|
|
219
|
+
foreignTable: fk.foreign_table_name,
|
|
220
|
+
foreignColumns: [fk.foreign_column_name],
|
|
221
|
+
deleteRule: fk.delete_rule
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
return Array.from(byName.values());
|
|
225
|
+
}
|
|
226
|
+
/** Column sets that are unique in a table: its primary key and every unique index. */
|
|
227
|
+
function uniqueColumnSets(table, pks, uniques) {
|
|
228
|
+
const sets = [];
|
|
229
|
+
if (pks.length > 0) sets.push(pks);
|
|
230
|
+
for (const unique of uniques) if (unique.table_name === table) sets.push(unique.column_names);
|
|
231
|
+
return sets;
|
|
232
|
+
}
|
|
233
|
+
function sameColumnSet(a, b) {
|
|
234
|
+
if (a.length !== b.length) return false;
|
|
235
|
+
const left = [...a].sort();
|
|
236
|
+
const right = [...b].sort();
|
|
237
|
+
return left.every((value, index) => value === right[index]);
|
|
238
|
+
}
|
|
239
|
+
function buildContext(metadata, tables) {
|
|
240
|
+
const allConstraints = groupForeignKeys(metadata.fks);
|
|
241
|
+
const constraintsByTable = /* @__PURE__ */ new Map();
|
|
242
|
+
const inboundByTable = /* @__PURE__ */ new Map();
|
|
243
|
+
for (const constraint of allConstraints) {
|
|
244
|
+
const outbound = constraintsByTable.get(constraint.table) ?? [];
|
|
245
|
+
outbound.push(constraint);
|
|
246
|
+
constraintsByTable.set(constraint.table, outbound);
|
|
247
|
+
const inbound = inboundByTable.get(constraint.foreignTable) ?? [];
|
|
248
|
+
inbound.push(constraint);
|
|
249
|
+
inboundByTable.set(constraint.foreignTable, inbound);
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
schema: metadata.schema,
|
|
253
|
+
tables,
|
|
254
|
+
constraintsByTable,
|
|
255
|
+
inboundByTable,
|
|
256
|
+
uniques: metadata.uniques,
|
|
257
|
+
rowCounts: metadata.rowCounts
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* A table that exists only to relate two others.
|
|
262
|
+
*
|
|
263
|
+
* Requires all of:
|
|
264
|
+
* - exactly two single-column foreign keys, to two distinct columns;
|
|
265
|
+
* - that pair is unique — it is the primary key, or a unique index covers it.
|
|
266
|
+
* Without this the table can hold the same pair twice, which is a list of
|
|
267
|
+
* events between two things, not a set membership;
|
|
268
|
+
* - no payload columns. A join row that carries a quantity is an association
|
|
269
|
+
* with attributes, and collapsing it into a many-to-many silently drops those
|
|
270
|
+
* attributes from the UI entirely;
|
|
271
|
+
* - nothing references it. A junction with its own dependents is something rows
|
|
272
|
+
* point *at*, so it needs an identity of its own;
|
|
273
|
+
* - it is in `public`. That is the only schema Rebase reads and creates
|
|
274
|
+
* junction tables in (`resolveTableJunctions`), so a `manyToMany` folded from
|
|
275
|
+
* `crm.contacts_tags` would read and write an empty `public.contacts_tags`
|
|
276
|
+
* instead. Kept as a table, its rows stay where they are and are served.
|
|
277
|
+
*/
|
|
278
|
+
function classifyJunction(table, context) {
|
|
279
|
+
if (context.schema !== "public") return null;
|
|
280
|
+
const meta = context.tables.get(table);
|
|
281
|
+
if (!meta) return null;
|
|
282
|
+
const constraints = context.constraintsByTable.get(table) ?? [];
|
|
283
|
+
if (constraints.length !== 2) return null;
|
|
284
|
+
if (constraints.some((c) => c.columns.length !== 1)) return null;
|
|
285
|
+
const [first, second] = constraints;
|
|
286
|
+
if (first.columns[0] === second.columns[0]) return null;
|
|
287
|
+
if ((context.inboundByTable.get(table) ?? []).length > 0) return null;
|
|
288
|
+
const pair = [first.columns[0], second.columns[0]];
|
|
289
|
+
if (!uniqueColumnSets(table, meta.pks, context.uniques).some((set) => sameColumnSet(set, pair))) return null;
|
|
290
|
+
const fkColumns = new Set(pair);
|
|
291
|
+
if (meta.columns.filter((column) => isPayloadColumn(column, meta.pks, fkColumns)).length > 0) return null;
|
|
292
|
+
return {
|
|
293
|
+
table,
|
|
294
|
+
role: "junction",
|
|
295
|
+
reason: `only relates ${first.foreignTable} to ${second.foreignTable}: two foreign keys, unique together, no other data`,
|
|
296
|
+
junction: {
|
|
297
|
+
sourceTable: first.foreignTable,
|
|
298
|
+
sourceColumn: first.columns[0],
|
|
299
|
+
targetTable: second.foreignTable,
|
|
300
|
+
targetColumn: second.columns[0]
|
|
301
|
+
}
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* A policy expression that reads who is asking: the `app.uid` setting every
|
|
306
|
+
* request runs with, `rebase.uid()` (or the retired `auth.uid()`), the JWT,
|
|
307
|
+
* or the session's own role.
|
|
308
|
+
*/
|
|
309
|
+
var CALLER_IDENTITY = /current_setting\(\s*'app\.(uid|user_id|jwt)'|\b(rebase|auth)\.(uid|jwt)\s*\(|\bcurrent_user\b|\bsession_user\b/i;
|
|
310
|
+
/**
|
|
311
|
+
* The tables whose row-level security hands each caller rows of their own,
|
|
312
|
+
* with the policies that do it.
|
|
313
|
+
*
|
|
314
|
+
* Structure in the sense this module means: a policy is a rule the database
|
|
315
|
+
* enforces, and one that compares a row to the caller's identity says the rows
|
|
316
|
+
* belong to users. That is the app's data. A young database holds three
|
|
317
|
+
* customers and one order; by row count the customers are "a 3-row code list"
|
|
318
|
+
* and the orders a child reached only through them, and both go missing from
|
|
319
|
+
* the navigation of the app that owns them.
|
|
320
|
+
*/
|
|
321
|
+
function callerScopedTables(metadata) {
|
|
322
|
+
const scoped = /* @__PURE__ */ new Map();
|
|
323
|
+
for (const policy of metadata.policies ?? []) {
|
|
324
|
+
if (!CALLER_IDENTITY.test(policy.qual ?? "") && !CALLER_IDENTITY.test(policy.with_check ?? "")) continue;
|
|
325
|
+
scoped.set(policy.table_name, [...scoped.get(policy.table_name) ?? [], policy.policy_name]);
|
|
326
|
+
}
|
|
327
|
+
return scoped;
|
|
328
|
+
}
|
|
329
|
+
/** An entity because its policies give each user their own rows — see {@link callerScopedTables}. */
|
|
330
|
+
function classifyCallerScoped(table, perCaller) {
|
|
331
|
+
const policies = perCaller.get(table);
|
|
332
|
+
if (!policies) return null;
|
|
333
|
+
return {
|
|
334
|
+
table,
|
|
335
|
+
role: "entity",
|
|
336
|
+
reason: `its row-level security gives each user their own rows (${policies.join(", ")}), so they are the app's data`
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* A small, referenced, self-contained code list.
|
|
341
|
+
*
|
|
342
|
+
* Requires: something references it, it references nothing, it carries few and
|
|
343
|
+
* simple payload columns, and it is small — where "small" is a real count, not
|
|
344
|
+
* an estimate. `reltuples` is -1 on any table that has never been analyzed,
|
|
345
|
+
* which is every table in a freshly restored dump, so a count that is merely
|
|
346
|
+
* absent must not read as "small".
|
|
347
|
+
*/
|
|
348
|
+
function classifyLookup(table, context) {
|
|
349
|
+
if (!isLookupCandidate(table, context)) return null;
|
|
350
|
+
const rowCount = context.rowCounts[table];
|
|
351
|
+
if (typeof rowCount !== "number") return null;
|
|
352
|
+
if (rowCount < 1 || rowCount > 50) return null;
|
|
353
|
+
return {
|
|
354
|
+
table,
|
|
355
|
+
role: "lookup",
|
|
356
|
+
reason: `a ${rowCount}-row code list: referenced by ${(context.inboundByTable.get(table) ?? []).length} table(s), references none, 3 or fewer simple columns`
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* The structural half of the lookup test — everything except the row count.
|
|
361
|
+
*
|
|
362
|
+
* Separate because the count costs a query per table, and the caller only wants
|
|
363
|
+
* to pay it for tables that could possibly qualify.
|
|
364
|
+
*/
|
|
365
|
+
function isLookupCandidate(table, context) {
|
|
366
|
+
const meta = context.tables.get(table);
|
|
367
|
+
if (!meta) return false;
|
|
368
|
+
if ((context.constraintsByTable.get(table) ?? []).length > 0) return false;
|
|
369
|
+
if ((context.inboundByTable.get(table) ?? []).length === 0) return false;
|
|
370
|
+
const payload = meta.columns.filter((column) => isPayloadColumn(column, meta.pks, /* @__PURE__ */ new Set()));
|
|
371
|
+
if (payload.length > 3) return false;
|
|
372
|
+
return payload.every((column) => {
|
|
373
|
+
const type = mapPgType(column.data_type);
|
|
374
|
+
return type === "boolean" || type === "number" || type === "string";
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Names the tables whose classification depends on a row count.
|
|
379
|
+
*
|
|
380
|
+
* The caller counts these — and only these — before calling
|
|
381
|
+
* {@link classifyTables}. On a schema of any size this is a handful of tables,
|
|
382
|
+
* and the count itself is capped (see `countRowsUpTo`), so the whole extra cost
|
|
383
|
+
* is bounded regardless of how much data the database holds.
|
|
384
|
+
*/
|
|
385
|
+
function lookupCandidates(metadata, tables) {
|
|
386
|
+
const context = buildContext(metadata, tables);
|
|
387
|
+
return Array.from(tables.keys()).filter((table) => isLookupCandidate(table, context));
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Rows that belong to one parent row and are reached through it.
|
|
391
|
+
*
|
|
392
|
+
* Requires nothing to reference the table — a table others point at has an
|
|
393
|
+
* identity of its own and belongs in the navigation — and an *unambiguous*
|
|
394
|
+
* owner among its foreign keys. The evidence ladder runs strongest first; each
|
|
395
|
+
* rung is only taken when exactly one key satisfies it, so a table with two
|
|
396
|
+
* equally plausible parents stays an entity rather than being filed under a
|
|
397
|
+
* coin-flip.
|
|
398
|
+
*/
|
|
399
|
+
function classifyOwnedChild(table, context) {
|
|
400
|
+
const meta = context.tables.get(table);
|
|
401
|
+
if (!meta) return null;
|
|
402
|
+
const constraints = context.constraintsByTable.get(table) ?? [];
|
|
403
|
+
if (constraints.length === 0) return null;
|
|
404
|
+
if ((context.inboundByTable.get(table) ?? []).length > 0) return null;
|
|
405
|
+
const owner = pickOwner(meta, constraints);
|
|
406
|
+
if (!owner) return null;
|
|
407
|
+
return {
|
|
408
|
+
table,
|
|
409
|
+
role: "owned-child",
|
|
410
|
+
reason: `belongs to ${owner.constraint.foreignTable} (${describeEvidence(owner.evidence)}) and nothing else references it`,
|
|
411
|
+
owner: {
|
|
412
|
+
table: owner.constraint.foreignTable,
|
|
413
|
+
column: owner.constraint.columns[0],
|
|
414
|
+
evidence: owner.evidence
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
function describeEvidence(evidence) {
|
|
419
|
+
switch (evidence) {
|
|
420
|
+
case "cascade-delete": return "its only ON DELETE CASCADE foreign key";
|
|
421
|
+
case "identifying-key": return "its only foreign key inside the primary key";
|
|
422
|
+
case "sole-required-key": return "its only NOT NULL foreign key";
|
|
423
|
+
case "leading-key-column": return "the leading column of a primary key made only of foreign keys";
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
function pickOwner(meta, constraints) {
|
|
427
|
+
const singleColumn = constraints.filter((c) => c.columns.length === 1);
|
|
428
|
+
if (singleColumn.length === 0) return null;
|
|
429
|
+
const nullability = new Map(meta.columns.map((c) => [c.column_name, c.is_nullable === "NO"]));
|
|
430
|
+
const cascading = singleColumn.filter((c) => c.deleteRule === "CASCADE");
|
|
431
|
+
if (cascading.length === 1) return {
|
|
432
|
+
constraint: cascading[0],
|
|
433
|
+
evidence: "cascade-delete"
|
|
434
|
+
};
|
|
435
|
+
const identifying = singleColumn.filter((c) => meta.pks.includes(c.columns[0]));
|
|
436
|
+
if (identifying.length === 1) return {
|
|
437
|
+
constraint: identifying[0],
|
|
438
|
+
evidence: "identifying-key"
|
|
439
|
+
};
|
|
440
|
+
const required = singleColumn.filter((c) => nullability.get(c.columns[0]) === true);
|
|
441
|
+
if (required.length === 1) return {
|
|
442
|
+
constraint: required[0],
|
|
443
|
+
evidence: "sole-required-key"
|
|
444
|
+
};
|
|
445
|
+
if (identifying.length === meta.pks.length && meta.pks.length > 1) {
|
|
446
|
+
const leading = identifying.find((c) => c.columns[0] === meta.pks[0]);
|
|
447
|
+
if (leading) return {
|
|
448
|
+
constraint: leading,
|
|
449
|
+
evidence: "leading-key-column"
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Classifies every table in the schema.
|
|
456
|
+
*
|
|
457
|
+
* Order matters: junction is the most specific and most consequential (the
|
|
458
|
+
* table disappears), so it is tested first; then lookup, which needs no
|
|
459
|
+
* ownership reasoning; then ownership. Anything unmatched is an entity, which
|
|
460
|
+
* is also what every rule falls back to when its evidence is ambiguous.
|
|
461
|
+
*/
|
|
462
|
+
function classifyTables(metadata, tables) {
|
|
463
|
+
const context = buildContext(metadata, tables);
|
|
464
|
+
const result = /* @__PURE__ */ new Map();
|
|
465
|
+
const perCaller = callerScopedTables(metadata);
|
|
466
|
+
for (const table of tables.keys()) {
|
|
467
|
+
const classification = classifyJunction(table, context) ?? classifyCallerScoped(table, perCaller) ?? classifyLookup(table, context) ?? classifyOwnedChild(table, context) ?? {
|
|
468
|
+
table,
|
|
469
|
+
role: "entity",
|
|
470
|
+
reason: "no structural evidence that it is a join table, a code list, or owned by another table"
|
|
471
|
+
};
|
|
472
|
+
result.set(table, classification);
|
|
473
|
+
}
|
|
474
|
+
return result;
|
|
475
|
+
}
|
|
476
|
+
function buildColumnFacts(meta, metadata, enumMap, checkFacts) {
|
|
477
|
+
const fkColumns = new Set(meta.fks.map((fk) => fk.column_name));
|
|
478
|
+
const singleColumnUniques = new Set(metadata.uniques.filter((u) => u.table_name === meta.name && u.column_names.length === 1).map((u) => u.column_names[0]));
|
|
479
|
+
const tableChecks = checkFacts.get(meta.name);
|
|
480
|
+
const facts = /* @__PURE__ */ new Map();
|
|
481
|
+
for (const column of meta.columns) {
|
|
482
|
+
const pgEnum = column.data_type === "USER-DEFINED" ? enumMap.get(column.udt_name) : void 0;
|
|
483
|
+
const checkEnum = tableChecks?.get(column.column_name)?.enumValues;
|
|
484
|
+
facts.set(column.column_name, {
|
|
485
|
+
column,
|
|
486
|
+
isPk: meta.pks.includes(column.column_name),
|
|
487
|
+
isFk: fkColumns.has(column.column_name),
|
|
488
|
+
isUniqueAlone: singleColumnUniques.has(column.column_name),
|
|
489
|
+
isAutoTimestamp: isAutoTimestamp(column),
|
|
490
|
+
isGenerated: isGeneratedColumn(column),
|
|
491
|
+
enumValues: pgEnum ?? checkEnum,
|
|
492
|
+
propType: pgEnum ? "string" : mapPgType(column.data_type)
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
return facts;
|
|
496
|
+
}
|
|
497
|
+
/**
|
|
498
|
+
* The column that identifies a row to a human.
|
|
499
|
+
*
|
|
500
|
+
* Structural, in three rungs, strongest first:
|
|
501
|
+
*
|
|
502
|
+
* 1. A single-column unique constraint on a required string. This is as close
|
|
503
|
+
* as a schema comes to declaring "this is what a row is called": it is the
|
|
504
|
+
* column a person looks a row up by, and the database guarantees it picks
|
|
505
|
+
* out one row.
|
|
506
|
+
* 2. The first required string that declares a length, when the table also has
|
|
507
|
+
* strings that do not. Choosing `varchar(n)` for one column and `text` for
|
|
508
|
+
* another is the author distinguishing a label from prose.
|
|
509
|
+
* 3. The first required string in declaration order. Weak, but it is the same
|
|
510
|
+
* rung the panel's own fallback stands on, and column order carries real
|
|
511
|
+
* information — the identifying column of a table is written near the top of
|
|
512
|
+
* it, in every schema, in every language.
|
|
513
|
+
*
|
|
514
|
+
* Deliberately not: a column called `name`, or `title`. That works on English
|
|
515
|
+
* schemas written by someone who read the same tutorial. This picks
|
|
516
|
+
* `film.title`, `actor.first_name` and `category.name` out of pagila without
|
|
517
|
+
* knowing what any of those words mean.
|
|
518
|
+
*/
|
|
519
|
+
function deriveTitleProperty(facts) {
|
|
520
|
+
const candidates = Array.from(facts.values()).filter((f) => !f.isPk && !f.isFk && !f.isGenerated && f.propType === "string" && !f.enumValues && f.column.is_nullable === "NO");
|
|
521
|
+
if (candidates.length === 0) return void 0;
|
|
522
|
+
const unique = candidates.find((f) => f.isUniqueAlone);
|
|
523
|
+
if (unique) return unique.column.column_name;
|
|
524
|
+
const bounded = candidates.filter((f) => isBoundedString(f.column));
|
|
525
|
+
if (bounded.length > 0 && bounded.length < candidates.length) return bounded[0].column.column_name;
|
|
526
|
+
return candidates[0].column.column_name;
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* The enum column a board should have as its columns.
|
|
530
|
+
*
|
|
531
|
+
* A board needs a small, closed, always-present set of states. `NOT NULL` is
|
|
532
|
+
* required because a null has no column to sit in; the bounds keep out
|
|
533
|
+
* two-state flags (a filter, not a board) and long code lists (a scrolling
|
|
534
|
+
* table). The first qualifying column in declaration order wins, so the output
|
|
535
|
+
* is stable across runs.
|
|
536
|
+
*/
|
|
537
|
+
function deriveKanbanProperty(facts) {
|
|
538
|
+
for (const fact of facts.values()) {
|
|
539
|
+
if (fact.isPk || fact.isFk || fact.isGenerated) continue;
|
|
540
|
+
if (!fact.enumValues) continue;
|
|
541
|
+
if (fact.column.is_nullable !== "NO") continue;
|
|
542
|
+
if (fact.enumValues.length < 2 || fact.enumValues.length > 12) continue;
|
|
543
|
+
return fact.column.column_name;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
/** Names a string column goes by when it holds a board's card order (a fractional-indexing key). */
|
|
547
|
+
var ORDER_KEY_NAMES = /* @__PURE__ */ new Set([
|
|
548
|
+
"__order",
|
|
549
|
+
"order_key",
|
|
550
|
+
"sort_key",
|
|
551
|
+
"rank",
|
|
552
|
+
"lexorank",
|
|
553
|
+
"position_key"
|
|
554
|
+
]);
|
|
555
|
+
/**
|
|
556
|
+
* The string column that can hold a board's card order, or nothing.
|
|
557
|
+
*
|
|
558
|
+
* A board without `orderProperty` cannot keep a card's position within a
|
|
559
|
+
* column, and the config validator says so on every generate — so a board is
|
|
560
|
+
* emitted only when the table already has somewhere to store the order. A
|
|
561
|
+
* legacy table almost never does; asking its owner to add a hidden column
|
|
562
|
+
* just to satisfy generated output was the wrong way round.
|
|
563
|
+
*/
|
|
564
|
+
function deriveKanbanOrderProperty(facts) {
|
|
565
|
+
for (const fact of facts.values()) {
|
|
566
|
+
if (fact.isPk || fact.isFk || fact.isGenerated || fact.enumValues) continue;
|
|
567
|
+
if (fact.propType !== "string") continue;
|
|
568
|
+
if (!/^(text|character varying)$/.test(fact.column.data_type)) continue;
|
|
569
|
+
if (ORDER_KEY_NAMES.has(fact.column.column_name.toLowerCase())) return fact.column.column_name;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
/**
|
|
573
|
+
* The column a list should be sorted by, newest first.
|
|
574
|
+
*
|
|
575
|
+
* Only when the table has exactly one database-maintained timestamp. With two —
|
|
576
|
+
* a created and an updated stamp — the two orderings differ and the schema does
|
|
577
|
+
* not say which the user means, so neither is chosen.
|
|
578
|
+
*/
|
|
579
|
+
function deriveSort(facts) {
|
|
580
|
+
const stamps = Array.from(facts.values()).filter((f) => f.isAutoTimestamp);
|
|
581
|
+
if (stamps.length !== 1) return void 0;
|
|
582
|
+
return [stamps[0].column.column_name, "desc"];
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* The first `LIST_PROPERTIES_CAP` visible properties, or nothing.
|
|
586
|
+
*
|
|
587
|
+
* Returning nothing when the table is already narrow matters: `listProperties`
|
|
588
|
+
* that restates every column is config the reader has to check against the
|
|
589
|
+
* property list to discover it does nothing, and it silently stops new columns
|
|
590
|
+
* from appearing in the list view when someone adds one later.
|
|
591
|
+
*
|
|
592
|
+
* `hidden` names the properties already marked `hideFromCollection` — spending
|
|
593
|
+
* one of six columns on a value the list does not render is worse than not
|
|
594
|
+
* capping at all.
|
|
595
|
+
*/
|
|
596
|
+
function deriveListProperties(propertiesOrder, hidden = /* @__PURE__ */ new Set()) {
|
|
597
|
+
const visible = propertiesOrder.filter((key) => !hidden.has(key));
|
|
598
|
+
if (visible.length <= 6) return void 0;
|
|
599
|
+
return visible.slice(0, 6);
|
|
600
|
+
}
|
|
601
|
+
//#endregion
|
|
602
|
+
//#region src/schema/introspect-db-logic.ts
|
|
603
|
+
/**
|
|
604
|
+
* Introspection logic — pure functions and the pipeline that transforms
|
|
605
|
+
* raw PostgreSQL metadata into `backend/schema` source (and, for a project
|
|
606
|
+
* with a frontend, `frontend/src/cms` customizations).
|
|
607
|
+
*
|
|
608
|
+
* This module contains NO side-effects: no fs writes, no pg.Client creation,
|
|
609
|
+
* no process.exit. It is imported by introspect-db.ts (the CLI entry-point)
|
|
610
|
+
* and consumed directly by tests.
|
|
611
|
+
*/
|
|
612
|
+
/**
|
|
613
|
+
* The icon a table's name suggests, for its panel customization: `Database`
|
|
614
|
+
* when the name suggests none (and then no icon is written).
|
|
615
|
+
*/
|
|
616
|
+
function getIconForTable(tableName) {
|
|
617
|
+
const table = tableName.toLowerCase();
|
|
618
|
+
if (table.includes("user") || table.includes("account") || table.includes("member") || table.includes("customer") || table.includes("client") || table.includes("patient")) return "Users";
|
|
619
|
+
if (table.includes("post") || table.includes("article") || table.includes("blog") || table.includes("page")) return "FileText";
|
|
620
|
+
if (table.includes("product") || table.includes("item")) return "Package";
|
|
621
|
+
if (table.includes("order") || table.includes("cart") || table.includes("purchase") || table.includes("invoice")) return "ShoppingCart";
|
|
622
|
+
if (table.includes("setting") || table.includes("config")) return "Settings";
|
|
623
|
+
if (table.includes("tag") || table.includes("categor")) return "Tag";
|
|
624
|
+
if (table.includes("image") || table.includes("photo") || table.includes("media") || table.includes("asset")) return "Image";
|
|
625
|
+
if (table.includes("notification") || table.includes("message") || table.includes("email")) return "Mail";
|
|
626
|
+
if (table.includes("log") || table.includes("audit") || table.includes("event")) return "Activity";
|
|
627
|
+
if (table.includes("subscription") || table.includes("plan") || table.includes("billing")) return "CreditCard";
|
|
628
|
+
if (table.includes("comment") || table.includes("review") || table.includes("feedback")) return "MessageCircle";
|
|
629
|
+
return "Database";
|
|
630
|
+
}
|
|
631
|
+
function buildEnumMap(enumValues) {
|
|
632
|
+
const enumMap = /* @__PURE__ */ new Map();
|
|
633
|
+
for (const ev of enumValues) {
|
|
634
|
+
const existing = enumMap.get(ev.enum_name);
|
|
635
|
+
if (existing) existing.push(ev.enum_value);
|
|
636
|
+
else enumMap.set(ev.enum_name, [ev.enum_value]);
|
|
637
|
+
}
|
|
638
|
+
return enumMap;
|
|
639
|
+
}
|
|
640
|
+
function buildTablesMap(tables, columns, pks, fks) {
|
|
641
|
+
const tablesMap = /* @__PURE__ */ new Map();
|
|
642
|
+
for (const t of tables) tablesMap.set(t.table_name, {
|
|
643
|
+
name: t.table_name,
|
|
644
|
+
columns: columns.filter((c) => c.table_name === t.table_name),
|
|
645
|
+
pks: pks.filter((pk) => pk.table_name === t.table_name).map((pk) => pk.column_name),
|
|
646
|
+
fks: fks.filter((fk) => fk.table_name === t.table_name)
|
|
647
|
+
});
|
|
648
|
+
return tablesMap;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Join tables, identified by column name.
|
|
652
|
+
*
|
|
653
|
+
* Superseded for the CLI by `classifyTables` in `./introspect-db-structure`,
|
|
654
|
+
* which asks the database instead: two single-column keys, unique together, no
|
|
655
|
+
* payload column, nothing referencing the table. This rule folds away
|
|
656
|
+
* `northwind.order_details` — which has the key shape and carries unit price,
|
|
657
|
+
* quantity and discount — because it recognises `id`, `created_at` and
|
|
658
|
+
* `updated_at` by name and calls everything else a foreign key.
|
|
659
|
+
*
|
|
660
|
+
* Still the runtime's rule (`describeTables(…, { purpose: "serve" })`): what a
|
|
661
|
+
* backend with no `backend/schema` has always folded away, kept so the set of
|
|
662
|
+
* tables it serves does not move. Row counts, which `classifyTables` needs,
|
|
663
|
+
* are not read at boot.
|
|
664
|
+
*/
|
|
665
|
+
function identifyJoinTables(tablesMap) {
|
|
666
|
+
const joinTables = /* @__PURE__ */ new Set();
|
|
667
|
+
for (const [tableName, meta] of tablesMap.entries()) if (meta.fks.length === 2) {
|
|
668
|
+
if (meta.columns.every((c) => meta.fks.some((fk) => fk.column_name === c.column_name) || c.column_name === "id" || c.column_name === "created_at" || c.column_name === "updated_at")) joinTables.add(tableName);
|
|
669
|
+
}
|
|
670
|
+
return joinTables;
|
|
671
|
+
}
|
|
672
|
+
var IDENTITY_EXACT = {
|
|
673
|
+
id: 0,
|
|
674
|
+
uuid: 1,
|
|
675
|
+
_id: 2
|
|
676
|
+
};
|
|
677
|
+
var TITLE_EXACT = {
|
|
678
|
+
name: 10,
|
|
679
|
+
title: 11,
|
|
680
|
+
label: 12,
|
|
681
|
+
display_name: 13,
|
|
682
|
+
displayname: 13,
|
|
683
|
+
headline: 14,
|
|
684
|
+
subject: 15,
|
|
685
|
+
heading: 16
|
|
686
|
+
};
|
|
687
|
+
var HUMAN_IDENTITY_EXACT = {
|
|
688
|
+
first_name: 20,
|
|
689
|
+
firstname: 20,
|
|
690
|
+
last_name: 21,
|
|
691
|
+
lastname: 21,
|
|
692
|
+
full_name: 22,
|
|
693
|
+
fullname: 22,
|
|
694
|
+
given_name: 22,
|
|
695
|
+
family_name: 23,
|
|
696
|
+
middle_name: 24,
|
|
697
|
+
username: 25,
|
|
698
|
+
user_name: 25,
|
|
699
|
+
email: 26,
|
|
700
|
+
email_address: 26,
|
|
701
|
+
phone: 27,
|
|
702
|
+
phone_number: 27,
|
|
703
|
+
mobile: 27
|
|
704
|
+
};
|
|
705
|
+
var DESCRIPTOR_EXACT = {
|
|
706
|
+
slug: 30,
|
|
707
|
+
code: 31,
|
|
708
|
+
sku: 32,
|
|
709
|
+
reference: 33,
|
|
710
|
+
ref: 33,
|
|
711
|
+
type: 34,
|
|
712
|
+
kind: 34,
|
|
713
|
+
status: 35,
|
|
714
|
+
state: 35,
|
|
715
|
+
role: 36,
|
|
716
|
+
category: 37,
|
|
717
|
+
group: 38,
|
|
718
|
+
priority: 39,
|
|
719
|
+
order: 39,
|
|
720
|
+
sort_order: 39,
|
|
721
|
+
position: 39
|
|
722
|
+
};
|
|
723
|
+
var SYSTEM_TIMESTAMP_EXACT = {
|
|
724
|
+
created_at: 120,
|
|
725
|
+
createdat: 120,
|
|
726
|
+
creation_date: 120,
|
|
727
|
+
inserted_at: 121,
|
|
728
|
+
updated_at: 122,
|
|
729
|
+
updatedat: 122,
|
|
730
|
+
modified_at: 122,
|
|
731
|
+
last_modified: 122,
|
|
732
|
+
deleted_at: 123,
|
|
733
|
+
deletedat: 123,
|
|
734
|
+
archived_at: 124
|
|
735
|
+
};
|
|
736
|
+
var TITLE_PATTERNS = [
|
|
737
|
+
"name",
|
|
738
|
+
"title",
|
|
739
|
+
"label"
|
|
740
|
+
];
|
|
741
|
+
var LONG_TEXT_NAMES = /* @__PURE__ */ new Set([
|
|
742
|
+
"description",
|
|
743
|
+
"summary",
|
|
744
|
+
"excerpt",
|
|
745
|
+
"abstract",
|
|
746
|
+
"overview",
|
|
747
|
+
"bio",
|
|
748
|
+
"biography",
|
|
749
|
+
"about"
|
|
750
|
+
]);
|
|
751
|
+
var RICH_CONTENT_NAMES = /* @__PURE__ */ new Set([
|
|
752
|
+
"content",
|
|
753
|
+
"body",
|
|
754
|
+
"html",
|
|
755
|
+
"markup",
|
|
756
|
+
"text",
|
|
757
|
+
"article_body",
|
|
758
|
+
"post_body"
|
|
759
|
+
]);
|
|
760
|
+
var MEDIA_PATTERNS = [
|
|
761
|
+
"image",
|
|
762
|
+
"avatar",
|
|
763
|
+
"photo",
|
|
764
|
+
"logo",
|
|
765
|
+
"cover",
|
|
766
|
+
"thumbnail",
|
|
767
|
+
"banner",
|
|
768
|
+
"icon",
|
|
769
|
+
"picture",
|
|
770
|
+
"poster"
|
|
771
|
+
];
|
|
772
|
+
var JSON_MAP_NAMES = /* @__PURE__ */ new Set([
|
|
773
|
+
"metadata",
|
|
774
|
+
"meta",
|
|
775
|
+
"config",
|
|
776
|
+
"configuration",
|
|
777
|
+
"settings",
|
|
778
|
+
"options",
|
|
779
|
+
"preferences",
|
|
780
|
+
"data",
|
|
781
|
+
"payload",
|
|
782
|
+
"attributes",
|
|
783
|
+
"extra",
|
|
784
|
+
"additional_info"
|
|
785
|
+
]);
|
|
786
|
+
/**
|
|
787
|
+
* Compute a numeric priority score for a property.
|
|
788
|
+
* Lower scores appear first in the generated `propertiesOrder` array.
|
|
789
|
+
*
|
|
790
|
+
* The system uses 14 tiers (0–139), with the original column index
|
|
791
|
+
* added as a fractional tiebreaker (originalIndex / 10000) to
|
|
792
|
+
* guarantee stable ordering within the same tier.
|
|
793
|
+
*
|
|
794
|
+
* Pure function — no side effects.
|
|
795
|
+
*/
|
|
796
|
+
function computePropertyPriority(columnName, ctx) {
|
|
797
|
+
const col = columnName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
798
|
+
const tiebreaker = ctx.originalIndex / 1e4;
|
|
799
|
+
if (ctx.isPk) return (IDENTITY_EXACT[col] ?? 5) + tiebreaker;
|
|
800
|
+
const systemTs = SYSTEM_TIMESTAMP_EXACT[col];
|
|
801
|
+
if (systemTs !== void 0) return systemTs + tiebreaker;
|
|
802
|
+
const titleExact = TITLE_EXACT[col];
|
|
803
|
+
if (titleExact !== void 0) return titleExact + tiebreaker;
|
|
804
|
+
const humanExact = HUMAN_IDENTITY_EXACT[col];
|
|
805
|
+
if (humanExact !== void 0) return humanExact + tiebreaker;
|
|
806
|
+
const descriptorExact = DESCRIPTOR_EXACT[col];
|
|
807
|
+
if (descriptorExact !== void 0) return descriptorExact + tiebreaker;
|
|
808
|
+
for (const pattern of TITLE_PATTERNS) if (col.includes(pattern) && col !== pattern) return 17 + tiebreaker;
|
|
809
|
+
if (ctx.isStorage) return 90 + tiebreaker;
|
|
810
|
+
for (const pattern of MEDIA_PATTERNS) if (col.includes(pattern)) return 91 + tiebreaker;
|
|
811
|
+
if (col.endsWith("_url") || col.endsWith("_uri") || col.endsWith("_link")) return 92 + tiebreaker;
|
|
812
|
+
if (LONG_TEXT_NAMES.has(col)) return 70 + tiebreaker;
|
|
813
|
+
if (RICH_CONTENT_NAMES.has(col)) return 80 + tiebreaker;
|
|
814
|
+
if (ctx.propType === "map") return JSON_MAP_NAMES.has(col) ? 100 + tiebreaker : 105 + tiebreaker;
|
|
815
|
+
if (ctx.propType === "array") return 110 + tiebreaker;
|
|
816
|
+
if (ctx.propType === "relation") return 60 + tiebreaker;
|
|
817
|
+
if (ctx.isEnum) return 40 + tiebreaker;
|
|
818
|
+
if (ctx.propType === "boolean") return 45 + tiebreaker;
|
|
819
|
+
if (ctx.propType === "string" && ctx.pgDataType !== "text") return 42 + tiebreaker;
|
|
820
|
+
if (ctx.propType === "number") return 50 + tiebreaker;
|
|
821
|
+
if (ctx.propType === "date") return 55 + tiebreaker;
|
|
822
|
+
if (ctx.propType === "string" && ctx.pgDataType === "text") return 75 + tiebreaker;
|
|
823
|
+
return 130 + tiebreaker;
|
|
824
|
+
}
|
|
825
|
+
function sortPropertiesOrder(entries) {
|
|
826
|
+
return [...entries].sort((a, b) => computePropertyPriority(a.key, a.ctx) - computePropertyPriority(b.key, b.ctx)).map((e) => e.key);
|
|
827
|
+
}
|
|
828
|
+
/** The column types a declared key may not have (`defineTable` refuses them). */
|
|
829
|
+
var UNKEYABLE_KINDS = /* @__PURE__ */ new Set([
|
|
830
|
+
"timestamptz",
|
|
831
|
+
"time",
|
|
832
|
+
"json",
|
|
833
|
+
"jsonb",
|
|
834
|
+
"vector",
|
|
835
|
+
"bytea",
|
|
836
|
+
"array",
|
|
837
|
+
"other"
|
|
838
|
+
]);
|
|
839
|
+
/** The `PropertyOrderingContext` property type of a column type. */
|
|
840
|
+
function orderingType(type) {
|
|
841
|
+
switch (type.kind) {
|
|
842
|
+
case "smallint":
|
|
843
|
+
case "integer":
|
|
844
|
+
case "bigint":
|
|
845
|
+
case "smallserial":
|
|
846
|
+
case "serial":
|
|
847
|
+
case "bigserial":
|
|
848
|
+
case "real":
|
|
849
|
+
case "doublePrecision":
|
|
850
|
+
case "numeric": return "number";
|
|
851
|
+
case "timestamptz":
|
|
852
|
+
case "date":
|
|
853
|
+
case "time": return "date";
|
|
854
|
+
case "json":
|
|
855
|
+
case "jsonb": return "map";
|
|
856
|
+
case "array": return "array";
|
|
857
|
+
case "boolean": return "boolean";
|
|
858
|
+
case "vector": return "vector";
|
|
859
|
+
case "bytea": return "binary";
|
|
860
|
+
default: return "string";
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
/**
|
|
864
|
+
* The panel options a table's structure and names suggest — what the
|
|
865
|
+
* generator used to write into the collection's `admin` block — or
|
|
866
|
+
* `undefined` when none fired (an icon of its own, a role, a title, a board, a
|
|
867
|
+
* sort, a capped list, an option on a field).
|
|
868
|
+
*/
|
|
869
|
+
function customizationOf(descriptor, meta, input, enumMap, fieldHints) {
|
|
870
|
+
const table = descriptor.table;
|
|
871
|
+
const classification = input.classifications?.get(table);
|
|
872
|
+
const options = {};
|
|
873
|
+
const comments = [];
|
|
874
|
+
const keyOf = new Map(descriptor.columns.map((column) => [column.column, column.key]));
|
|
875
|
+
const relationOf = new Map(descriptor.relations.filter((relation) => relation.kind === "belongsTo").map((relation) => [relation.kind === "belongsTo" ? relation.localKey : "", relation.name]));
|
|
876
|
+
const icon = getIconForTable(table);
|
|
877
|
+
if (icon !== "Database") options.icon = icon;
|
|
878
|
+
if (classification?.role === "owned-child") options.hideFromNavigation = true;
|
|
879
|
+
if (classification?.role === "lookup") options.group = "Reference";
|
|
880
|
+
const fields = {};
|
|
881
|
+
const hidden = /* @__PURE__ */ new Set();
|
|
882
|
+
for (const column of descriptor.columns) {
|
|
883
|
+
const col = meta.columns.find((candidate) => candidate.column_name === column.column);
|
|
884
|
+
if (!col || column.foreignKeyOf !== void 0) continue;
|
|
885
|
+
const name = column.column.toLowerCase();
|
|
886
|
+
const field = {};
|
|
887
|
+
if (column.stamp?.value === "now") {
|
|
888
|
+
field.readOnly = true;
|
|
889
|
+
if (name === "created_at" || name === "createdat" || name === "updated_at" || name === "updatedat") {
|
|
890
|
+
field.hidden = true;
|
|
891
|
+
hidden.add(column.key);
|
|
892
|
+
}
|
|
893
|
+
} else if (isDerivedIndexColumn(col)) {
|
|
894
|
+
field.hidden = true;
|
|
895
|
+
hidden.add(column.key);
|
|
896
|
+
} else if ((column.type.kind === "text" || column.type.kind === "varchar") && column.validate?.url !== true && !column.primaryKey) {
|
|
897
|
+
if (name === "content" || name === "body") {
|
|
898
|
+
field.multiline = true;
|
|
899
|
+
field.markdown = true;
|
|
900
|
+
} else if (column.type.kind === "text" || name === "description" || name === "summary" || name === "excerpt") field.multiline = true;
|
|
901
|
+
}
|
|
902
|
+
Object.assign(field, fieldHints.get(column.key) ?? {});
|
|
903
|
+
if (Object.keys(field).length > 0) fields[column.key] = field;
|
|
904
|
+
}
|
|
905
|
+
const entries = [];
|
|
906
|
+
descriptor.columns.forEach((column, index) => {
|
|
907
|
+
const col = meta.columns.find((candidate) => candidate.column_name === column.column);
|
|
908
|
+
const relation = relationOf.get(column.column);
|
|
909
|
+
const isPk = column.primaryKey === true;
|
|
910
|
+
entries.push({
|
|
911
|
+
key: relation !== void 0 && !isPk ? relation : column.key,
|
|
912
|
+
ctx: {
|
|
913
|
+
propType: relation !== void 0 && !isPk ? "relation" : orderingType(column.type),
|
|
914
|
+
isPk,
|
|
915
|
+
isEnum: column.type.kind === "enum",
|
|
916
|
+
isStorage: false,
|
|
917
|
+
pgDataType: col?.data_type ?? "",
|
|
918
|
+
originalIndex: index
|
|
919
|
+
}
|
|
920
|
+
});
|
|
921
|
+
});
|
|
922
|
+
const defaultOrder = entries.map((entry) => entry.key);
|
|
923
|
+
const order = sortPropertiesOrder(entries);
|
|
924
|
+
if (classification && input.metadata) {
|
|
925
|
+
const facts = buildColumnFacts(meta, input.metadata, enumMap, input.checkFacts ?? /* @__PURE__ */ new Map());
|
|
926
|
+
const asKey = (column) => keyOf.get(column) ?? toWireKey(column);
|
|
927
|
+
const title = deriveTitleProperty(facts);
|
|
928
|
+
if (title) options.display = { title: asKey(title) };
|
|
929
|
+
const kanban = deriveKanbanProperty(facts);
|
|
930
|
+
const orderField = kanban ? deriveKanbanOrderProperty(facts) : void 0;
|
|
931
|
+
if (kanban && orderField) options.kanban = {
|
|
932
|
+
columnField: asKey(kanban),
|
|
933
|
+
orderField: asKey(orderField)
|
|
934
|
+
};
|
|
935
|
+
else if (kanban) comments.push(`A board over "${asKey(kanban)}" fits this table, but a board needs a text column to keep each card's order in. Add one, then declare kanban: { columnField: "${asKey(kanban)}", orderField: "<that column>" }.`);
|
|
936
|
+
const sort = deriveSort(facts);
|
|
937
|
+
if (sort) options.sort = [asKey(sort[0]), "desc"];
|
|
938
|
+
const listFields = deriveListProperties(order, hidden);
|
|
939
|
+
if (listFields) options.listFields = listFields;
|
|
940
|
+
}
|
|
941
|
+
if (Object.keys(fields).length > 0) options.fields = fields;
|
|
942
|
+
if (Object.keys(options).length === 0 && comments.length === 0) return void 0;
|
|
943
|
+
if (order.join("\n") !== defaultOrder.join("\n")) options.fieldOrder = order;
|
|
944
|
+
return {
|
|
945
|
+
options,
|
|
946
|
+
comments
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
/** The comment a table whose row-level security is off opens with. */
|
|
950
|
+
function rlsOffComment(table) {
|
|
951
|
+
if (table?.rls_enabled !== false) return [];
|
|
952
|
+
return ["⚠ Row-level security is off on this table, so every request reaches every row. `rebase db push`", "switches it on: from then on the server and admins reach its rows, and anyone else what `rls` grants."];
|
|
953
|
+
}
|
|
954
|
+
/** Comment lines, safe after `//`. */
|
|
955
|
+
var commentLines = (lines) => lines.map((line) => `// ${line.replace(/\s*[\r\n]+\s*/g, " ")}`.trimEnd()).join("\n");
|
|
956
|
+
/**
|
|
957
|
+
* The source `rebase schema introspect` writes for a database: one
|
|
958
|
+
* `backend/schema/<table>.ts` per table through the one table printer
|
|
959
|
+
* (`printTableModule`), and a `frontend/src/cms/<table>.tsx` beside a table
|
|
960
|
+
* whose structure suggested how the panel should show it.
|
|
961
|
+
*
|
|
962
|
+
* The tables are described with `describeTables(…, { purpose: "generate" })`:
|
|
963
|
+
* columns as their Postgres types, foreign keys as `belongsTo` with the column
|
|
964
|
+
* declared, the reverse `hasMany`, a junction as `manyToMany`, the policies as
|
|
965
|
+
* `rls` (or `"admin-only"` when the table holds only the admin baseline). Pure.
|
|
966
|
+
*/
|
|
967
|
+
function generateSchemaModules(input) {
|
|
968
|
+
const { metadata } = input;
|
|
969
|
+
const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);
|
|
970
|
+
const enumMap = buildEnumMap(metadata.enumValues);
|
|
971
|
+
const joinTables = input.classifications ? new Set([...input.classifications.values()].filter((c) => c.role === "junction").map((c) => c.table)) : identifyJoinTables(tablesMap);
|
|
972
|
+
const keyless = [...tablesMap.values()].filter((meta) => meta.pks.length === 0 && !joinTables.has(meta.name) && !(input.leaveOut?.has(meta.name) ?? false));
|
|
973
|
+
const describe = (leaveOut) => describeTables(metadata, {
|
|
974
|
+
purpose: "generate",
|
|
975
|
+
joinTables,
|
|
976
|
+
leaveOut: /* @__PURE__ */ new Set([
|
|
977
|
+
...input.leaveOut ?? [],
|
|
978
|
+
...keyless.map((meta) => meta.name),
|
|
979
|
+
...leaveOut
|
|
980
|
+
]),
|
|
981
|
+
checkFacts: input.checkFacts
|
|
982
|
+
});
|
|
983
|
+
const unkeyable = /* @__PURE__ */ new Map();
|
|
984
|
+
for (const table of describe(/* @__PURE__ */ new Set()).tables) {
|
|
985
|
+
const bad = table.columns.filter((column) => column.primaryKey && UNKEYABLE_KINDS.has(column.type.kind));
|
|
986
|
+
if (bad.length > 0) unkeyable.set(table.table, `its key includes ${bad.map((column) => `"${column.column}" (${columnTypeLabel(column.type)})`).join(", ")}, and a key column is a value a row is addressed by — text, a number, a uuid, a date, a boolean or an enum. Key the table on such a column and introspect again.`);
|
|
987
|
+
}
|
|
988
|
+
const described = describe(new Set(unkeyable.keys()));
|
|
989
|
+
const bySlug = new Map(described.tables.map((table) => [table.slug, table]));
|
|
990
|
+
const resolveTarget = (target) => {
|
|
991
|
+
const found = bySlug.get(target.slug);
|
|
992
|
+
return {
|
|
993
|
+
identifier: tableIdentifier(target.slug),
|
|
994
|
+
importPath: `./${target.slug}`,
|
|
995
|
+
...found ? {
|
|
996
|
+
table: found.table,
|
|
997
|
+
kind: found.kind
|
|
998
|
+
} : {}
|
|
999
|
+
};
|
|
1000
|
+
};
|
|
1001
|
+
const out = {
|
|
1002
|
+
tables: [],
|
|
1003
|
+
failed: [...keyless.map((meta) => ({
|
|
1004
|
+
table: meta.name,
|
|
1005
|
+
reason: "it has no primary key, and a table is declared with the column (or columns) that identify a row. Add one (`ALTER TABLE … ADD PRIMARY KEY (…)`) and introspect again."
|
|
1006
|
+
})), ...[...unkeyable].map(([table, reason]) => ({
|
|
1007
|
+
table,
|
|
1008
|
+
reason
|
|
1009
|
+
}))],
|
|
1010
|
+
rlsOff: []
|
|
1011
|
+
};
|
|
1012
|
+
for (const descriptor of described.tables) {
|
|
1013
|
+
const meta = tablesMap.get(descriptor.table);
|
|
1014
|
+
if (!meta) continue;
|
|
1015
|
+
const notes = [...described.notes.drift.get(descriptor.table) ?? []];
|
|
1016
|
+
const remarks = [...described.notes.remark.get(descriptor.table) ?? []];
|
|
1017
|
+
const rows = input.samples?.get(descriptor.table);
|
|
1018
|
+
const fieldHints = /* @__PURE__ */ new Map();
|
|
1019
|
+
const columns = descriptor.columns.map((column) => {
|
|
1020
|
+
const hints = rows ? inferColumnHints(column.column, column.type, rows.map((row) => row[column.column])) : {};
|
|
1021
|
+
if (hints.field) fieldHints.set(column.key, { ...hints.field });
|
|
1022
|
+
let validate = hints.validate;
|
|
1023
|
+
const name = column.column.toLowerCase();
|
|
1024
|
+
const text = column.type.kind === "text" || column.type.kind === "varchar" || column.type.kind === "char";
|
|
1025
|
+
if (!validate && !rows && text && column.foreignKeyOf === void 0 && /_(url|uri|link)$/.test(name)) validate = { url: true };
|
|
1026
|
+
return validate ? {
|
|
1027
|
+
...column,
|
|
1028
|
+
validate: {
|
|
1029
|
+
...column.validate,
|
|
1030
|
+
...validate
|
|
1031
|
+
}
|
|
1032
|
+
} : column;
|
|
1033
|
+
});
|
|
1034
|
+
const table = {
|
|
1035
|
+
...descriptor,
|
|
1036
|
+
columns
|
|
1037
|
+
};
|
|
1038
|
+
let schemaModule;
|
|
1039
|
+
try {
|
|
1040
|
+
schemaModule = printTableModule(table, {
|
|
1041
|
+
resolveTarget,
|
|
1042
|
+
...input.specifier ? { specifier: input.specifier } : {}
|
|
1043
|
+
});
|
|
1044
|
+
} catch (error) {
|
|
1045
|
+
out.failed.push({
|
|
1046
|
+
table: descriptor.table,
|
|
1047
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1048
|
+
});
|
|
1049
|
+
continue;
|
|
1050
|
+
}
|
|
1051
|
+
const row = metadata.tables.find((candidate) => candidate.table_name === descriptor.table);
|
|
1052
|
+
if (row?.rls_enabled === false) out.rlsOff.push(descriptor.table);
|
|
1053
|
+
const classification = input.classifications?.get(descriptor.table);
|
|
1054
|
+
const header = [
|
|
1055
|
+
...classification && classification.role !== "entity" ? [`Introspected as ${/^[aeiou]/.test(classification.role) ? "an" : "a"} ${classification.role}: ${classification.reason}.`] : [],
|
|
1056
|
+
...notes.length > 0 ? ["⚠ Not reproduced exactly by `rebase db push` — read before pushing:", ...notes.map((note) => ` - ${note}`)] : [],
|
|
1057
|
+
...remarks.length > 0 ? ["Introspection notes:", ...remarks.map((remark) => ` - ${remark}`)] : [],
|
|
1058
|
+
...rlsOffComment(row)
|
|
1059
|
+
];
|
|
1060
|
+
if (header.length > 0) {
|
|
1061
|
+
const split = schemaModule.indexOf("\n\nexport const ");
|
|
1062
|
+
schemaModule = `${schemaModule.slice(0, split)}\n\n${commentLines(header)}${schemaModule.slice(split + 1)}`;
|
|
1063
|
+
}
|
|
1064
|
+
const identifier = tableIdentifier(descriptor.slug);
|
|
1065
|
+
let customization;
|
|
1066
|
+
if (input.cms) {
|
|
1067
|
+
const options = customizationOf(table, meta, input, enumMap, fieldHints);
|
|
1068
|
+
if (options) customization = printCustomizationModule({
|
|
1069
|
+
slug: descriptor.slug,
|
|
1070
|
+
tableIdentifier: identifier,
|
|
1071
|
+
tableImport: input.cms.tableImport(descriptor.table),
|
|
1072
|
+
options: options.options,
|
|
1073
|
+
comments: options.comments
|
|
1074
|
+
});
|
|
1075
|
+
}
|
|
1076
|
+
out.tables.push({
|
|
1077
|
+
table: descriptor.table,
|
|
1078
|
+
identifier,
|
|
1079
|
+
schemaModule,
|
|
1080
|
+
notes,
|
|
1081
|
+
remarks,
|
|
1082
|
+
...customization ? { customization } : {}
|
|
1083
|
+
});
|
|
1084
|
+
}
|
|
1085
|
+
return out;
|
|
1086
|
+
}
|
|
1087
|
+
/**
|
|
1088
|
+
* `backend/schema/index.ts` with an export line added for each table it does
|
|
1089
|
+
* not export yet — what a run without `--force` does to an index that exists.
|
|
1090
|
+
*/
|
|
1091
|
+
function mergeIndexModule(existing, tables) {
|
|
1092
|
+
const exported = new Set([...existing.matchAll(/from\s+["']\.\/([^"']+)["']/g)].map((match) => match[1]));
|
|
1093
|
+
const missing = tables.filter((table) => !exported.has(table.importPath.replace(/^\.\//, "")));
|
|
1094
|
+
if (missing.length === 0) return existing;
|
|
1095
|
+
const lines = printIndexModule(missing).trimEnd().split("\n");
|
|
1096
|
+
const lastExport = [...existing.matchAll(/^export \{[^}]*\} from [^\n]*$/gm)].pop();
|
|
1097
|
+
if (!lastExport || lastExport.index === void 0) return `${lines.join("\n")}\n${existing.startsWith("\n") ? "" : "\n"}${existing}`;
|
|
1098
|
+
const at = lastExport.index + lastExport[0].length;
|
|
1099
|
+
return `${existing.slice(0, at)}\n${lines.join("\n")}${existing.slice(at)}`;
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* What `rebase db push` does to tables whose row-level security is off, for
|
|
1103
|
+
* the introspection to say once — or `undefined` when there are none.
|
|
1104
|
+
*/
|
|
1105
|
+
function describeRlsOffTables(tableNames) {
|
|
1106
|
+
if (tableNames.length === 0) return void 0;
|
|
1107
|
+
return `${tableNames.length} table(s) have row-level security off, so every request reaches every row: ${[...tableNames].sort().join(", ")}.\n\`rebase db push\` switches it on: from then on the server and admins reach their rows, and anyone else what each table's \`rls\` grants.`;
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Safely extract the host portion of a database URL for logging.
|
|
1111
|
+
*/
|
|
1112
|
+
function safeHostFromUrl(url) {
|
|
1113
|
+
return url.includes("@") ? url.split("@")[1] : "(local connection)";
|
|
1114
|
+
}
|
|
1115
|
+
//#endregion
|
|
1116
|
+
//#region src/schema/introspect-db-storage.ts
|
|
1117
|
+
/**
|
|
1118
|
+
* The sequence a `SERIAL` column owns, named the way Postgres names it — how
|
|
1119
|
+
* introspection tells a key whose default is its own serial sequence (declared
|
|
1120
|
+
* `col.serial()`) from one fed by a sequence Rebase did not create (a
|
|
1121
|
+
* `{ kind: "database" }` default).
|
|
1122
|
+
*/
|
|
1123
|
+
/**
|
|
1124
|
+
* The name Postgres gives a `SERIAL` column's sequence — `ChooseRelationName`
|
|
1125
|
+
* with the `seq` label: `<table>_<column>_seq`, and when that is over 63 bytes
|
|
1126
|
+
* the longer of the two names is shortened, one character at a time, until it
|
|
1127
|
+
* fits.
|
|
1128
|
+
*/
|
|
1129
|
+
function serialSequenceName(table, column) {
|
|
1130
|
+
const available = 58;
|
|
1131
|
+
let tableChars = table.length;
|
|
1132
|
+
let columnChars = column.length;
|
|
1133
|
+
while (tableChars + columnChars > available) if (tableChars > columnChars) tableChars--;
|
|
1134
|
+
else columnChars--;
|
|
1135
|
+
return `${table.slice(0, tableChars)}_${column.slice(0, columnChars)}_seq`;
|
|
1136
|
+
}
|
|
1137
|
+
//#endregion
|
|
1138
|
+
//#region src/schema/introspect-db-search.ts
|
|
1139
|
+
/**
|
|
1140
|
+
* A table's `search` block, read back out of the column it built.
|
|
1141
|
+
*
|
|
1142
|
+
* A Rebase search column is `tsvector GENERATED ALWAYS AS (…) STORED`, stamped
|
|
1143
|
+
* with a fingerprint of the expression in its `COMMENT`. Introspection used to
|
|
1144
|
+
* emit it as an ordinary read-only text column, which the planner makes a
|
|
1145
|
+
* `text` column — so the first push after adopting a Rebase database planned
|
|
1146
|
+
* `ALTER COLUMN "search_vector" TYPE text … DROP EXPRESSION`, and search was
|
|
1147
|
+
* gone for whoever approved it.
|
|
1148
|
+
*
|
|
1149
|
+
* Reading the block back is a guess checked by the stamp: the deparsed
|
|
1150
|
+
* expression names each field's column, weight and language, which is enough
|
|
1151
|
+
* to write a candidate block; the candidate is then compiled by the very code
|
|
1152
|
+
* that built the column, and kept only if its fingerprint is the one the column
|
|
1153
|
+
* carries. A block that does not reproduce the stamp is not emitted at all —
|
|
1154
|
+
* the note says so — because a wrong one would rebuild the column differently.
|
|
1155
|
+
*
|
|
1156
|
+
* `mode` and `fuzzyThreshold` act at query time and are stored nowhere, so they
|
|
1157
|
+
* come back as their defaults.
|
|
1158
|
+
*/
|
|
1159
|
+
/** One `setweight(to_tsvector('<lang>'::regconfig, <text>), '<W>'::"char")`, deparsed. */
|
|
1160
|
+
var SEGMENT = /setweight\(to_tsvector\('((?:[^']|'')+)'::regconfig, ([\s\S]+?)\), '([A-D])'::"char"\)/g;
|
|
1161
|
+
/**
|
|
1162
|
+
* The column's type as the search builder classifies it, for the candidate
|
|
1163
|
+
* block to resolve against: every string type reads as text, as the builder
|
|
1164
|
+
* indexes them alike.
|
|
1165
|
+
*/
|
|
1166
|
+
function searchableTypeOf(col) {
|
|
1167
|
+
if (col.data_type === "text" || col.data_type === "character varying" || col.data_type === "character") return { kind: "text" };
|
|
1168
|
+
if (col.udt_name === "_text") return {
|
|
1169
|
+
kind: "array",
|
|
1170
|
+
of: { kind: "text" }
|
|
1171
|
+
};
|
|
1172
|
+
if (col.data_type === "jsonb") return { kind: "jsonb" };
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* The search block a table's stamped generated columns were built from, or a
|
|
1176
|
+
* note saying why it could not be read back.
|
|
1177
|
+
*/
|
|
1178
|
+
function reconstructSearchBlock(input) {
|
|
1179
|
+
const stamped = input.columns.filter((col) => col.is_generated === "ALWAYS" && (input.comments.get(col.column_name) ?? "").startsWith("rebase:search:v1:"));
|
|
1180
|
+
const main = stamped.find((col) => col.udt_name === "tsvector");
|
|
1181
|
+
if (!main) return { columns: /* @__PURE__ */ new Set() };
|
|
1182
|
+
const fuzzy = stamped.find((col) => col.column_name === `${main.column_name}_text`);
|
|
1183
|
+
const columns = new Set(stamped.map((col) => col.column_name));
|
|
1184
|
+
const unreadable = (why) => ({
|
|
1185
|
+
columns,
|
|
1186
|
+
note: `"${main.column_name}" is a Rebase search column whose \`search\` block could not be read back (${why}). Declare the block again before pushing — without it a push plans dropping the column.`
|
|
1187
|
+
});
|
|
1188
|
+
const expression = main.generation_expression ?? "";
|
|
1189
|
+
const byColumn = new Map(input.columns.map((col) => [col.column_name, col]));
|
|
1190
|
+
const fields = [];
|
|
1191
|
+
let language;
|
|
1192
|
+
let unaccent = false;
|
|
1193
|
+
for (const [, lang, inner, weight] of expression.matchAll(SEGMENT)) {
|
|
1194
|
+
language ??= lang.replace(/''/g, "'");
|
|
1195
|
+
if (lang.replace(/''/g, "'") !== language) return unreadable("its fields use different languages");
|
|
1196
|
+
if (inner.includes("rebase_search_unaccent")) unaccent = true;
|
|
1197
|
+
const column = [...inner.matchAll(/"?([A-Za-z_][A-Za-z0-9_$]*)"?/g)].map((m) => m[1]).find((name) => byColumn.has(name) && !columns.has(name));
|
|
1198
|
+
if (!column) return unreadable("a field reads no column of this table");
|
|
1199
|
+
const key = input.keyByColumn.get(column);
|
|
1200
|
+
if (!key) return unreadable(`the column "${column}" is not a declared column`);
|
|
1201
|
+
const jsonPath = [...inner.matchAll(/(?:->|#>)\s*'([^']+)'/g)].flatMap((m) => m[1].replace(/^\{|\}$/g, "").split(","));
|
|
1202
|
+
fields.push({
|
|
1203
|
+
path: [key, ...jsonPath].join("."),
|
|
1204
|
+
weight
|
|
1205
|
+
});
|
|
1206
|
+
}
|
|
1207
|
+
if (fields.length === 0 || !language) return unreadable("its expression is not one Rebase writes");
|
|
1208
|
+
const search = {
|
|
1209
|
+
...main.column_name !== DEFAULT_SEARCH_COLUMN ? { column: main.column_name } : {},
|
|
1210
|
+
...language !== DEFAULT_SEARCH_LANGUAGE ? { language } : {},
|
|
1211
|
+
...unaccent ? { unaccent: true } : {},
|
|
1212
|
+
...fuzzy ? { fuzzy: true } : {},
|
|
1213
|
+
fields: fields.map((f) => ({
|
|
1214
|
+
path: f.path,
|
|
1215
|
+
weight: f.weight
|
|
1216
|
+
}))
|
|
1217
|
+
};
|
|
1218
|
+
const candidateColumns = [];
|
|
1219
|
+
for (const [column, key] of input.keyByColumn) {
|
|
1220
|
+
const col = byColumn.get(column);
|
|
1221
|
+
const type = col ? searchableTypeOf(col) : void 0;
|
|
1222
|
+
if (type) candidateColumns.push({
|
|
1223
|
+
key,
|
|
1224
|
+
column,
|
|
1225
|
+
type,
|
|
1226
|
+
nullable: true
|
|
1227
|
+
});
|
|
1228
|
+
}
|
|
1229
|
+
const candidate = {
|
|
1230
|
+
name: input.table,
|
|
1231
|
+
slug: input.table,
|
|
1232
|
+
table: input.table,
|
|
1233
|
+
schema: input.schema,
|
|
1234
|
+
kind: "table",
|
|
1235
|
+
columns: candidateColumns,
|
|
1236
|
+
primaryKey: [],
|
|
1237
|
+
relations: [],
|
|
1238
|
+
rls: {
|
|
1239
|
+
posture: "rules",
|
|
1240
|
+
rules: [],
|
|
1241
|
+
defaultPolicies: false
|
|
1242
|
+
},
|
|
1243
|
+
search
|
|
1244
|
+
};
|
|
1245
|
+
let fingerprints;
|
|
1246
|
+
try {
|
|
1247
|
+
const spec = buildTableSearchColumnSpec(candidate);
|
|
1248
|
+
if (!spec) return unreadable("no block compiles from it");
|
|
1249
|
+
fingerprints = new Map(searchColumnStamps(spec).map((stamp) => [stamp.column, stamp.fingerprint]));
|
|
1250
|
+
} catch (err) {
|
|
1251
|
+
return unreadable(err instanceof Error ? err.message : String(err));
|
|
1252
|
+
}
|
|
1253
|
+
for (const col of stamped) if (fingerprints.get(col.column_name) !== input.comments.get(col.column_name)) return unreadable("the block read from its expression does not reproduce the column's stamp");
|
|
1254
|
+
return {
|
|
1255
|
+
columns,
|
|
1256
|
+
search
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
//#endregion
|
|
1260
|
+
//#region src/schema/introspect-tables.ts
|
|
1261
|
+
/**
|
|
1262
|
+
* Describe every table of a Postgres schema, as the runtime serves them.
|
|
1263
|
+
*
|
|
1264
|
+
* Reads the catalogue (`readSchemaMetadata`: tables with `relrowsecurity`,
|
|
1265
|
+
* columns, enums, keys, foreign keys, unique constraints, indexes, CHECKs,
|
|
1266
|
+
* comments, `pg_policies`) and describes each table that is neither a junction
|
|
1267
|
+
* nor unprotected. Only `SELECT`s.
|
|
1268
|
+
*
|
|
1269
|
+
* @group Schema
|
|
1270
|
+
*/
|
|
1271
|
+
async function introspectTables(client, schema, options = {}) {
|
|
1272
|
+
const { tables, skipped, junctions, unprotected } = describeTables(await readSchemaMetadata(client, schema), {
|
|
1273
|
+
purpose: "serve",
|
|
1274
|
+
...options
|
|
1275
|
+
});
|
|
1276
|
+
return {
|
|
1277
|
+
tables,
|
|
1278
|
+
skipped,
|
|
1279
|
+
junctions,
|
|
1280
|
+
unprotected
|
|
1281
|
+
};
|
|
1282
|
+
}
|
|
1283
|
+
/**
|
|
1284
|
+
* The tables of one Postgres schema that no declared table maps, each
|
|
1285
|
+
* described for "Import an existing table" to adopt.
|
|
1286
|
+
*
|
|
1287
|
+
* Each table is described as `rebase schema introspect` writes it
|
|
1288
|
+
* (`describeTables(…, { purpose: "generate" })`), alone: a foreign key to a
|
|
1289
|
+
* declared table is a `belongsTo`, one to another undeclared table stays a
|
|
1290
|
+
* plain column (its constraint is left as it is), and the generator's reverse
|
|
1291
|
+
* links — relations of other tables — are not this table's to declare.
|
|
1292
|
+
*
|
|
1293
|
+
* Its `rls` is never weaker than what the database enforces: with row-level
|
|
1294
|
+
* security off, or no policy at all, it is `"admin-only"`, and `rlsRaised`
|
|
1295
|
+
* says so. A table with no primary key is listed with why it cannot be
|
|
1296
|
+
* imported. Junction tables and Rebase's own tables are left out. Only
|
|
1297
|
+
* `SELECT`s.
|
|
1298
|
+
*
|
|
1299
|
+
* @param mapped The SQL names of the tables already declared in `schema`.
|
|
1300
|
+
* @group Schema
|
|
1301
|
+
*/
|
|
1302
|
+
async function describeUnmappedTables(client, schema, options) {
|
|
1303
|
+
const metadata = await readSchemaMetadata(client, schema);
|
|
1304
|
+
const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);
|
|
1305
|
+
const joinTables = identifyJoinTables(tablesMap);
|
|
1306
|
+
const candidates = metadata.tables.map((row) => row.table_name).filter((name) => !options.mapped.has(name) && !joinTables.has(name) && classifyTable(name, schema) !== "rebase-internal");
|
|
1307
|
+
const out = [];
|
|
1308
|
+
for (const name of candidates) {
|
|
1309
|
+
const row = metadata.tables.find((candidate) => candidate.table_name === name);
|
|
1310
|
+
const policies = metadata.policies?.filter((policy) => policy.table_name === name) ?? [];
|
|
1311
|
+
const base = {
|
|
1312
|
+
schema,
|
|
1313
|
+
table: name,
|
|
1314
|
+
rlsEnabled: row?.rls_enabled === true,
|
|
1315
|
+
policies: policies.length
|
|
1316
|
+
};
|
|
1317
|
+
if ((tablesMap.get(name)?.pks.length ?? 0) === 0) {
|
|
1318
|
+
out.push({
|
|
1319
|
+
...base,
|
|
1320
|
+
notes: [],
|
|
1321
|
+
unimportable: "it has no primary key, and a table is declared with the column (or columns) that identify a row. Add one (`ALTER TABLE … ADD PRIMARY KEY (…)`) and import it again."
|
|
1322
|
+
});
|
|
1323
|
+
continue;
|
|
1324
|
+
}
|
|
1325
|
+
const described = describeTables(metadata, {
|
|
1326
|
+
purpose: "generate",
|
|
1327
|
+
joinTables,
|
|
1328
|
+
leaveOut: new Set(candidates.filter((other) => other !== name))
|
|
1329
|
+
});
|
|
1330
|
+
const found = described.tables.find((table) => table.table === name);
|
|
1331
|
+
if (!found) {
|
|
1332
|
+
out.push({
|
|
1333
|
+
...base,
|
|
1334
|
+
notes: [],
|
|
1335
|
+
unimportable: "introspection could not describe it."
|
|
1336
|
+
});
|
|
1337
|
+
continue;
|
|
1338
|
+
}
|
|
1339
|
+
const rlsRaised = !base.rlsEnabled ? `Row-level security is off on "${name}", so today every request reaches every row. It is imported as "admin-only": applying it switches row-level security on, and from then on only the server and admins reach its rows, until you add rules.` : policies.length === 0 ? `"${name}" has row-level security on and no policy. It is imported as "admin-only": applying it gives the server and admins its rows, and nobody else, until you add rules.` : void 0;
|
|
1340
|
+
const descriptor = {
|
|
1341
|
+
...found,
|
|
1342
|
+
relations: found.relations.filter((relation) => relation.kind === "belongsTo"),
|
|
1343
|
+
...rlsRaised ? { rls: {
|
|
1344
|
+
posture: "admin-only",
|
|
1345
|
+
rules: [],
|
|
1346
|
+
defaultPolicies: true
|
|
1347
|
+
} } : {}
|
|
1348
|
+
};
|
|
1349
|
+
out.push({
|
|
1350
|
+
...base,
|
|
1351
|
+
descriptor,
|
|
1352
|
+
...rlsRaised ? { rlsRaised } : {},
|
|
1353
|
+
notes: [...described.notes.drift.get(name) ?? [], ...described.notes.remark.get(name) ?? []]
|
|
1354
|
+
});
|
|
1355
|
+
}
|
|
1356
|
+
return out;
|
|
1357
|
+
}
|
|
1358
|
+
/**
|
|
1359
|
+
* The SQL that protects a table introspection skipped: row-level security on,
|
|
1360
|
+
* and an example policy to adapt — what boot prints for it.
|
|
1361
|
+
*
|
|
1362
|
+
* @group Schema
|
|
1363
|
+
*/
|
|
1364
|
+
function rlsRemediationSql(schema, table) {
|
|
1365
|
+
const relation = `${quoteIdent(schema)}.${quoteIdent(table)}`;
|
|
1366
|
+
return `ALTER TABLE ${relation} ENABLE ROW LEVEL SECURITY;\nCREATE POLICY ${quoteIdent(`${table}_owner`)} ON ${relation} FOR ALL TO public USING (owner_id = rebase.uid()); -- an example: write the condition that fits`;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Describe a schema from catalogue rows already read. Pure.
|
|
1370
|
+
*
|
|
1371
|
+
* @group Schema
|
|
1372
|
+
*/
|
|
1373
|
+
function describeTables(metadata, options = {}) {
|
|
1374
|
+
const generate = options.purpose === "generate";
|
|
1375
|
+
const schema = metadata.schema;
|
|
1376
|
+
const tablesMap = buildTablesMap(metadata.tables, metadata.columns, metadata.pks, metadata.fks);
|
|
1377
|
+
const enumMap = buildEnumMap(metadata.enumValues);
|
|
1378
|
+
const joinTables = options.joinTables ?? identifyJoinTables(tablesMap);
|
|
1379
|
+
const leaveOut = options.leaveOut ?? /* @__PURE__ */ new Set();
|
|
1380
|
+
const notes = {
|
|
1381
|
+
drift: /* @__PURE__ */ new Map(),
|
|
1382
|
+
remark: /* @__PURE__ */ new Map()
|
|
1383
|
+
};
|
|
1384
|
+
const note = (table, text, kind = "drift") => {
|
|
1385
|
+
const list = notes[kind].get(table) ?? [];
|
|
1386
|
+
list.push(text);
|
|
1387
|
+
notes[kind].set(table, list);
|
|
1388
|
+
};
|
|
1389
|
+
const skipped = [];
|
|
1390
|
+
const junctions = [];
|
|
1391
|
+
const unprotected = [];
|
|
1392
|
+
const described = [];
|
|
1393
|
+
for (const row of metadata.tables) {
|
|
1394
|
+
const name = row.table_name;
|
|
1395
|
+
if (joinTables.has(name)) {
|
|
1396
|
+
junctions.push({
|
|
1397
|
+
table: name,
|
|
1398
|
+
rlsEnabled: row.rls_enabled === true
|
|
1399
|
+
});
|
|
1400
|
+
continue;
|
|
1401
|
+
}
|
|
1402
|
+
if (leaveOut.has(name)) continue;
|
|
1403
|
+
if (!generate && row.rls_enabled !== true && options.unprotectedTables !== "serve") {
|
|
1404
|
+
skipped.push({
|
|
1405
|
+
table: name,
|
|
1406
|
+
reason: "row-level security is disabled, so the table has no authorization model: every request would reach every row",
|
|
1407
|
+
remediationSql: rlsRemediationSql(schema, name)
|
|
1408
|
+
});
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
if (!generate && row.rls_enabled !== true) unprotected.push(name);
|
|
1412
|
+
described.push(row);
|
|
1413
|
+
}
|
|
1414
|
+
const context = {
|
|
1415
|
+
metadata,
|
|
1416
|
+
schema,
|
|
1417
|
+
generate,
|
|
1418
|
+
tablesMap,
|
|
1419
|
+
enumMap,
|
|
1420
|
+
joinTables,
|
|
1421
|
+
servedNames: new Set(described.map((row) => row.table_name)),
|
|
1422
|
+
checkFacts: options.checkFacts ?? /* @__PURE__ */ new Map(),
|
|
1423
|
+
note
|
|
1424
|
+
};
|
|
1425
|
+
const shapes = /* @__PURE__ */ new Map();
|
|
1426
|
+
for (const row of described) {
|
|
1427
|
+
const meta = tablesMap.get(row.table_name);
|
|
1428
|
+
if (meta) shapes.set(row.table_name, shapeTable(meta, context));
|
|
1429
|
+
}
|
|
1430
|
+
const tables = [];
|
|
1431
|
+
for (const row of described) {
|
|
1432
|
+
const shape = shapes.get(row.table_name);
|
|
1433
|
+
if (shape) tables.push(describeTable(row, shape, shapes, context));
|
|
1434
|
+
}
|
|
1435
|
+
return {
|
|
1436
|
+
tables,
|
|
1437
|
+
skipped,
|
|
1438
|
+
junctions,
|
|
1439
|
+
unprotected,
|
|
1440
|
+
notes
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
var quoteIdent = (name) => `"${name.replace(/"/g, "\"\"")}"`;
|
|
1444
|
+
/** `NOT NULL` facts, as the catalogue says them. */
|
|
1445
|
+
var isNotNull = (col) => col.is_nullable === "NO";
|
|
1446
|
+
/** The foreign keys of a table that a `belongsTo` can hold: one column, pointing at the target's single-column key. */
|
|
1447
|
+
function linkableForeignKeys(meta, context) {
|
|
1448
|
+
const byConstraint = /* @__PURE__ */ new Map();
|
|
1449
|
+
for (const fk of meta.fks) {
|
|
1450
|
+
const key = fk.constraint_name ?? `${fk.column_name}->${fk.foreign_table_name}`;
|
|
1451
|
+
byConstraint.set(key, [...byConstraint.get(key) ?? [], fk]);
|
|
1452
|
+
}
|
|
1453
|
+
const out = [];
|
|
1454
|
+
for (const [constraint, rows] of byConstraint) {
|
|
1455
|
+
const fk = rows[0];
|
|
1456
|
+
if (rows.length > 1) {
|
|
1457
|
+
context.note(meta.name, `the foreign key ${constraint} spans (${rows.map((r) => r.column_name).join(", ")}); a relation holds one column, so its columns are plain columns.`);
|
|
1458
|
+
continue;
|
|
1459
|
+
}
|
|
1460
|
+
if (!context.servedNames.has(fk.foreign_table_name)) continue;
|
|
1461
|
+
const target = context.tablesMap.get(fk.foreign_table_name);
|
|
1462
|
+
if (!target || target.pks.length !== 1 || target.pks[0] !== fk.foreign_column_name) {
|
|
1463
|
+
context.note(meta.name, `"${fk.column_name}" references ${fk.foreign_table_name}(${fk.foreign_column_name}), which is not that table's one-column primary key; a relation points at the key, so it stays a plain column.`);
|
|
1464
|
+
continue;
|
|
1465
|
+
}
|
|
1466
|
+
if (out.some((other) => other.column_name === fk.column_name)) continue;
|
|
1467
|
+
out.push(fk);
|
|
1468
|
+
}
|
|
1469
|
+
return out;
|
|
1470
|
+
}
|
|
1471
|
+
function shapeTable(meta, context) {
|
|
1472
|
+
const { generate } = context;
|
|
1473
|
+
const comments = /* @__PURE__ */ new Map();
|
|
1474
|
+
for (const comment of context.metadata.comments) if (comment.table_name === meta.name && comment.column_name !== null) comments.set(comment.column_name, comment.comment);
|
|
1475
|
+
const links = linkableForeignKeys(meta, context);
|
|
1476
|
+
const linkColumns = new Set(links.map((fk) => fk.column_name));
|
|
1477
|
+
const searchColumns = new Set(meta.columns.filter((col) => generate && col.is_generated === "ALWAYS" && (comments.get(col.column_name) ?? "").startsWith("rebase:search:v1:")).map((col) => col.column_name));
|
|
1478
|
+
const taken = /* @__PURE__ */ new Set();
|
|
1479
|
+
const keyByColumn = /* @__PURE__ */ new Map();
|
|
1480
|
+
const isFolded = (col) => linkColumns.has(col.column_name) && !meta.pks.includes(col.column_name);
|
|
1481
|
+
for (const col of meta.columns) {
|
|
1482
|
+
if (searchColumns.has(col.column_name) || isFolded(col)) continue;
|
|
1483
|
+
const key = firstFreeKey([toWireKey(col.column_name), col.column_name], taken);
|
|
1484
|
+
taken.add(key);
|
|
1485
|
+
keyByColumn.set(col.column_name, key);
|
|
1486
|
+
}
|
|
1487
|
+
const named = [];
|
|
1488
|
+
if (generate) {
|
|
1489
|
+
for (const col of meta.columns) {
|
|
1490
|
+
if (!isFolded(col)) continue;
|
|
1491
|
+
const key = firstFreeKey([toWireKey(col.column_name), col.column_name], taken);
|
|
1492
|
+
taken.add(key);
|
|
1493
|
+
keyByColumn.set(col.column_name, key);
|
|
1494
|
+
}
|
|
1495
|
+
for (const fk of links) {
|
|
1496
|
+
const stripped = toWireKey(fk.column_name.replace(/_id$/, ""));
|
|
1497
|
+
const name = firstFreeKey([stripped, `${stripped}Relation`], taken);
|
|
1498
|
+
taken.add(name);
|
|
1499
|
+
named.push({
|
|
1500
|
+
fk,
|
|
1501
|
+
name
|
|
1502
|
+
});
|
|
1503
|
+
}
|
|
1504
|
+
} else {
|
|
1505
|
+
for (const fk of links) {
|
|
1506
|
+
const stripped = toWireKey(fk.column_name.replace(/_id$/, ""));
|
|
1507
|
+
const name = firstFreeKey([
|
|
1508
|
+
...meta.pks.includes(fk.column_name) && stripped === fk.column_name ? [] : [stripped],
|
|
1509
|
+
fk.foreign_table_name,
|
|
1510
|
+
toWireKey(fk.foreign_table_name),
|
|
1511
|
+
`${stripped}Relation`
|
|
1512
|
+
], taken);
|
|
1513
|
+
taken.add(name);
|
|
1514
|
+
named.push({
|
|
1515
|
+
fk,
|
|
1516
|
+
name
|
|
1517
|
+
});
|
|
1518
|
+
}
|
|
1519
|
+
for (const col of meta.columns) {
|
|
1520
|
+
if (!isFolded(col)) continue;
|
|
1521
|
+
const key = firstFreeKey([toWireKey(col.column_name), col.column_name], taken);
|
|
1522
|
+
taken.add(key);
|
|
1523
|
+
keyByColumn.set(col.column_name, key);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
const uniques = new Set(context.metadata.uniques.filter((unique) => unique.table_name === meta.name && unique.column_names.length === 1).map((unique) => unique.column_names[0]));
|
|
1527
|
+
const columns = [];
|
|
1528
|
+
for (const col of meta.columns) {
|
|
1529
|
+
const key = keyByColumn.get(col.column_name);
|
|
1530
|
+
if (key === void 0) continue;
|
|
1531
|
+
const link = named.find((entry) => entry.fk.column_name === col.column_name);
|
|
1532
|
+
columns.push(describeColumn(col, key, meta, context, {
|
|
1533
|
+
unique: uniques.has(col.column_name),
|
|
1534
|
+
description: comments.get(col.column_name),
|
|
1535
|
+
foreignKeyOf: link?.name,
|
|
1536
|
+
derived: !generate && link !== void 0 && isFolded(col)
|
|
1537
|
+
}));
|
|
1538
|
+
}
|
|
1539
|
+
let search;
|
|
1540
|
+
if (generate && searchColumns.size > 0) {
|
|
1541
|
+
const read = reconstructSearchBlock({
|
|
1542
|
+
schema: context.schema,
|
|
1543
|
+
table: meta.name,
|
|
1544
|
+
columns: meta.columns,
|
|
1545
|
+
comments,
|
|
1546
|
+
keyByColumn
|
|
1547
|
+
});
|
|
1548
|
+
if (read.note) context.note(meta.name, read.note);
|
|
1549
|
+
search = read.search;
|
|
1550
|
+
}
|
|
1551
|
+
return {
|
|
1552
|
+
meta,
|
|
1553
|
+
columns,
|
|
1554
|
+
keyByColumn,
|
|
1555
|
+
links: named,
|
|
1556
|
+
taken,
|
|
1557
|
+
search
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
function describeColumn(col, key, meta, context, facts) {
|
|
1561
|
+
const isPk = meta.pks.includes(col.column_name);
|
|
1562
|
+
const sequenceKey = isPk && meta.pks.length === 1 ? serialKind(col) : void 0;
|
|
1563
|
+
const type = sequenceKey ?? columnTypeOf(col, context, meta.name);
|
|
1564
|
+
const out = {
|
|
1565
|
+
key,
|
|
1566
|
+
column: col.column_name,
|
|
1567
|
+
type,
|
|
1568
|
+
nullable: !isPk && !isNotNull(col)
|
|
1569
|
+
};
|
|
1570
|
+
if (isPk) out.primaryKey = true;
|
|
1571
|
+
if (facts.unique && !isPk) out.unique = true;
|
|
1572
|
+
if (col.is_generated === "ALWAYS" && col.generation_expression) {
|
|
1573
|
+
out.generated = { expression: col.generation_expression };
|
|
1574
|
+
out.readOnly = true;
|
|
1575
|
+
} else if (col.is_generated === "ALWAYS") {
|
|
1576
|
+
out.readOnly = true;
|
|
1577
|
+
context.note(meta.name, `"${col.column_name}" is a generated column whose expression was not read; it is declared read-only, and a push would plan it as a plain column.`);
|
|
1578
|
+
} else if (!sequenceKey) {
|
|
1579
|
+
const fallback = defaultOf(col, type);
|
|
1580
|
+
if (fallback) out.default = fallback;
|
|
1581
|
+
}
|
|
1582
|
+
if (facts.description !== void 0) out.description = facts.description;
|
|
1583
|
+
if (facts.foreignKeyOf !== void 0) out.foreignKeyOf = facts.foreignKeyOf;
|
|
1584
|
+
if (facts.derived) out.derived = true;
|
|
1585
|
+
if (context.generate) applyGeneratedFacts(out, col, meta, context);
|
|
1586
|
+
return out;
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* The stamps and CHECK bounds the generator writes — what `schema introspect`
|
|
1590
|
+
* has always declared. Not in `"serve"`: the runtime stamps nothing the
|
|
1591
|
+
* database does not, and leaves CHECKs to the database.
|
|
1592
|
+
*/
|
|
1593
|
+
function applyGeneratedFacts(out, col, meta, context) {
|
|
1594
|
+
const name = col.column_name.toLowerCase();
|
|
1595
|
+
const temporal = out.type.kind === "timestamptz" || out.type.kind === "date" || out.type.kind === "time";
|
|
1596
|
+
const nowDefault = out.default?.kind === "sql" && /^(now\(\)|CURRENT_TIMESTAMP)$/i.test(out.default.expression);
|
|
1597
|
+
if (temporal && !out.primaryKey && out.generated === void 0) {
|
|
1598
|
+
if (name === "updated_at" || name === "updatedat") {
|
|
1599
|
+
out.stamp = {
|
|
1600
|
+
on: "update",
|
|
1601
|
+
value: "now"
|
|
1602
|
+
};
|
|
1603
|
+
delete out.default;
|
|
1604
|
+
} else if (name === "created_at" || name === "createdat" || nowDefault) {
|
|
1605
|
+
out.stamp = {
|
|
1606
|
+
on: "create",
|
|
1607
|
+
value: "now"
|
|
1608
|
+
};
|
|
1609
|
+
delete out.default;
|
|
1610
|
+
}
|
|
1611
|
+
}
|
|
1612
|
+
const checks = context.checkFacts.get(meta.name)?.get(col.column_name);
|
|
1613
|
+
if (!checks) return;
|
|
1614
|
+
const numeric = [
|
|
1615
|
+
"smallint",
|
|
1616
|
+
"integer",
|
|
1617
|
+
"bigint",
|
|
1618
|
+
"real",
|
|
1619
|
+
"doublePrecision",
|
|
1620
|
+
"numeric"
|
|
1621
|
+
].includes(out.type.kind);
|
|
1622
|
+
const text = out.type.kind === "text" || out.type.kind === "varchar" || out.type.kind === "char";
|
|
1623
|
+
const validate = {};
|
|
1624
|
+
if (numeric) {
|
|
1625
|
+
if (checks.min !== void 0) validate.min = checks.min;
|
|
1626
|
+
if (checks.max !== void 0) validate.max = checks.max;
|
|
1627
|
+
if (checks.moreThan !== void 0) validate.moreThan = checks.moreThan;
|
|
1628
|
+
if (checks.lessThan !== void 0) validate.lessThan = checks.lessThan;
|
|
1629
|
+
}
|
|
1630
|
+
if (text) {
|
|
1631
|
+
if (checks.lengthMin !== void 0) validate.min = checks.lengthMin;
|
|
1632
|
+
if (checks.lengthMax !== void 0) validate.max = checks.lengthMax;
|
|
1633
|
+
}
|
|
1634
|
+
if (Object.keys(validate).length > 0) out.validate = validate;
|
|
1635
|
+
if (checks.enumValues && text) context.note(meta.name, `"${col.column_name}" accepts only ${checks.enumValues.map((v) => `'${v}'`).join(", ")} (a CHECK the database enforces); a closed set on a text column is not declared yet (\`.oneOf()\` there waits on \`text-one-of\`), so the API leaves it to the database.`);
|
|
1636
|
+
}
|
|
1637
|
+
/** `NEXTVAL('<table>_<column>_seq')`, the default `SERIAL` gives a column. */
|
|
1638
|
+
var SEQUENCE_DEFAULT = /^nextval\('([^']+)'::regclass\)$/i;
|
|
1639
|
+
/** The serial kind of a single-column key whose default is its own conventional sequence. */
|
|
1640
|
+
function serialKind(col) {
|
|
1641
|
+
const match = col.column_default ? SEQUENCE_DEFAULT.exec(col.column_default.trim()) : null;
|
|
1642
|
+
if (!match) return void 0;
|
|
1643
|
+
if (match[1].replace(/^.*\./, "").replace(/^"|"$/g, "") !== serialSequenceName(col.table_name, col.column_name)) return void 0;
|
|
1644
|
+
switch (col.data_type.toLowerCase()) {
|
|
1645
|
+
case "smallint": return { kind: "smallserial" };
|
|
1646
|
+
case "integer": return { kind: "serial" };
|
|
1647
|
+
case "bigint": return { kind: "bigserial" };
|
|
1648
|
+
default: return;
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
/** A catalogue element type name (`udt_name` without the `_`) as the type an array holds, when it is one Rebase stores in an array. */
|
|
1652
|
+
function elementTypeOf(udt, typmod, enumMap) {
|
|
1653
|
+
switch (udt) {
|
|
1654
|
+
case "text": return { kind: "text" };
|
|
1655
|
+
case "varchar": return typmod !== null && typmod > 4 ? {
|
|
1656
|
+
kind: "varchar",
|
|
1657
|
+
length: typmod - 4
|
|
1658
|
+
} : { kind: "text" };
|
|
1659
|
+
case "bpchar": return {
|
|
1660
|
+
kind: "char",
|
|
1661
|
+
length: typmod !== null && typmod > 4 ? typmod - 4 : 1
|
|
1662
|
+
};
|
|
1663
|
+
case "uuid": return { kind: "uuid" };
|
|
1664
|
+
case "int2": return { kind: "smallint" };
|
|
1665
|
+
case "int4": return { kind: "integer" };
|
|
1666
|
+
case "int8": return { kind: "bigint" };
|
|
1667
|
+
case "float4": return { kind: "real" };
|
|
1668
|
+
case "float8": return { kind: "doublePrecision" };
|
|
1669
|
+
case "numeric": return { kind: "numeric" };
|
|
1670
|
+
case "bool": return { kind: "boolean" };
|
|
1671
|
+
case "timestamptz": return { kind: "timestamptz" };
|
|
1672
|
+
case "date": return { kind: "date" };
|
|
1673
|
+
case "time": return { kind: "time" };
|
|
1674
|
+
default: {
|
|
1675
|
+
const labels = enumMap.get(udt);
|
|
1676
|
+
return labels ? {
|
|
1677
|
+
kind: "enum",
|
|
1678
|
+
values: labels,
|
|
1679
|
+
name: udt
|
|
1680
|
+
} : void 0;
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* A column's Postgres type, as the catalogue states it. A type with no
|
|
1686
|
+
* `ColumnType` member is `{ kind: "other", sqlType }`, spelled as Postgres
|
|
1687
|
+
* names it — served as the driver returns it, and declared with `col.custom()`.
|
|
1688
|
+
*/
|
|
1689
|
+
function columnTypeOf(col, context, table) {
|
|
1690
|
+
switch (col.data_type.toLowerCase()) {
|
|
1691
|
+
case "text": return { kind: "text" };
|
|
1692
|
+
case "character varying":
|
|
1693
|
+
if (typeof col.character_maximum_length === "number" && col.character_maximum_length > 0) return {
|
|
1694
|
+
kind: "varchar",
|
|
1695
|
+
length: col.character_maximum_length
|
|
1696
|
+
};
|
|
1697
|
+
context.note(table, `"${col.column_name}" is a varchar with no length, declared as text: a push would convert it to text, which keeps every value.`);
|
|
1698
|
+
return { kind: "text" };
|
|
1699
|
+
case "character": return {
|
|
1700
|
+
kind: "char",
|
|
1701
|
+
length: typeof col.character_maximum_length === "number" && col.character_maximum_length > 0 ? col.character_maximum_length : 1
|
|
1702
|
+
};
|
|
1703
|
+
case "uuid": return { kind: "uuid" };
|
|
1704
|
+
case "smallint": return { kind: "smallint" };
|
|
1705
|
+
case "integer": return { kind: "integer" };
|
|
1706
|
+
case "bigint": return { kind: "bigint" };
|
|
1707
|
+
case "real": return { kind: "real" };
|
|
1708
|
+
case "double precision": return { kind: "doublePrecision" };
|
|
1709
|
+
case "numeric":
|
|
1710
|
+
if (typeof col.numeric_precision !== "number") return { kind: "numeric" };
|
|
1711
|
+
return typeof col.numeric_scale === "number" ? {
|
|
1712
|
+
kind: "numeric",
|
|
1713
|
+
precision: col.numeric_precision,
|
|
1714
|
+
scale: col.numeric_scale
|
|
1715
|
+
} : {
|
|
1716
|
+
kind: "numeric",
|
|
1717
|
+
precision: col.numeric_precision
|
|
1718
|
+
};
|
|
1719
|
+
case "boolean": return { kind: "boolean" };
|
|
1720
|
+
case "timestamp with time zone": return withPrecision(col) ?? { kind: "timestamptz" };
|
|
1721
|
+
case "date": return { kind: "date" };
|
|
1722
|
+
case "time without time zone": return withPrecision(col) ?? { kind: "time" };
|
|
1723
|
+
case "json": return { kind: "json" };
|
|
1724
|
+
case "jsonb": return { kind: "jsonb" };
|
|
1725
|
+
case "bytea": return { kind: "bytea" };
|
|
1726
|
+
case "user-defined": {
|
|
1727
|
+
const labels = context.enumMap.get(col.udt_name);
|
|
1728
|
+
if (labels) return {
|
|
1729
|
+
kind: "enum",
|
|
1730
|
+
values: labels,
|
|
1731
|
+
name: col.udt_name
|
|
1732
|
+
};
|
|
1733
|
+
if (col.udt_name === "vector" && typeof col.atttypmod === "number" && col.atttypmod > 0) return {
|
|
1734
|
+
kind: "vector",
|
|
1735
|
+
dimensions: col.atttypmod
|
|
1736
|
+
};
|
|
1737
|
+
return {
|
|
1738
|
+
kind: "other",
|
|
1739
|
+
sqlType: col.formatted_type ?? col.udt_name
|
|
1740
|
+
};
|
|
1741
|
+
}
|
|
1742
|
+
case "array": {
|
|
1743
|
+
const element = col.udt_name.replace(/^_/, "");
|
|
1744
|
+
const of = elementTypeOf(element, col.atttypmod, context.enumMap);
|
|
1745
|
+
return of ? {
|
|
1746
|
+
kind: "array",
|
|
1747
|
+
of
|
|
1748
|
+
} : {
|
|
1749
|
+
kind: "other",
|
|
1750
|
+
sqlType: col.formatted_type ?? `${element}[]`
|
|
1751
|
+
};
|
|
1752
|
+
}
|
|
1753
|
+
default: return {
|
|
1754
|
+
kind: "other",
|
|
1755
|
+
sqlType: col.formatted_type ?? col.data_type
|
|
1756
|
+
};
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
/** A temporal column with a declared precision, as `col.custom()` of the type the catalogue prints; `undefined` without one. */
|
|
1760
|
+
function withPrecision(col) {
|
|
1761
|
+
return col.formatted_type && /\(\d+\)/.test(col.formatted_type) ? {
|
|
1762
|
+
kind: "other",
|
|
1763
|
+
sqlType: col.formatted_type
|
|
1764
|
+
} : void 0;
|
|
1765
|
+
}
|
|
1766
|
+
/** `'text'::type` → `text`, unescaped. */
|
|
1767
|
+
var QUOTED_LITERAL = /^'((?:[^']|'')*)'(?:::[\w\s."[\]]+)?$/;
|
|
1768
|
+
/**
|
|
1769
|
+
* A column's DEFAULT, classified.
|
|
1770
|
+
*
|
|
1771
|
+
* - identity → `{ kind: "identity" }`; `gen_random_uuid()` → `random-uuid`;
|
|
1772
|
+
* - a literal of the column's own type → `literal`;
|
|
1773
|
+
* - an expression Rebase can state again verbatim (`now()`, a function call,
|
|
1774
|
+
* an operator) → `sql`;
|
|
1775
|
+
* - a `nextval` of a sequence that is not the column's own `SERIAL` one —
|
|
1776
|
+
* an object Rebase does not create, so stating it would fail on a fresh
|
|
1777
|
+
* database — → `database`: the database owns it, and a push leaves it alone.
|
|
1778
|
+
*/
|
|
1779
|
+
function defaultOf(col, type) {
|
|
1780
|
+
if (col.is_identity === "YES") return { kind: "identity" };
|
|
1781
|
+
const raw = col.column_default?.trim();
|
|
1782
|
+
if (!raw) return void 0;
|
|
1783
|
+
if (/^gen_random_uuid\(\)$/i.test(raw) && type.kind === "uuid") return { kind: "random-uuid" };
|
|
1784
|
+
if (/^nextval\(/i.test(raw)) return { kind: "database" };
|
|
1785
|
+
if (/^NULL(::[\w\s."[\]]+)?$/i.test(raw)) return void 0;
|
|
1786
|
+
const literal = literalOf(raw, type);
|
|
1787
|
+
if (literal !== void 0) return {
|
|
1788
|
+
kind: "literal",
|
|
1789
|
+
value: literal
|
|
1790
|
+
};
|
|
1791
|
+
return {
|
|
1792
|
+
kind: "sql",
|
|
1793
|
+
expression: raw
|
|
1794
|
+
};
|
|
1795
|
+
}
|
|
1796
|
+
/** A DEFAULT that is a literal of the column's type, as the value; `undefined` when it is an expression. */
|
|
1797
|
+
function literalOf(raw, type) {
|
|
1798
|
+
const quoted = QUOTED_LITERAL.exec(raw);
|
|
1799
|
+
const text = quoted ? quoted[1].replace(/''/g, "'") : void 0;
|
|
1800
|
+
switch (type.kind) {
|
|
1801
|
+
case "text":
|
|
1802
|
+
case "varchar":
|
|
1803
|
+
case "char":
|
|
1804
|
+
case "enum": return text;
|
|
1805
|
+
case "smallint":
|
|
1806
|
+
case "integer":
|
|
1807
|
+
case "bigint":
|
|
1808
|
+
case "real":
|
|
1809
|
+
case "doublePrecision":
|
|
1810
|
+
case "numeric": {
|
|
1811
|
+
const value = text ?? raw.replace(/^\((.*)\)$/, "$1").replace(/::[\w\s]+$/, "");
|
|
1812
|
+
return /^-?\d+(\.\d+)?$/.test(value) && Number.isFinite(Number(value)) ? Number(value) : void 0;
|
|
1813
|
+
}
|
|
1814
|
+
case "boolean":
|
|
1815
|
+
if (/^true$/i.test(raw)) return true;
|
|
1816
|
+
if (/^false$/i.test(raw)) return false;
|
|
1817
|
+
return;
|
|
1818
|
+
case "json":
|
|
1819
|
+
case "jsonb":
|
|
1820
|
+
if (text === void 0) return void 0;
|
|
1821
|
+
try {
|
|
1822
|
+
const parsed = JSON.parse(text);
|
|
1823
|
+
return parsed !== null && typeof parsed === "object" ? parsed : void 0;
|
|
1824
|
+
} catch {
|
|
1825
|
+
return;
|
|
1826
|
+
}
|
|
1827
|
+
case "date":
|
|
1828
|
+
case "time":
|
|
1829
|
+
case "timestamptz": return text !== void 0 && /^\d/.test(text) ? text : void 0;
|
|
1830
|
+
default: return;
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
/** `ON DELETE`, when it is not the default a relation gets (`RESTRICT` for a required link, `SET NULL` otherwise). */
|
|
1834
|
+
function onDeleteOf(fk, required) {
|
|
1835
|
+
const rule = fk.delete_rule?.toLowerCase();
|
|
1836
|
+
if (!rule) return void 0;
|
|
1837
|
+
if (rule === (required ? "restrict" : "set null")) return void 0;
|
|
1838
|
+
switch (rule) {
|
|
1839
|
+
case "cascade":
|
|
1840
|
+
case "restrict":
|
|
1841
|
+
case "no action":
|
|
1842
|
+
case "set null":
|
|
1843
|
+
case "set default": return rule;
|
|
1844
|
+
default: return;
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
function describeTable(row, shape, shapes, context) {
|
|
1848
|
+
const { meta } = shape;
|
|
1849
|
+
const name = meta.name;
|
|
1850
|
+
const relations = [];
|
|
1851
|
+
for (const link of shape.links) {
|
|
1852
|
+
const col = meta.columns.find((column) => column.column_name === link.fk.column_name);
|
|
1853
|
+
const required = col ? isNotNull(col) : false;
|
|
1854
|
+
const onDelete = onDeleteOf(link.fk, required);
|
|
1855
|
+
relations.push({
|
|
1856
|
+
name: link.name,
|
|
1857
|
+
kind: "belongsTo",
|
|
1858
|
+
target: link.fk.foreign_table_name,
|
|
1859
|
+
cardinality: "one",
|
|
1860
|
+
localKey: link.fk.column_name,
|
|
1861
|
+
localField: shape.keyByColumn.get(link.fk.column_name) ?? toWireKey(link.fk.column_name),
|
|
1862
|
+
...onDelete !== void 0 ? { onDelete } : {},
|
|
1863
|
+
index: foreignKeyIndexed(name, link.fk.column_name, meta, context),
|
|
1864
|
+
constraint: true
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
if (context.generate) relations.push(...inverseRelations(name, shape, shapes, context));
|
|
1868
|
+
let description;
|
|
1869
|
+
for (const comment of context.metadata.comments) if (comment.table_name === name && comment.column_name === null) description = comment.comment;
|
|
1870
|
+
const descriptor = {
|
|
1871
|
+
name,
|
|
1872
|
+
slug: name,
|
|
1873
|
+
table: name,
|
|
1874
|
+
schema: context.schema,
|
|
1875
|
+
kind: "table",
|
|
1876
|
+
...description !== void 0 ? { description } : {},
|
|
1877
|
+
columns: shape.columns,
|
|
1878
|
+
primaryKey: meta.pks.map((pk) => shape.keyByColumn.get(pk) ?? toWireKey(pk)),
|
|
1879
|
+
relations,
|
|
1880
|
+
rls: rlsOf(row, name, context)
|
|
1881
|
+
};
|
|
1882
|
+
if (shape.search) descriptor.search = shape.search;
|
|
1883
|
+
return descriptor;
|
|
1884
|
+
}
|
|
1885
|
+
/**
|
|
1886
|
+
* Whether the database indexes a foreign-key column the way Rebase would —
|
|
1887
|
+
* so that a `belongsTo` saying `index: true` (the default) plans no new
|
|
1888
|
+
* index. `true` when the indexes were not read: nothing is claimed then.
|
|
1889
|
+
*/
|
|
1890
|
+
function foreignKeyIndexed(table, column, meta, context) {
|
|
1891
|
+
const indexes = context.metadata.indexes?.filter((index) => index.table_name === table);
|
|
1892
|
+
if (indexes === void 0 || meta.pks[0] === column) return true;
|
|
1893
|
+
const derived = foreignKeyIndexSpec(context.schema, table, column).indexName;
|
|
1894
|
+
if (indexes.some((index) => index.index_name === derived)) return true;
|
|
1895
|
+
const servedBy = indexes.find((index) => index.leading_column === column && index.serves_leading_column);
|
|
1896
|
+
context.note(table, servedBy ? `${servedBy.index_name} already indexes "${column}", so its relation says \`index: false\`: without it \`rebase db push\` would build a second index.` : `the database has no index on "${column}", so its relation says \`index: false\`; drop that to have one built.`, "remark");
|
|
1897
|
+
return false;
|
|
1898
|
+
}
|
|
1899
|
+
/** The generator's reverse links: a `hasMany` for each foreign key into the table, a `manyToMany` through each junction. */
|
|
1900
|
+
function inverseRelations(table, shape, shapes, context) {
|
|
1901
|
+
const out = [];
|
|
1902
|
+
const nameFor = (preferred, fallback) => {
|
|
1903
|
+
const name = firstFreeKey([preferred, fallback], shape.taken);
|
|
1904
|
+
shape.taken.add(name);
|
|
1905
|
+
return name;
|
|
1906
|
+
};
|
|
1907
|
+
for (const [source, other] of shapes) for (const link of other.links) {
|
|
1908
|
+
if (link.fk.foreign_table_name !== table) continue;
|
|
1909
|
+
out.push({
|
|
1910
|
+
name: nameFor(source, `${source}_by_${link.fk.column_name}`),
|
|
1911
|
+
kind: "hasMany",
|
|
1912
|
+
target: source,
|
|
1913
|
+
cardinality: "many",
|
|
1914
|
+
foreignKey: link.fk.column_name
|
|
1915
|
+
});
|
|
1916
|
+
}
|
|
1917
|
+
for (const junction of context.joinTables) {
|
|
1918
|
+
const jt = context.tablesMap.get(junction);
|
|
1919
|
+
if (!jt || jt.fks.length < 2) continue;
|
|
1920
|
+
const keyPosition = (fk) => {
|
|
1921
|
+
const position = jt.pks.indexOf(fk.column_name);
|
|
1922
|
+
return position === -1 ? Number.MAX_SAFE_INTEGER : position;
|
|
1923
|
+
};
|
|
1924
|
+
const linkColumns = new Set(jt.fks.map((fk) => fk.column_name));
|
|
1925
|
+
const pivot = () => jt.columns.filter((col) => !linkColumns.has(col.column_name)).map((col) => {
|
|
1926
|
+
const column = describeColumn(col, toWireKey(col.column_name), {
|
|
1927
|
+
...jt,
|
|
1928
|
+
pks: []
|
|
1929
|
+
}, context, {
|
|
1930
|
+
unique: false,
|
|
1931
|
+
derived: false
|
|
1932
|
+
});
|
|
1933
|
+
delete column.primaryKey;
|
|
1934
|
+
return column;
|
|
1935
|
+
});
|
|
1936
|
+
const selfLinks = jt.fks.filter((fk) => fk.foreign_table_name === table).sort((a, b) => keyPosition(a) - keyPosition(b));
|
|
1937
|
+
if (selfLinks.length === 2) {
|
|
1938
|
+
const [own, otherEnd] = selfLinks;
|
|
1939
|
+
const preferred = `${table}_via_${otherEnd.column_name.replace(/_id$/, "")}`;
|
|
1940
|
+
out.push({
|
|
1941
|
+
name: nameFor(preferred, `${preferred}_${junction}`),
|
|
1942
|
+
kind: "manyToMany",
|
|
1943
|
+
target: table,
|
|
1944
|
+
cardinality: "many",
|
|
1945
|
+
through: {
|
|
1946
|
+
table: junction,
|
|
1947
|
+
sourceKey: own.column_name,
|
|
1948
|
+
targetKey: otherEnd.column_name,
|
|
1949
|
+
pivot: pivot()
|
|
1950
|
+
}
|
|
1951
|
+
});
|
|
1952
|
+
continue;
|
|
1953
|
+
}
|
|
1954
|
+
const own = jt.fks.find((fk) => fk.foreign_table_name === table);
|
|
1955
|
+
const otherEnd = jt.fks.find((fk) => fk.foreign_table_name !== table);
|
|
1956
|
+
if (!own || !otherEnd || !context.servedNames.has(otherEnd.foreign_table_name)) continue;
|
|
1957
|
+
const leading = jt.fks.find((fk) => fk.column_name === jt.pks[0])?.foreign_table_name;
|
|
1958
|
+
const sortsFirst = [table, otherEnd.foreign_table_name].sort()[0];
|
|
1959
|
+
if (leading && leading !== sortsFirst && leading !== table) {
|
|
1960
|
+
context.note(table, `the many-to-many with ${otherEnd.foreign_table_name} through ${junction} is declared on ${otherEnd.foreign_table_name} only: declaring it here too would re-key ${junction} from (${jt.pks.join(", ")}).`, "remark");
|
|
1961
|
+
continue;
|
|
1962
|
+
}
|
|
1963
|
+
out.push({
|
|
1964
|
+
name: nameFor(otherEnd.foreign_table_name, `${otherEnd.foreign_table_name}_via_${junction}`),
|
|
1965
|
+
kind: "manyToMany",
|
|
1966
|
+
target: otherEnd.foreign_table_name,
|
|
1967
|
+
cardinality: "many",
|
|
1968
|
+
through: {
|
|
1969
|
+
table: junction,
|
|
1970
|
+
sourceKey: own.column_name,
|
|
1971
|
+
targetKey: otherEnd.column_name,
|
|
1972
|
+
pivot: pivot()
|
|
1973
|
+
}
|
|
1974
|
+
});
|
|
1975
|
+
}
|
|
1976
|
+
return out;
|
|
1977
|
+
}
|
|
1978
|
+
/** The admin baseline's policy names (`<table>_default_admin_*`). */
|
|
1979
|
+
var adminBaselineNames = (table) => tableGeneratedPolicyNames({
|
|
1980
|
+
slug: table,
|
|
1981
|
+
table,
|
|
1982
|
+
columns: {},
|
|
1983
|
+
links: {},
|
|
1984
|
+
idKey: "id",
|
|
1985
|
+
rules: [],
|
|
1986
|
+
auth: false
|
|
1987
|
+
});
|
|
1988
|
+
/** A `pg_policies` row as the rule `db push` compiles back into it. */
|
|
1989
|
+
function ruleOf(policy) {
|
|
1990
|
+
const cmd = policy.cmd.toUpperCase();
|
|
1991
|
+
return policyToSecurityRule({
|
|
1992
|
+
policyname: policy.policy_name,
|
|
1993
|
+
cmd: cmd === "SELECT" || cmd === "INSERT" || cmd === "UPDATE" || cmd === "DELETE" || cmd === "ALL" ? cmd : void 0,
|
|
1994
|
+
permissive: policy.permissive.toUpperCase() === "RESTRICTIVE" ? "RESTRICTIVE" : "PERMISSIVE",
|
|
1995
|
+
roles: policy.roles,
|
|
1996
|
+
qual: policy.qual,
|
|
1997
|
+
with_check: policy.with_check
|
|
1998
|
+
});
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* A table's row-level security, from the catalogue.
|
|
2002
|
+
*
|
|
2003
|
+
* `"serve"`: every policy as a rule, `defaultPolicies: false` (Rebase injected
|
|
2004
|
+
* nothing). RLS on with no policy is `rules: []` — closed. RLS off (only with
|
|
2005
|
+
* `unprotectedTables: "serve"`) is one rule granting everyone everything,
|
|
2006
|
+
* which is what such a table does.
|
|
2007
|
+
*
|
|
2008
|
+
* `"generate"`: the admin baseline is folded — a table holding every baseline
|
|
2009
|
+
* policy keeps `defaultPolicies` and lists only its own; holding nothing else,
|
|
2010
|
+
* it is `"admin-only"`. RLS on with no policy at all is one closed rule (a
|
|
2011
|
+
* push then creates a policy that grants nothing, which is what the table
|
|
2012
|
+
* does today). RLS off keeps the baseline and its own policies (`"admin-only"`
|
|
2013
|
+
* when it has none): the push switches it on.
|
|
2014
|
+
*/
|
|
2015
|
+
function rlsOf(row, table, context) {
|
|
2016
|
+
const policies = context.metadata.policies?.filter((policy) => policy.table_name === table);
|
|
2017
|
+
if (!context.generate) {
|
|
2018
|
+
if (row.rls_enabled !== true) return {
|
|
2019
|
+
posture: "rules",
|
|
2020
|
+
rules: [{
|
|
2021
|
+
name: `${table}_rls_disabled`,
|
|
2022
|
+
operations: ["all"],
|
|
2023
|
+
access: "public"
|
|
2024
|
+
}],
|
|
2025
|
+
defaultPolicies: false
|
|
2026
|
+
};
|
|
2027
|
+
return {
|
|
2028
|
+
posture: "rules",
|
|
2029
|
+
rules: (policies ?? []).map(ruleOf),
|
|
2030
|
+
defaultPolicies: false
|
|
2031
|
+
};
|
|
2032
|
+
}
|
|
2033
|
+
if (policies === void 0) return {
|
|
2034
|
+
posture: "admin-only",
|
|
2035
|
+
rules: [],
|
|
2036
|
+
defaultPolicies: true
|
|
2037
|
+
};
|
|
2038
|
+
const baseline = adminBaselineNames(table);
|
|
2039
|
+
if (row.rls_enabled === false) {
|
|
2040
|
+
const own = policies.filter((policy) => !baseline.has(policy.policy_name)).map(ruleOf);
|
|
2041
|
+
return own.length > 0 ? {
|
|
2042
|
+
posture: "rules",
|
|
2043
|
+
rules: own,
|
|
2044
|
+
defaultPolicies: true
|
|
2045
|
+
} : {
|
|
2046
|
+
posture: "admin-only",
|
|
2047
|
+
rules: [],
|
|
2048
|
+
defaultPolicies: true
|
|
2049
|
+
};
|
|
2050
|
+
}
|
|
2051
|
+
const present = new Set(policies.map((policy) => policy.policy_name));
|
|
2052
|
+
if (row.rls_enabled !== true && present.size === 0) return {
|
|
2053
|
+
posture: "admin-only",
|
|
2054
|
+
rules: [],
|
|
2055
|
+
defaultPolicies: true
|
|
2056
|
+
};
|
|
2057
|
+
const keepsBaseline = [...baseline].every((name) => present.has(name));
|
|
2058
|
+
const own = policies.filter((policy) => !(keepsBaseline && baseline.has(policy.policy_name))).map(ruleOf);
|
|
2059
|
+
if (keepsBaseline) return own.length > 0 ? {
|
|
2060
|
+
posture: "rules",
|
|
2061
|
+
rules: own,
|
|
2062
|
+
defaultPolicies: true
|
|
2063
|
+
} : {
|
|
2064
|
+
posture: "admin-only",
|
|
2065
|
+
rules: [],
|
|
2066
|
+
defaultPolicies: true
|
|
2067
|
+
};
|
|
2068
|
+
if (own.length > 0) return {
|
|
2069
|
+
posture: "rules",
|
|
2070
|
+
rules: own,
|
|
2071
|
+
defaultPolicies: false
|
|
2072
|
+
};
|
|
2073
|
+
return {
|
|
2074
|
+
posture: "rules",
|
|
2075
|
+
rules: [{
|
|
2076
|
+
name: `${table}_closed`,
|
|
2077
|
+
operation: "all",
|
|
2078
|
+
using: "false"
|
|
2079
|
+
}],
|
|
2080
|
+
defaultPolicies: false
|
|
2081
|
+
};
|
|
2082
|
+
}
|
|
2083
|
+
//#endregion
|
|
2084
|
+
export { describeRlsOffTables as a, mergeIndexModule as c, lookupCandidates as d, CMS_PACKAGE as f, buildTablesMap as i, safeHostFromUrl as l, introspectTables as n, generateSchemaModules as o, buildEnumMap as r, identifyJoinTables as s, describeUnmappedTables as t, classifyTables as u };
|
|
2085
|
+
|
|
2086
|
+
//# sourceMappingURL=introspect-tables-Cw_A-kk4.js.map
|