@rebasepro/server-postgres 0.30.1 → 0.31.0-canary.g902a0ce
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
|
@@ -1,2047 +0,0 @@
|
|
|
1
|
-
import { createRequire as __createRequire } from "module";
|
|
2
|
-
__createRequire(import.meta.url);
|
|
3
|
-
import { a as buildSearchColumnSpec, u as searchColumnStamps } from "./search-column-BM-GV6vH.js";
|
|
4
|
-
import { p as foreignKeyIndexSpec } from "./source-fZb92pN8.js";
|
|
5
|
-
import { DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE } from "@rebasepro/types";
|
|
6
|
-
import { getGeneratedPolicyNames, policyToSecurityRule } from "@rebasepro/common";
|
|
7
|
-
import { firstFreeKey, toPostgresIdentifier, toWireKey } from "@rebasepro/utils";
|
|
8
|
-
//#region src/schema/introspect-db-naming.ts
|
|
9
|
-
/**
|
|
10
|
-
* Naming helpers shared by the introspection modules. These live apart from
|
|
11
|
-
* `introspect-db-logic.ts` because the inference pass needs them too, and
|
|
12
|
-
* importing them from there would close a cycle back through this module.
|
|
13
|
-
*/
|
|
14
|
-
/**
|
|
15
|
-
* Convert a snake_case name to a human-readable Title Case label.
|
|
16
|
-
* e.g. "created_at" -> "Created At", "customer_id" -> "Customer Id"
|
|
17
|
-
*/
|
|
18
|
-
function humanize(snakeName) {
|
|
19
|
-
return snakeName.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
|
-
//#region src/schema/introspect-db-inference.ts
|
|
23
|
-
var ISO_8601_REGEX = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/;
|
|
24
|
-
var UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
25
|
-
var CUID_REGEX = /^c[^\s-]{7,}$/i;
|
|
26
|
-
function inferPropertyFromData(columnName, pgDataType, currentPropType, sampleValues, isPk, emitAdmin = true) {
|
|
27
|
-
const result = {};
|
|
28
|
-
const extraLines = [];
|
|
29
|
-
const adminOptions = [];
|
|
30
|
-
const validValues = sampleValues.filter((v) => v !== null && v !== void 0 && v !== "");
|
|
31
|
-
if (validValues.length === 0) return result;
|
|
32
|
-
const colNameLower = columnName.toLowerCase();
|
|
33
|
-
if (currentPropType === "number") {
|
|
34
|
-
if (validValues.every((v) => v === 0 || v === 1 || v === "0" || v === "1")) {
|
|
35
|
-
result.propType = "boolean";
|
|
36
|
-
return result;
|
|
37
|
-
}
|
|
38
|
-
const numValues = validValues.map((v) => Number(v)).filter((v) => !isNaN(v));
|
|
39
|
-
if (numValues.length === validValues.length) {
|
|
40
|
-
const min = Math.min(...numValues);
|
|
41
|
-
const max = Math.max(...numValues);
|
|
42
|
-
if (min >= 0 && max <= 100 && (colNameLower.includes("percent") || colNameLower.includes("rate") || colNameLower.includes("score"))) extraLines.push(" validation: {\n min: 0,\n max: 100\n }");
|
|
43
|
-
else if (min >= 0 && (colNameLower.includes("count") || colNameLower.includes("total") || colNameLower.includes("amount"))) extraLines.push(" validation: {\n min: 0\n }");
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
if (currentPropType === "map" || pgDataType.includes("json")) {
|
|
47
|
-
let allArrays = true;
|
|
48
|
-
let allObjects = true;
|
|
49
|
-
for (const v of validValues) {
|
|
50
|
-
let parsed = v;
|
|
51
|
-
if (typeof v === "string") try {
|
|
52
|
-
parsed = JSON.parse(v);
|
|
53
|
-
} catch (e) {
|
|
54
|
-
allArrays = false;
|
|
55
|
-
allObjects = false;
|
|
56
|
-
break;
|
|
57
|
-
}
|
|
58
|
-
if (Array.isArray(parsed)) allObjects = false;
|
|
59
|
-
else if (typeof parsed === "object" && parsed !== null) allArrays = false;
|
|
60
|
-
else {
|
|
61
|
-
allArrays = false;
|
|
62
|
-
allObjects = false;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
if (allArrays && !allObjects) {
|
|
66
|
-
result.propType = "array";
|
|
67
|
-
let allNumbers = true;
|
|
68
|
-
let allStrings = true;
|
|
69
|
-
for (const v of validValues) {
|
|
70
|
-
const parsed = typeof v === "string" ? JSON.parse(v) : v;
|
|
71
|
-
for (const item of parsed) {
|
|
72
|
-
if (typeof item !== "number") allNumbers = false;
|
|
73
|
-
if (typeof item !== "string") allStrings = false;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
const innerType = allNumbers ? "number" : allStrings ? "string" : "map";
|
|
77
|
-
extraLines.push(` of: { name: "${humanize(columnName)} Item", type: "${innerType}" }`);
|
|
78
|
-
} else {
|
|
79
|
-
result.propType = "map";
|
|
80
|
-
if (allObjects && validValues.length > 0) {
|
|
81
|
-
const schema = {};
|
|
82
|
-
for (const v of validValues) {
|
|
83
|
-
const parsed = typeof v === "string" ? JSON.parse(v) : v;
|
|
84
|
-
for (const [k, val] of Object.entries(parsed)) {
|
|
85
|
-
if (val === null || val === void 0) continue;
|
|
86
|
-
const type = typeof val;
|
|
87
|
-
if (type === "string" || type === "number" || type === "boolean") {
|
|
88
|
-
if (!schema[k]) schema[k] = type;
|
|
89
|
-
else if (schema[k] !== type) schema[k] = "mixed";
|
|
90
|
-
} else if (Array.isArray(val)) {
|
|
91
|
-
if (!schema[k]) schema[k] = "array";
|
|
92
|
-
else if (schema[k] !== "array") schema[k] = "mixed";
|
|
93
|
-
} else if (type === "object") {
|
|
94
|
-
if (!schema[k]) schema[k] = "map";
|
|
95
|
-
else if (schema[k] !== "map") schema[k] = "mixed";
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
const keys = Object.keys(schema).filter((k) => schema[k] !== "mixed");
|
|
100
|
-
if (keys.length > 0) {
|
|
101
|
-
const props = keys.map((k) => {
|
|
102
|
-
return `\n ${k}: { name: "${humanize(k)}", type: "${schema[k]}" }`;
|
|
103
|
-
}).join(",");
|
|
104
|
-
extraLines.push(` properties: {${props}\n }`);
|
|
105
|
-
} else extraLines.push(" keyValue: true");
|
|
106
|
-
} else extraLines.push(" keyValue: true");
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
if (currentPropType === "string") {
|
|
110
|
-
if (validValues.every((v) => typeof v === "string" && ISO_8601_REGEX.test(v))) {
|
|
111
|
-
result.propType = "date";
|
|
112
|
-
return result;
|
|
113
|
-
}
|
|
114
|
-
const uniqueValues = new Set(validValues);
|
|
115
|
-
let maxEnumLength = 0;
|
|
116
|
-
for (const v of uniqueValues) if (typeof v === "string" && v.length > maxEnumLength) maxEnumLength = v.length;
|
|
117
|
-
if (uniqueValues.size > 0 && uniqueValues.size <= 5 && maxEnumLength <= 50 && validValues.length > uniqueValues.size && !uniqueValues.has("")) {
|
|
118
|
-
if (!(isPk || colNameLower.endsWith("_id"))) {
|
|
119
|
-
const enumEntries = Array.from(uniqueValues).map((v) => `{ id: ${JSON.stringify(v)}, label: ${JSON.stringify(humanize(v))} }`).join(", ");
|
|
120
|
-
extraLines.push(` enum: [${enumEntries}]`);
|
|
121
|
-
result.extra = extraLines.length > 0 ? "\n" + extraLines.join(",\n") + "," : "";
|
|
122
|
-
return result;
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
const allUuid = validValues.every((v) => typeof v === "string" && UUID_REGEX.test(v));
|
|
126
|
-
const allCuid = validValues.every((v) => typeof v === "string" && CUID_REGEX.test(v));
|
|
127
|
-
if (allUuid) {
|
|
128
|
-
if (isPk) extraLines.push(" isId: \"uuid\"");
|
|
129
|
-
} else if (allCuid) {
|
|
130
|
-
if (isPk) extraLines.push(" isId: \"cuid\"");
|
|
131
|
-
}
|
|
132
|
-
let maxLength = 0;
|
|
133
|
-
let hasNewlines = false;
|
|
134
|
-
let hasMarkdown = false;
|
|
135
|
-
for (const v of validValues) if (typeof v === "string") {
|
|
136
|
-
if (v.length > maxLength) maxLength = v.length;
|
|
137
|
-
if (v.includes("\n")) hasNewlines = true;
|
|
138
|
-
if (/^#{1,6}\s+.+/m.test(v) || /\*\*.+\*\*/.test(v) || /\[.+\]\(.+\)/.test(v) || /^\s*[-*]\s+.+/m.test(v)) hasMarkdown = true;
|
|
139
|
-
}
|
|
140
|
-
if (hasMarkdown) adminOptions.push("multiline: true", "markdown: true");
|
|
141
|
-
else if (hasNewlines || maxLength > 100) adminOptions.push("multiline: true");
|
|
142
|
-
if (maxLength > 0 && maxLength < 1e4) {
|
|
143
|
-
const paddedMax = Math.ceil(maxLength * 1.5 / 10) * 10;
|
|
144
|
-
if (paddedMax < 255) extraLines.push(` validation: {\n max: ${paddedMax}\n }`);
|
|
145
|
-
}
|
|
146
|
-
const isUrl = colNameLower.endsWith("_url") || colNameLower.endsWith("_uri") || colNameLower.endsWith("_link");
|
|
147
|
-
const isMedia = colNameLower.includes("image") || colNameLower.includes("avatar") || colNameLower.includes("photo") || colNameLower.includes("logo") || colNameLower.includes("cover");
|
|
148
|
-
if (validValues.every((v) => typeof v === "string" && (v.startsWith("http://") || v.startsWith("https://")))) if (validValues.some((v) => typeof v === "string" && v.match(/\.(jpeg|jpg|gif|png|webp|svg)/i)) || isMedia) {
|
|
149
|
-
extraLines.push(" url: true");
|
|
150
|
-
adminOptions.push("urlPreview: \"image\"");
|
|
151
|
-
} else extraLines.push(" url: true");
|
|
152
|
-
else if (validValues.some((v) => typeof v === "string" && v.match(/\.[a-zA-Z0-9]+$/))) {
|
|
153
|
-
const firstVal = validValues[0];
|
|
154
|
-
const lastSlash = firstVal.lastIndexOf("/");
|
|
155
|
-
const inferredStoragePath = lastSlash > 0 ? firstVal.substring(0, lastSlash) : "files";
|
|
156
|
-
extraLines.push(` storage: {\n storagePath: "${inferredStoragePath}"\n }`);
|
|
157
|
-
} else if (isUrl) {
|
|
158
|
-
extraLines.push(" url: true");
|
|
159
|
-
if (isMedia) adminOptions.push("urlPreview: \"image\"");
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
if (emitAdmin && adminOptions.length > 0) extraLines.push(` admin: {\n${adminOptions.map((o) => ` ${o}`).join(",\n")}\n }`);
|
|
163
|
-
result.extra = extraLines.length > 0 ? "\n" + extraLines.join(",\n") + "," : "";
|
|
164
|
-
return result;
|
|
165
|
-
}
|
|
166
|
-
//#endregion
|
|
167
|
-
//#region src/schema/introspect-db-types.ts
|
|
168
|
-
/**
|
|
169
|
-
* The PostgreSQL type → Rebase property type mapping.
|
|
170
|
-
*
|
|
171
|
-
* Split out of `introspect-db-logic` so that the structural analysis can use it
|
|
172
|
-
* without importing the generator, which imports the analysis. Re-exported from
|
|
173
|
-
* `introspect-db-logic` so existing callers keep their import path.
|
|
174
|
-
*/
|
|
175
|
-
/**
|
|
176
|
-
* Map a PostgreSQL data type to a Rebase property type.
|
|
177
|
-
*/
|
|
178
|
-
function mapPgType(dataType) {
|
|
179
|
-
const dt = dataType.toLowerCase();
|
|
180
|
-
if (dt === "interval") return "string";
|
|
181
|
-
if (dt === "array" || dt.startsWith("_")) return "array";
|
|
182
|
-
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";
|
|
183
|
-
if (dt.includes("bool")) return "boolean";
|
|
184
|
-
if (dt.includes("time") || dt.includes("date")) return "date";
|
|
185
|
-
if (dt === "json" || dt === "jsonb") return "map";
|
|
186
|
-
if (dt === "bytea") return "binary";
|
|
187
|
-
if (dt === "inet" || dt === "cidr" || dt === "macaddr" || dt === "macaddr8") return "string";
|
|
188
|
-
if (dt === "uuid") return "string";
|
|
189
|
-
return "string";
|
|
190
|
-
}
|
|
191
|
-
//#endregion
|
|
192
|
-
//#region src/schema/introspect-db-storage.ts
|
|
193
|
-
var literal = (value) => JSON.stringify(value);
|
|
194
|
-
/** `character varying` → `varchar`, the spellings the planner's `columnType` uses. */
|
|
195
|
-
var NUMBER_COLUMN_TYPE = {
|
|
196
|
-
"integer": "integer",
|
|
197
|
-
"bigint": "bigint",
|
|
198
|
-
"real": "real",
|
|
199
|
-
"double precision": "double precision"
|
|
200
|
-
};
|
|
201
|
-
/** A sequence default — `nextval('orders_id_seq'::regclass)`. */
|
|
202
|
-
var SEQUENCE_DEFAULT = /^nextval\('([^']+)'::regclass\)$/;
|
|
203
|
-
/**
|
|
204
|
-
* Whether a `nextval` default names the sequence `SERIAL` would have made for
|
|
205
|
-
* this column — the only one the planner can declare, because it declares the
|
|
206
|
-
* column as `SERIAL` and lets Postgres name the sequence.
|
|
207
|
-
*/
|
|
208
|
-
var isConventionalSequence = (col, sequence) => {
|
|
209
|
-
return sequence.replace(/^.*\./, "").replace(/^"|"$/g, "") === serialSequenceName(col.table_name, col.column_name);
|
|
210
|
-
};
|
|
211
|
-
/**
|
|
212
|
-
* The name Postgres gives a `SERIAL` column's sequence — `ChooseRelationName`
|
|
213
|
-
* with the `seq` label: `<table>_<column>_seq`, and when that is over 63 bytes
|
|
214
|
-
* the longer of the two names is shortened, one character at a time, until it
|
|
215
|
-
* fits.
|
|
216
|
-
*/
|
|
217
|
-
function serialSequenceName(table, column) {
|
|
218
|
-
const available = 58;
|
|
219
|
-
let tableChars = table.length;
|
|
220
|
-
let columnChars = column.length;
|
|
221
|
-
while (tableChars + columnChars > available) if (tableChars > columnChars) tableChars--;
|
|
222
|
-
else columnChars--;
|
|
223
|
-
return `${table.slice(0, tableChars)}_${column.slice(0, columnChars)}_seq`;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* The `isId` (and `columnType`) a single-column primary key needs.
|
|
227
|
-
*
|
|
228
|
-
* `isId: "increment"` is an identity column, and only an INTEGER one. A serial
|
|
229
|
-
* key — an integer with a `nextval` default — is `SERIAL`/`BIGSERIAL`, declared
|
|
230
|
-
* through `columnType` beside `isId: "manual"`. A uuid key is `"uuid"` only when
|
|
231
|
-
* the database generates it; a key with no default is `"manual"`, which keeps
|
|
232
|
-
* the planner from inventing one.
|
|
233
|
-
*/
|
|
234
|
-
function primaryKeyStorage(col, propType) {
|
|
235
|
-
const dataType = col.data_type.toLowerCase();
|
|
236
|
-
const fallback = col.column_default?.trim();
|
|
237
|
-
if (propType === "number") {
|
|
238
|
-
if (col.is_identity === "YES") {
|
|
239
|
-
if (dataType === "integer") return { keys: [`isId: ${literal("increment")}`] };
|
|
240
|
-
return {
|
|
241
|
-
keys: [`isId: ${literal("increment")}`],
|
|
242
|
-
note: `"${col.column_name}" is a ${dataType} identity key; \`isId: "increment"\` is always INTEGER, so a push would plan a narrowing type change (and ask before applying it).`
|
|
243
|
-
};
|
|
244
|
-
}
|
|
245
|
-
const sequence = fallback ? SEQUENCE_DEFAULT.exec(fallback) : null;
|
|
246
|
-
if (sequence) {
|
|
247
|
-
const serial = dataType === "bigint" ? "bigserial" : dataType === "integer" ? "serial" : void 0;
|
|
248
|
-
if (serial && isConventionalSequence(col, sequence[1])) return { keys: [`isId: ${literal("manual")}`, `columnType: ${literal(serial)}`] };
|
|
249
|
-
return {
|
|
250
|
-
keys: [`isId: ${literal("manual")}`, ...numberColumnType(dataType)],
|
|
251
|
-
note: `"${col.column_name}" takes its value from the sequence ${sequence[1]}, which no property can declare; a push would plan dropping that default.`
|
|
252
|
-
};
|
|
253
|
-
}
|
|
254
|
-
if (fallback) return { keys: [`isId: ${literal(`sql\`${fallback}\``)}`, ...numberColumnType(dataType)] };
|
|
255
|
-
return { keys: [`isId: ${literal("manual")}`, ...numberColumnType(dataType)] };
|
|
256
|
-
}
|
|
257
|
-
if (propType === "date" && dataType === "date") return { keys: [`isId: ${literal("manual")}`, `columnType: ${literal("date")}`] };
|
|
258
|
-
if (dataType === "uuid") {
|
|
259
|
-
if (fallback === "gen_random_uuid()") return { keys: [`isId: ${literal("uuid")}`] };
|
|
260
|
-
if (fallback) return { keys: [`isId: ${literal(`sql\`${fallback}\``)}`, `columnType: ${literal("uuid")}`] };
|
|
261
|
-
return { keys: [`isId: ${literal("manual")}`, `columnType: ${literal("uuid")}`] };
|
|
262
|
-
}
|
|
263
|
-
const strategy = fallback ? `sql\`${fallback}\`` : "manual";
|
|
264
|
-
const stored = stringStorage(col);
|
|
265
|
-
return {
|
|
266
|
-
keys: [`isId: ${literal(strategy)}`, ...stored.keys],
|
|
267
|
-
note: stored.note
|
|
268
|
-
};
|
|
269
|
-
}
|
|
270
|
-
/** `columnType` for a number column the planner would otherwise make NUMERIC. */
|
|
271
|
-
function numberColumnType(dataType) {
|
|
272
|
-
const mapped = NUMBER_COLUMN_TYPE[dataType];
|
|
273
|
-
return mapped ? [`columnType: ${literal(mapped)}`] : [];
|
|
274
|
-
}
|
|
275
|
-
/** The keys a `string` column needs; the bound itself is emitted as `validation.max`. */
|
|
276
|
-
function stringStorage(col) {
|
|
277
|
-
switch (col.data_type.toLowerCase()) {
|
|
278
|
-
case "text": return { keys: [] };
|
|
279
|
-
case "character varying":
|
|
280
|
-
if (typeof col.character_maximum_length === "number" && col.character_maximum_length > 0) return { keys: [`columnType: ${literal("varchar")}`] };
|
|
281
|
-
return {
|
|
282
|
-
keys: [],
|
|
283
|
-
note: `"${col.column_name}" is a varchar with no length, declared as text: a push would plan converting it to text, which keeps every value.`
|
|
284
|
-
};
|
|
285
|
-
case "character": return { keys: [`columnType: ${literal("char")}`] };
|
|
286
|
-
case "uuid": return { keys: [`columnType: ${literal("uuid")}`] };
|
|
287
|
-
default: return {
|
|
288
|
-
keys: [],
|
|
289
|
-
note: `"${col.column_name}" is ${col.data_type === "USER-DEFINED" ? col.udt_name : col.data_type}, which no property type stores; it is read as text, and a push would plan converting the column to text.`
|
|
290
|
-
};
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
/**
|
|
294
|
-
* The keys a non-key column needs, for the property type introspection chose.
|
|
295
|
-
*
|
|
296
|
-
* `enumTypeName` is the type the planner would name for this column
|
|
297
|
-
* (`<table>_<column>`, cut to 63 bytes); an enum column whose type is called
|
|
298
|
-
* anything else cannot be declared, and the note says how to rename it.
|
|
299
|
-
*/
|
|
300
|
-
function columnStorage(col, propType, context) {
|
|
301
|
-
const dataType = col.data_type.toLowerCase();
|
|
302
|
-
if (context.isEnumColumn) {
|
|
303
|
-
if (col.udt_name === context.enumTypeName) return { keys: [] };
|
|
304
|
-
return {
|
|
305
|
-
keys: [],
|
|
306
|
-
note: context.enumTypeShared ? `"${col.column_name}" uses the enum type "${col.udt_name}", which other columns share; Rebase gives each column its own type (<table>_<column>), so a push would plan "${context.enumTypeName}" and a conversion Postgres cannot cast.` : `"${col.column_name}" uses the enum type "${col.udt_name}", and Rebase names a column's enum type <table>_<column>. Rename it before pushing: ALTER TYPE "${col.udt_name}" RENAME TO "${context.enumTypeName}";`
|
|
307
|
-
};
|
|
308
|
-
}
|
|
309
|
-
switch (propType) {
|
|
310
|
-
case "number": {
|
|
311
|
-
if (dataType === "numeric") {
|
|
312
|
-
const keys = [];
|
|
313
|
-
if (typeof col.numeric_precision === "number") keys.push(`precision: ${col.numeric_precision}`);
|
|
314
|
-
if (typeof col.numeric_precision === "number" && typeof col.numeric_scale === "number") keys.push(`scale: ${col.numeric_scale}`);
|
|
315
|
-
return { keys };
|
|
316
|
-
}
|
|
317
|
-
if (dataType === "smallint") return {
|
|
318
|
-
keys: [`columnType: ${literal("integer")}`],
|
|
319
|
-
note: `"${col.column_name}" is smallint, which no \`columnType\` names; it is declared integer, so a push widens it (every value survives).`
|
|
320
|
-
};
|
|
321
|
-
const mapped = numberColumnType(dataType);
|
|
322
|
-
if (mapped.length > 0) return { keys: mapped };
|
|
323
|
-
return {
|
|
324
|
-
keys: [],
|
|
325
|
-
note: `"${col.column_name}" is ${col.data_type}, which no \`columnType\` names; it is declared numeric, and a push would plan converting it.`
|
|
326
|
-
};
|
|
327
|
-
}
|
|
328
|
-
case "string": return stringStorage(col);
|
|
329
|
-
case "date": switch (dataType) {
|
|
330
|
-
case "timestamp with time zone": return { keys: [] };
|
|
331
|
-
case "date": return { keys: [`columnType: ${literal("date")}`] };
|
|
332
|
-
case "time without time zone": return { keys: [`columnType: ${literal("time")}`] };
|
|
333
|
-
default: return {
|
|
334
|
-
keys: [],
|
|
335
|
-
note: `"${col.column_name}" is ${col.data_type}; a date property stores timestamptz, date or time, so a push would plan converting it to timestamptz (and ask before applying it).`
|
|
336
|
-
};
|
|
337
|
-
}
|
|
338
|
-
case "map": return dataType === "json" ? { keys: [`columnType: ${literal("json")}`] } : { keys: [] };
|
|
339
|
-
default: return { keys: [] };
|
|
340
|
-
}
|
|
341
|
-
}
|
|
342
|
-
/**
|
|
343
|
-
* The `columnType` an array column needs, or a note when its element type is
|
|
344
|
-
* not one the planner stores natively.
|
|
345
|
-
*
|
|
346
|
-
* Only `text[]`, `integer[]`, `boolean[]` and `numeric[]` are. Reading
|
|
347
|
-
* `bigint[]` as `integer[]` — what this used to do — planned a narrowing.
|
|
348
|
-
*/
|
|
349
|
-
function arrayStorage(col) {
|
|
350
|
-
switch (col.udt_name) {
|
|
351
|
-
case "_text": return {
|
|
352
|
-
columnType: "text[]",
|
|
353
|
-
innerType: "string"
|
|
354
|
-
};
|
|
355
|
-
case "_int4": return {
|
|
356
|
-
columnType: "integer[]",
|
|
357
|
-
innerType: "number"
|
|
358
|
-
};
|
|
359
|
-
case "_bool": return {
|
|
360
|
-
columnType: "boolean[]",
|
|
361
|
-
innerType: "boolean"
|
|
362
|
-
};
|
|
363
|
-
case "_numeric": return {
|
|
364
|
-
columnType: "numeric[]",
|
|
365
|
-
innerType: "number"
|
|
366
|
-
};
|
|
367
|
-
default: {
|
|
368
|
-
const element = col.udt_name.replace(/^_/, "");
|
|
369
|
-
return {
|
|
370
|
-
innerType: "string",
|
|
371
|
-
note: `"${col.column_name}" is an array of ${element}; arrays are stored as text[], integer[], boolean[] or numeric[] (anything else as jsonb), so a push would plan converting it.`
|
|
372
|
-
};
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
/**
|
|
377
|
-
* A column default as a `defaultValue`, when it is a literal a property can carry.
|
|
378
|
-
*
|
|
379
|
-
* `undefined` when there is no default to carry, or when the default is one the
|
|
380
|
-
* generator expresses another way (`now()` is `autoValue`, a key's default is
|
|
381
|
-
* its `isId`). `{ note }` when there is a default and no property can say it —
|
|
382
|
-
* a push would plan dropping it.
|
|
383
|
-
*/
|
|
384
|
-
function literalDefaultOf(col, propType) {
|
|
385
|
-
const raw = col.column_default?.trim();
|
|
386
|
-
if (!raw) return void 0;
|
|
387
|
-
if (/^(now\(\)|CURRENT_TIMESTAMP)$/i.test(raw)) return void 0;
|
|
388
|
-
const quoted = /^'((?:[^']|'')*)'(?:::[\w\s."[\]]+)?$/.exec(raw);
|
|
389
|
-
const unquoted = quoted ? quoted[1].replace(/''/g, "'") : void 0;
|
|
390
|
-
switch (propType) {
|
|
391
|
-
case "string":
|
|
392
|
-
if (unquoted !== void 0) return { source: literal(unquoted) };
|
|
393
|
-
break;
|
|
394
|
-
case "number": {
|
|
395
|
-
const text = unquoted ?? raw.replace(/^\((.*)\)$/, "$1").replace(/::[\w\s]+$/, "");
|
|
396
|
-
if (/^-?\d+(\.\d+)?$/.test(text) && Number.isFinite(Number(text))) return { source: String(Number(text)) };
|
|
397
|
-
break;
|
|
398
|
-
}
|
|
399
|
-
case "boolean":
|
|
400
|
-
if (/^true$/i.test(raw)) return { source: "true" };
|
|
401
|
-
if (/^false$/i.test(raw)) return { source: "false" };
|
|
402
|
-
break;
|
|
403
|
-
case "map":
|
|
404
|
-
if (unquoted !== void 0) try {
|
|
405
|
-
const parsed = JSON.parse(unquoted);
|
|
406
|
-
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return { source: JSON.stringify(parsed) };
|
|
407
|
-
} catch {}
|
|
408
|
-
break;
|
|
409
|
-
default: break;
|
|
410
|
-
}
|
|
411
|
-
return { note: `"${col.column_name}" defaults to ${raw}, which no \`defaultValue\` can express; a push would plan dropping that default.` };
|
|
412
|
-
}
|
|
413
|
-
/** `ON DELETE` as the relation's `onDelete`, when it is not the default the planner would choose. */
|
|
414
|
-
function onDeleteOf(fk, required) {
|
|
415
|
-
const rule = fk.delete_rule?.toUpperCase();
|
|
416
|
-
if (!rule) return void 0;
|
|
417
|
-
if (rule === (required ? "RESTRICT" : "SET NULL")) return void 0;
|
|
418
|
-
return rule.toLowerCase();
|
|
419
|
-
}
|
|
420
|
-
//#endregion
|
|
421
|
-
//#region src/schema/introspect-db-search.ts
|
|
422
|
-
/**
|
|
423
|
-
* A collection's `search` block, read back out of the column it built.
|
|
424
|
-
*
|
|
425
|
-
* A Rebase search column is `tsvector GENERATED ALWAYS AS (…) STORED`, stamped
|
|
426
|
-
* with a fingerprint of the expression in its `COMMENT`. Introspection used to
|
|
427
|
-
* emit it as an ordinary read-only string property, which the planner makes a
|
|
428
|
-
* `text` column — so the first push after adopting a Rebase database planned
|
|
429
|
-
* `ALTER COLUMN "search_vector" TYPE text … DROP EXPRESSION`, and search was
|
|
430
|
-
* gone for whoever approved it.
|
|
431
|
-
*
|
|
432
|
-
* Reading the block back is a guess checked by the stamp: the deparsed
|
|
433
|
-
* expression names each field's column, weight and language, which is enough
|
|
434
|
-
* to write a candidate block; the candidate is then compiled by the very code
|
|
435
|
-
* that built the column, and kept only if its fingerprint is the one the column
|
|
436
|
-
* carries. A block that does not reproduce the stamp is not emitted at all —
|
|
437
|
-
* the note says so — because a wrong one would rebuild the column differently.
|
|
438
|
-
*
|
|
439
|
-
* `mode` and `fuzzyThreshold` act at query time and are stored nowhere, so they
|
|
440
|
-
* come back as their defaults.
|
|
441
|
-
*/
|
|
442
|
-
/** One `setweight(to_tsvector('<lang>'::regconfig, <text>), '<W>'::"char")`, deparsed. */
|
|
443
|
-
var SEGMENT = /setweight\(to_tsvector\('((?:[^']|'')+)'::regconfig, ([\s\S]+?)\), '([A-D])'::"char"\)/g;
|
|
444
|
-
/** A property with the column's shape, for the candidate block to resolve against. */
|
|
445
|
-
function propertyFor(col) {
|
|
446
|
-
if (col.data_type === "text" || col.data_type === "character varying" || col.data_type === "character") return {
|
|
447
|
-
name: col.column_name,
|
|
448
|
-
type: "string",
|
|
449
|
-
columnName: col.column_name
|
|
450
|
-
};
|
|
451
|
-
if (col.udt_name === "_text") return {
|
|
452
|
-
name: col.column_name,
|
|
453
|
-
type: "array",
|
|
454
|
-
columnName: col.column_name,
|
|
455
|
-
of: {
|
|
456
|
-
name: col.column_name,
|
|
457
|
-
type: "string"
|
|
458
|
-
}
|
|
459
|
-
};
|
|
460
|
-
if (col.data_type === "jsonb") return {
|
|
461
|
-
name: col.column_name,
|
|
462
|
-
type: "map",
|
|
463
|
-
columnName: col.column_name,
|
|
464
|
-
keyValue: true
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
/**
|
|
468
|
-
* The search block a table's stamped generated columns were built from, or a
|
|
469
|
-
* note saying why it could not be read back.
|
|
470
|
-
*/
|
|
471
|
-
function reconstructSearchBlock(input) {
|
|
472
|
-
const stamped = input.columns.filter((col) => col.is_generated === "ALWAYS" && (input.comments.get(col.column_name) ?? "").startsWith("rebase:search:v1:"));
|
|
473
|
-
const main = stamped.find((col) => col.udt_name === "tsvector");
|
|
474
|
-
if (!main) return { columns: /* @__PURE__ */ new Set() };
|
|
475
|
-
const fuzzy = stamped.find((col) => col.column_name === `${main.column_name}_text`);
|
|
476
|
-
const columns = new Set(stamped.map((col) => col.column_name));
|
|
477
|
-
const unreadable = (why) => ({
|
|
478
|
-
columns,
|
|
479
|
-
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.`
|
|
480
|
-
});
|
|
481
|
-
const expression = main.generation_expression ?? "";
|
|
482
|
-
const byColumn = new Map(input.columns.map((col) => [col.column_name, col]));
|
|
483
|
-
const fields = [];
|
|
484
|
-
let language;
|
|
485
|
-
let unaccent = false;
|
|
486
|
-
for (const [, lang, inner, weight] of expression.matchAll(SEGMENT)) {
|
|
487
|
-
language ??= lang.replace(/''/g, "'");
|
|
488
|
-
if (lang.replace(/''/g, "'") !== language) return unreadable("its fields use different languages");
|
|
489
|
-
if (inner.includes("rebase_search_unaccent")) unaccent = true;
|
|
490
|
-
const column = [...inner.matchAll(/"?([A-Za-z_][A-Za-z0-9_$]*)"?/g)].map((m) => m[1]).find((name) => byColumn.has(name) && !columns.has(name));
|
|
491
|
-
if (!column) return unreadable("a field reads no column of this table");
|
|
492
|
-
const key = input.keyByColumn.get(column);
|
|
493
|
-
if (!key) return unreadable(`the column "${column}" is not a property`);
|
|
494
|
-
const jsonPath = [...inner.matchAll(/(?:->|#>)\s*'([^']+)'/g)].flatMap((m) => m[1].replace(/^\{|\}$/g, "").split(","));
|
|
495
|
-
fields.push({
|
|
496
|
-
path: [key, ...jsonPath].join("."),
|
|
497
|
-
weight
|
|
498
|
-
});
|
|
499
|
-
}
|
|
500
|
-
if (fields.length === 0 || !language) return unreadable("its expression is not one Rebase writes");
|
|
501
|
-
const search = {
|
|
502
|
-
...main.column_name !== DEFAULT_SEARCH_COLUMN ? { column: main.column_name } : {},
|
|
503
|
-
...language !== DEFAULT_SEARCH_LANGUAGE ? { language } : {},
|
|
504
|
-
...unaccent ? { unaccent: true } : {},
|
|
505
|
-
...fuzzy ? { fuzzy: true } : {},
|
|
506
|
-
fields: fields.map((f) => ({
|
|
507
|
-
path: f.path,
|
|
508
|
-
weight: f.weight
|
|
509
|
-
}))
|
|
510
|
-
};
|
|
511
|
-
const properties = {};
|
|
512
|
-
for (const [column, key] of input.keyByColumn) {
|
|
513
|
-
const col = byColumn.get(column);
|
|
514
|
-
const prop = col ? propertyFor(col) : void 0;
|
|
515
|
-
if (prop) properties[key] = prop;
|
|
516
|
-
}
|
|
517
|
-
const candidate = {
|
|
518
|
-
slug: input.table,
|
|
519
|
-
name: input.table,
|
|
520
|
-
table: input.table,
|
|
521
|
-
...input.schema !== "public" ? { schema: input.schema } : {},
|
|
522
|
-
properties,
|
|
523
|
-
search
|
|
524
|
-
};
|
|
525
|
-
let fingerprints;
|
|
526
|
-
try {
|
|
527
|
-
const spec = buildSearchColumnSpec(candidate);
|
|
528
|
-
if (!spec) return unreadable("no block compiles from it");
|
|
529
|
-
fingerprints = new Map(searchColumnStamps(spec).map((stamp) => [stamp.column, stamp.fingerprint]));
|
|
530
|
-
} catch (err) {
|
|
531
|
-
return unreadable(err instanceof Error ? err.message : String(err));
|
|
532
|
-
}
|
|
533
|
-
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");
|
|
534
|
-
return {
|
|
535
|
-
columns,
|
|
536
|
-
block: `\n search: {\n ${[
|
|
537
|
-
...search.column ? [`column: ${JSON.stringify(search.column)}`] : [],
|
|
538
|
-
...search.language ? [`language: ${JSON.stringify(search.language)}`] : [],
|
|
539
|
-
...search.unaccent ? ["unaccent: true"] : [],
|
|
540
|
-
...search.fuzzy ? ["fuzzy: true"] : [],
|
|
541
|
-
`fields: [\n${fields.map((f) => ` { path: ${JSON.stringify(f.path)}, weight: ${JSON.stringify(f.weight)} }`).join(",\n")}\n ]`
|
|
542
|
-
].join(",\n ")}\n },`
|
|
543
|
-
};
|
|
544
|
-
}
|
|
545
|
-
/**
|
|
546
|
-
* A timestamp the database maintains: a temporal column defaulting to the
|
|
547
|
-
* transaction clock.
|
|
548
|
-
*
|
|
549
|
-
* This is the structural stand-in for the `created_at`/`updated_at` name check.
|
|
550
|
-
* It is strictly better than the name: it catches `fecha_creacion` and
|
|
551
|
-
* `last_update` (pagila's spelling, which the name list misses), and it does not
|
|
552
|
-
* fire on a user-editable `created_at date` column that has no default and which
|
|
553
|
-
* the name check would wrongly make read-only.
|
|
554
|
-
*/
|
|
555
|
-
function isAutoTimestamp(column) {
|
|
556
|
-
if (mapPgType(column.data_type) !== "date") return false;
|
|
557
|
-
const columnDefault = (column.column_default ?? "").toLowerCase();
|
|
558
|
-
if (!columnDefault) return false;
|
|
559
|
-
return /\b(now\(\)|current_timestamp|current_date|current_time|localtimestamp|localtime|transaction_timestamp\(\)|statement_timestamp\(\)|clock_timestamp\(\))/.test(columnDefault);
|
|
560
|
-
}
|
|
561
|
-
/** A column Postgres computes; writing to it is an error. */
|
|
562
|
-
function isGeneratedColumn(column) {
|
|
563
|
-
return column.is_generated === "ALWAYS";
|
|
564
|
-
}
|
|
565
|
-
/**
|
|
566
|
-
* Types that exist to be searched or indexed, never to be typed into.
|
|
567
|
-
*
|
|
568
|
-
* A `tsvector` column is a derived search index — maintained by a trigger, a
|
|
569
|
-
* generated expression, or an application job — and its contents are lexeme
|
|
570
|
-
* positions, not text. Pagila's `film.fulltext` is one, and introspection used
|
|
571
|
-
* to emit it as an ordinary required string: a mandatory form field whose
|
|
572
|
-
* correct value no user can produce, on the sixth column of the list view.
|
|
573
|
-
*/
|
|
574
|
-
function isDerivedIndexColumn(column) {
|
|
575
|
-
return column.udt_name === "tsvector" || column.udt_name === "tsquery";
|
|
576
|
-
}
|
|
577
|
-
/** Anything the user cannot meaningfully edit, whatever the reason. */
|
|
578
|
-
function isReadOnlyColumn(column) {
|
|
579
|
-
return isGeneratedColumn(column) || isDerivedIndexColumn(column);
|
|
580
|
-
}
|
|
581
|
-
/**
|
|
582
|
-
* A string column with a declared maximum length.
|
|
583
|
-
*
|
|
584
|
-
* `varchar(50)` and `text` are the same type to an application but not to the
|
|
585
|
-
* author: choosing a bound is a statement that the value is short and
|
|
586
|
-
* label-like, which is what makes this usable for picking a display column.
|
|
587
|
-
*/
|
|
588
|
-
function isBoundedString(column) {
|
|
589
|
-
return mapPgType(column.data_type) === "string" && typeof column.character_maximum_length === "number" && column.character_maximum_length > 0;
|
|
590
|
-
}
|
|
591
|
-
/**
|
|
592
|
-
* A column carrying data rather than structure: not a key, not a foreign key,
|
|
593
|
-
* not a database-maintained timestamp, not computed.
|
|
594
|
-
*
|
|
595
|
-
* The count of these is what tells a pure join table from an association that
|
|
596
|
-
* carries its own attributes — `northwind.order_details` has the key shape of a
|
|
597
|
-
* junction and three payload columns, so it is not one.
|
|
598
|
-
*/
|
|
599
|
-
function isPayloadColumn(column, pks, fkColumns) {
|
|
600
|
-
if (pks.includes(column.column_name)) return false;
|
|
601
|
-
if (fkColumns.has(column.column_name)) return false;
|
|
602
|
-
if (isAutoTimestamp(column)) return false;
|
|
603
|
-
if (isGeneratedColumn(column)) return false;
|
|
604
|
-
return true;
|
|
605
|
-
}
|
|
606
|
-
/**
|
|
607
|
-
* Groups per-column foreign key rows back into constraints.
|
|
608
|
-
*
|
|
609
|
-
* Rows arrive one per referencing column. A composite key looks exactly like two
|
|
610
|
-
* separate keys until they are grouped by constraint name, and the difference
|
|
611
|
-
* matters: two single-column keys to two tables can be a junction, one
|
|
612
|
-
* two-column key never is.
|
|
613
|
-
*/
|
|
614
|
-
function groupForeignKeys(fks) {
|
|
615
|
-
const byName = /* @__PURE__ */ new Map();
|
|
616
|
-
for (const fk of fks) {
|
|
617
|
-
const key = `${fk.table_name}::${fk.constraint_name ?? `${fk.column_name}->${fk.foreign_table_name}`}`;
|
|
618
|
-
const existing = byName.get(key);
|
|
619
|
-
if (existing) {
|
|
620
|
-
existing.columns.push(fk.column_name);
|
|
621
|
-
existing.foreignColumns.push(fk.foreign_column_name);
|
|
622
|
-
continue;
|
|
623
|
-
}
|
|
624
|
-
byName.set(key, {
|
|
625
|
-
name: fk.constraint_name ?? `${fk.table_name}_${fk.column_name}_fkey`,
|
|
626
|
-
table: fk.table_name,
|
|
627
|
-
columns: [fk.column_name],
|
|
628
|
-
foreignTable: fk.foreign_table_name,
|
|
629
|
-
foreignColumns: [fk.foreign_column_name],
|
|
630
|
-
deleteRule: fk.delete_rule
|
|
631
|
-
});
|
|
632
|
-
}
|
|
633
|
-
return Array.from(byName.values());
|
|
634
|
-
}
|
|
635
|
-
/** Column sets that are unique in a table: its primary key and every unique index. */
|
|
636
|
-
function uniqueColumnSets(table, pks, uniques) {
|
|
637
|
-
const sets = [];
|
|
638
|
-
if (pks.length > 0) sets.push(pks);
|
|
639
|
-
for (const unique of uniques) if (unique.table_name === table) sets.push(unique.column_names);
|
|
640
|
-
return sets;
|
|
641
|
-
}
|
|
642
|
-
function sameColumnSet(a, b) {
|
|
643
|
-
if (a.length !== b.length) return false;
|
|
644
|
-
const left = [...a].sort();
|
|
645
|
-
const right = [...b].sort();
|
|
646
|
-
return left.every((value, index) => value === right[index]);
|
|
647
|
-
}
|
|
648
|
-
function buildContext(metadata, tables) {
|
|
649
|
-
const allConstraints = groupForeignKeys(metadata.fks);
|
|
650
|
-
const constraintsByTable = /* @__PURE__ */ new Map();
|
|
651
|
-
const inboundByTable = /* @__PURE__ */ new Map();
|
|
652
|
-
for (const constraint of allConstraints) {
|
|
653
|
-
const outbound = constraintsByTable.get(constraint.table) ?? [];
|
|
654
|
-
outbound.push(constraint);
|
|
655
|
-
constraintsByTable.set(constraint.table, outbound);
|
|
656
|
-
const inbound = inboundByTable.get(constraint.foreignTable) ?? [];
|
|
657
|
-
inbound.push(constraint);
|
|
658
|
-
inboundByTable.set(constraint.foreignTable, inbound);
|
|
659
|
-
}
|
|
660
|
-
return {
|
|
661
|
-
schema: metadata.schema,
|
|
662
|
-
tables,
|
|
663
|
-
constraintsByTable,
|
|
664
|
-
inboundByTable,
|
|
665
|
-
uniques: metadata.uniques,
|
|
666
|
-
rowCounts: metadata.rowCounts
|
|
667
|
-
};
|
|
668
|
-
}
|
|
669
|
-
/**
|
|
670
|
-
* A table that exists only to relate two others.
|
|
671
|
-
*
|
|
672
|
-
* Requires all of:
|
|
673
|
-
* - exactly two single-column foreign keys, to two distinct columns;
|
|
674
|
-
* - that pair is unique — it is the primary key, or a unique index covers it.
|
|
675
|
-
* Without this the table can hold the same pair twice, which is a list of
|
|
676
|
-
* events between two things, not a set membership;
|
|
677
|
-
* - no payload columns. A join row that carries a quantity is an association
|
|
678
|
-
* with attributes, and collapsing it into a many-to-many silently drops those
|
|
679
|
-
* attributes from the UI entirely;
|
|
680
|
-
* - nothing references it. A junction with its own dependents is something rows
|
|
681
|
-
* point *at*, so it needs an identity of its own;
|
|
682
|
-
* - it is in `public`. That is the only schema Rebase reads and creates
|
|
683
|
-
* junction tables in (`resolveJunctionSpecs`), so a `manyToMany` folded from
|
|
684
|
-
* `crm.contacts_tags` would read and write an empty `public.contacts_tags`
|
|
685
|
-
* instead. Kept as a table, its rows stay where they are and are served.
|
|
686
|
-
*/
|
|
687
|
-
function classifyJunction(table, context) {
|
|
688
|
-
if (context.schema !== "public") return null;
|
|
689
|
-
const meta = context.tables.get(table);
|
|
690
|
-
if (!meta) return null;
|
|
691
|
-
const constraints = context.constraintsByTable.get(table) ?? [];
|
|
692
|
-
if (constraints.length !== 2) return null;
|
|
693
|
-
if (constraints.some((c) => c.columns.length !== 1)) return null;
|
|
694
|
-
const [first, second] = constraints;
|
|
695
|
-
if (first.columns[0] === second.columns[0]) return null;
|
|
696
|
-
if ((context.inboundByTable.get(table) ?? []).length > 0) return null;
|
|
697
|
-
const pair = [first.columns[0], second.columns[0]];
|
|
698
|
-
if (!uniqueColumnSets(table, meta.pks, context.uniques).some((set) => sameColumnSet(set, pair))) return null;
|
|
699
|
-
const fkColumns = new Set(pair);
|
|
700
|
-
if (meta.columns.filter((column) => isPayloadColumn(column, meta.pks, fkColumns)).length > 0) return null;
|
|
701
|
-
return {
|
|
702
|
-
table,
|
|
703
|
-
role: "junction",
|
|
704
|
-
reason: `only relates ${first.foreignTable} to ${second.foreignTable}: two foreign keys, unique together, no other data`,
|
|
705
|
-
junction: {
|
|
706
|
-
sourceTable: first.foreignTable,
|
|
707
|
-
sourceColumn: first.columns[0],
|
|
708
|
-
targetTable: second.foreignTable,
|
|
709
|
-
targetColumn: second.columns[0]
|
|
710
|
-
}
|
|
711
|
-
};
|
|
712
|
-
}
|
|
713
|
-
/**
|
|
714
|
-
* A policy expression that reads who is asking: the `app.uid` setting every
|
|
715
|
-
* request runs with, `rebase.uid()` (or the retired `auth.uid()`), the JWT,
|
|
716
|
-
* or the session's own role.
|
|
717
|
-
*/
|
|
718
|
-
var CALLER_IDENTITY = /current_setting\(\s*'app\.(uid|user_id|jwt)'|\b(rebase|auth)\.(uid|jwt)\s*\(|\bcurrent_user\b|\bsession_user\b/i;
|
|
719
|
-
/**
|
|
720
|
-
* The tables whose row-level security hands each caller rows of their own,
|
|
721
|
-
* with the policies that do it.
|
|
722
|
-
*
|
|
723
|
-
* Structure in the sense this module means: a policy is a rule the database
|
|
724
|
-
* enforces, and one that compares a row to the caller's identity says the rows
|
|
725
|
-
* belong to users. That is the app's data. A young database holds three
|
|
726
|
-
* customers and one order; by row count the customers are "a 3-row code list"
|
|
727
|
-
* and the orders a child reached only through them, and both go missing from
|
|
728
|
-
* the navigation of the app that owns them.
|
|
729
|
-
*/
|
|
730
|
-
function callerScopedTables(metadata) {
|
|
731
|
-
const scoped = /* @__PURE__ */ new Map();
|
|
732
|
-
for (const policy of metadata.policies ?? []) {
|
|
733
|
-
if (!CALLER_IDENTITY.test(policy.qual ?? "") && !CALLER_IDENTITY.test(policy.with_check ?? "")) continue;
|
|
734
|
-
scoped.set(policy.table_name, [...scoped.get(policy.table_name) ?? [], policy.policy_name]);
|
|
735
|
-
}
|
|
736
|
-
return scoped;
|
|
737
|
-
}
|
|
738
|
-
/** An entity because its policies give each user their own rows — see {@link callerScopedTables}. */
|
|
739
|
-
function classifyCallerScoped(table, perCaller) {
|
|
740
|
-
const policies = perCaller.get(table);
|
|
741
|
-
if (!policies) return null;
|
|
742
|
-
return {
|
|
743
|
-
table,
|
|
744
|
-
role: "entity",
|
|
745
|
-
reason: `its row-level security gives each user their own rows (${policies.join(", ")}), so they are the app's data`
|
|
746
|
-
};
|
|
747
|
-
}
|
|
748
|
-
/**
|
|
749
|
-
* A small, referenced, self-contained code list.
|
|
750
|
-
*
|
|
751
|
-
* Requires: something references it, it references nothing, it carries few and
|
|
752
|
-
* simple payload columns, and it is small — where "small" is a real count, not
|
|
753
|
-
* an estimate. `reltuples` is -1 on any table that has never been analyzed,
|
|
754
|
-
* which is every table in a freshly restored dump, so a count that is merely
|
|
755
|
-
* absent must not read as "small".
|
|
756
|
-
*/
|
|
757
|
-
function classifyLookup(table, context) {
|
|
758
|
-
if (!isLookupCandidate(table, context)) return null;
|
|
759
|
-
const rowCount = context.rowCounts[table];
|
|
760
|
-
if (typeof rowCount !== "number") return null;
|
|
761
|
-
if (rowCount < 1 || rowCount > 50) return null;
|
|
762
|
-
return {
|
|
763
|
-
table,
|
|
764
|
-
role: "lookup",
|
|
765
|
-
reason: `a ${rowCount}-row code list: referenced by ${(context.inboundByTable.get(table) ?? []).length} table(s), references none, 3 or fewer simple columns`
|
|
766
|
-
};
|
|
767
|
-
}
|
|
768
|
-
/**
|
|
769
|
-
* The structural half of the lookup test — everything except the row count.
|
|
770
|
-
*
|
|
771
|
-
* Separate because the count costs a query per table, and the caller only wants
|
|
772
|
-
* to pay it for tables that could possibly qualify.
|
|
773
|
-
*/
|
|
774
|
-
function isLookupCandidate(table, context) {
|
|
775
|
-
const meta = context.tables.get(table);
|
|
776
|
-
if (!meta) return false;
|
|
777
|
-
if ((context.constraintsByTable.get(table) ?? []).length > 0) return false;
|
|
778
|
-
if ((context.inboundByTable.get(table) ?? []).length === 0) return false;
|
|
779
|
-
const payload = meta.columns.filter((column) => isPayloadColumn(column, meta.pks, /* @__PURE__ */ new Set()));
|
|
780
|
-
if (payload.length > 3) return false;
|
|
781
|
-
return payload.every((column) => {
|
|
782
|
-
const type = mapPgType(column.data_type);
|
|
783
|
-
return type === "boolean" || type === "number" || type === "string";
|
|
784
|
-
});
|
|
785
|
-
}
|
|
786
|
-
/**
|
|
787
|
-
* Names the tables whose classification depends on a row count.
|
|
788
|
-
*
|
|
789
|
-
* The caller counts these — and only these — before calling
|
|
790
|
-
* {@link classifyTables}. On a schema of any size this is a handful of tables,
|
|
791
|
-
* and the count itself is capped (see `countRowsUpTo`), so the whole extra cost
|
|
792
|
-
* is bounded regardless of how much data the database holds.
|
|
793
|
-
*/
|
|
794
|
-
function lookupCandidates(metadata, tables) {
|
|
795
|
-
const context = buildContext(metadata, tables);
|
|
796
|
-
return Array.from(tables.keys()).filter((table) => isLookupCandidate(table, context));
|
|
797
|
-
}
|
|
798
|
-
/**
|
|
799
|
-
* Rows that belong to one parent row and are reached through it.
|
|
800
|
-
*
|
|
801
|
-
* Requires nothing to reference the table — a table others point at has an
|
|
802
|
-
* identity of its own and belongs in the navigation — and an *unambiguous*
|
|
803
|
-
* owner among its foreign keys. The evidence ladder runs strongest first; each
|
|
804
|
-
* rung is only taken when exactly one key satisfies it, so a table with two
|
|
805
|
-
* equally plausible parents stays an entity rather than being filed under a
|
|
806
|
-
* coin-flip.
|
|
807
|
-
*/
|
|
808
|
-
function classifyOwnedChild(table, context) {
|
|
809
|
-
const meta = context.tables.get(table);
|
|
810
|
-
if (!meta) return null;
|
|
811
|
-
const constraints = context.constraintsByTable.get(table) ?? [];
|
|
812
|
-
if (constraints.length === 0) return null;
|
|
813
|
-
if ((context.inboundByTable.get(table) ?? []).length > 0) return null;
|
|
814
|
-
const owner = pickOwner(meta, constraints);
|
|
815
|
-
if (!owner) return null;
|
|
816
|
-
return {
|
|
817
|
-
table,
|
|
818
|
-
role: "owned-child",
|
|
819
|
-
reason: `belongs to ${owner.constraint.foreignTable} (${describeEvidence(owner.evidence)}) and nothing else references it`,
|
|
820
|
-
owner: {
|
|
821
|
-
table: owner.constraint.foreignTable,
|
|
822
|
-
column: owner.constraint.columns[0],
|
|
823
|
-
evidence: owner.evidence
|
|
824
|
-
}
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
function describeEvidence(evidence) {
|
|
828
|
-
switch (evidence) {
|
|
829
|
-
case "cascade-delete": return "its only ON DELETE CASCADE foreign key";
|
|
830
|
-
case "identifying-key": return "its only foreign key inside the primary key";
|
|
831
|
-
case "sole-required-key": return "its only NOT NULL foreign key";
|
|
832
|
-
case "leading-key-column": return "the leading column of a primary key made only of foreign keys";
|
|
833
|
-
}
|
|
834
|
-
}
|
|
835
|
-
function pickOwner(meta, constraints) {
|
|
836
|
-
const singleColumn = constraints.filter((c) => c.columns.length === 1);
|
|
837
|
-
if (singleColumn.length === 0) return null;
|
|
838
|
-
const nullability = new Map(meta.columns.map((c) => [c.column_name, c.is_nullable === "NO"]));
|
|
839
|
-
const cascading = singleColumn.filter((c) => c.deleteRule === "CASCADE");
|
|
840
|
-
if (cascading.length === 1) return {
|
|
841
|
-
constraint: cascading[0],
|
|
842
|
-
evidence: "cascade-delete"
|
|
843
|
-
};
|
|
844
|
-
const identifying = singleColumn.filter((c) => meta.pks.includes(c.columns[0]));
|
|
845
|
-
if (identifying.length === 1) return {
|
|
846
|
-
constraint: identifying[0],
|
|
847
|
-
evidence: "identifying-key"
|
|
848
|
-
};
|
|
849
|
-
const required = singleColumn.filter((c) => nullability.get(c.columns[0]) === true);
|
|
850
|
-
if (required.length === 1) return {
|
|
851
|
-
constraint: required[0],
|
|
852
|
-
evidence: "sole-required-key"
|
|
853
|
-
};
|
|
854
|
-
if (identifying.length === meta.pks.length && meta.pks.length > 1) {
|
|
855
|
-
const leading = identifying.find((c) => c.columns[0] === meta.pks[0]);
|
|
856
|
-
if (leading) return {
|
|
857
|
-
constraint: leading,
|
|
858
|
-
evidence: "leading-key-column"
|
|
859
|
-
};
|
|
860
|
-
}
|
|
861
|
-
return null;
|
|
862
|
-
}
|
|
863
|
-
/**
|
|
864
|
-
* Classifies every table in the schema.
|
|
865
|
-
*
|
|
866
|
-
* Order matters: junction is the most specific and most consequential (the
|
|
867
|
-
* table disappears), so it is tested first; then lookup, which needs no
|
|
868
|
-
* ownership reasoning; then ownership. Anything unmatched is an entity, which
|
|
869
|
-
* is also what every rule falls back to when its evidence is ambiguous.
|
|
870
|
-
*/
|
|
871
|
-
function classifyTables(metadata, tables) {
|
|
872
|
-
const context = buildContext(metadata, tables);
|
|
873
|
-
const result = /* @__PURE__ */ new Map();
|
|
874
|
-
const perCaller = callerScopedTables(metadata);
|
|
875
|
-
for (const table of tables.keys()) {
|
|
876
|
-
const classification = classifyJunction(table, context) ?? classifyCallerScoped(table, perCaller) ?? classifyLookup(table, context) ?? classifyOwnedChild(table, context) ?? {
|
|
877
|
-
table,
|
|
878
|
-
role: "entity",
|
|
879
|
-
reason: "no structural evidence that it is a join table, a code list, or owned by another table"
|
|
880
|
-
};
|
|
881
|
-
result.set(table, classification);
|
|
882
|
-
}
|
|
883
|
-
return result;
|
|
884
|
-
}
|
|
885
|
-
function buildColumnFacts(meta, metadata, enumMap, checkFacts) {
|
|
886
|
-
const fkColumns = new Set(meta.fks.map((fk) => fk.column_name));
|
|
887
|
-
const singleColumnUniques = new Set(metadata.uniques.filter((u) => u.table_name === meta.name && u.column_names.length === 1).map((u) => u.column_names[0]));
|
|
888
|
-
const tableChecks = checkFacts.get(meta.name);
|
|
889
|
-
const facts = /* @__PURE__ */ new Map();
|
|
890
|
-
for (const column of meta.columns) {
|
|
891
|
-
const pgEnum = column.data_type === "USER-DEFINED" ? enumMap.get(column.udt_name) : void 0;
|
|
892
|
-
const checkEnum = tableChecks?.get(column.column_name)?.enumValues;
|
|
893
|
-
facts.set(column.column_name, {
|
|
894
|
-
column,
|
|
895
|
-
isPk: meta.pks.includes(column.column_name),
|
|
896
|
-
isFk: fkColumns.has(column.column_name),
|
|
897
|
-
isUniqueAlone: singleColumnUniques.has(column.column_name),
|
|
898
|
-
isAutoTimestamp: isAutoTimestamp(column),
|
|
899
|
-
isGenerated: isGeneratedColumn(column),
|
|
900
|
-
enumValues: pgEnum ?? checkEnum,
|
|
901
|
-
propType: pgEnum ? "string" : mapPgType(column.data_type)
|
|
902
|
-
});
|
|
903
|
-
}
|
|
904
|
-
return facts;
|
|
905
|
-
}
|
|
906
|
-
/**
|
|
907
|
-
* The column that identifies a row to a human.
|
|
908
|
-
*
|
|
909
|
-
* Structural, in three rungs, strongest first:
|
|
910
|
-
*
|
|
911
|
-
* 1. A single-column unique constraint on a required string. This is as close
|
|
912
|
-
* as a schema comes to declaring "this is what a row is called": it is the
|
|
913
|
-
* column a person looks a row up by, and the database guarantees it picks
|
|
914
|
-
* out one row.
|
|
915
|
-
* 2. The first required string that declares a length, when the table also has
|
|
916
|
-
* strings that do not. Choosing `varchar(n)` for one column and `text` for
|
|
917
|
-
* another is the author distinguishing a label from prose.
|
|
918
|
-
* 3. The first required string in declaration order. Weak, but it is the same
|
|
919
|
-
* rung the panel's own fallback stands on, and column order carries real
|
|
920
|
-
* information — the identifying column of a table is written near the top of
|
|
921
|
-
* it, in every schema, in every language.
|
|
922
|
-
*
|
|
923
|
-
* Deliberately not: a column called `name`, or `title`. That works on English
|
|
924
|
-
* schemas written by someone who read the same tutorial. This picks
|
|
925
|
-
* `film.title`, `actor.first_name` and `category.name` out of pagila without
|
|
926
|
-
* knowing what any of those words mean.
|
|
927
|
-
*/
|
|
928
|
-
function deriveTitleProperty(facts) {
|
|
929
|
-
const candidates = Array.from(facts.values()).filter((f) => !f.isPk && !f.isFk && !f.isGenerated && f.propType === "string" && !f.enumValues && f.column.is_nullable === "NO");
|
|
930
|
-
if (candidates.length === 0) return void 0;
|
|
931
|
-
const unique = candidates.find((f) => f.isUniqueAlone);
|
|
932
|
-
if (unique) return unique.column.column_name;
|
|
933
|
-
const bounded = candidates.filter((f) => isBoundedString(f.column));
|
|
934
|
-
if (bounded.length > 0 && bounded.length < candidates.length) return bounded[0].column.column_name;
|
|
935
|
-
return candidates[0].column.column_name;
|
|
936
|
-
}
|
|
937
|
-
/**
|
|
938
|
-
* The enum column a board should have as its columns.
|
|
939
|
-
*
|
|
940
|
-
* A board needs a small, closed, always-present set of states. `NOT NULL` is
|
|
941
|
-
* required because a null has no column to sit in; the bounds keep out
|
|
942
|
-
* two-state flags (a filter, not a board) and long code lists (a scrolling
|
|
943
|
-
* table). The first qualifying column in declaration order wins, so the output
|
|
944
|
-
* is stable across runs.
|
|
945
|
-
*/
|
|
946
|
-
function deriveKanbanProperty(facts) {
|
|
947
|
-
for (const fact of facts.values()) {
|
|
948
|
-
if (fact.isPk || fact.isFk || fact.isGenerated) continue;
|
|
949
|
-
if (!fact.enumValues) continue;
|
|
950
|
-
if (fact.column.is_nullable !== "NO") continue;
|
|
951
|
-
if (fact.enumValues.length < 2 || fact.enumValues.length > 12) continue;
|
|
952
|
-
return fact.column.column_name;
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
/** Names a string column goes by when it holds a board's card order (a fractional-indexing key). */
|
|
956
|
-
var ORDER_KEY_NAMES = /* @__PURE__ */ new Set([
|
|
957
|
-
"__order",
|
|
958
|
-
"order_key",
|
|
959
|
-
"sort_key",
|
|
960
|
-
"rank",
|
|
961
|
-
"lexorank",
|
|
962
|
-
"position_key"
|
|
963
|
-
]);
|
|
964
|
-
/**
|
|
965
|
-
* The string column that can hold a board's card order, or nothing.
|
|
966
|
-
*
|
|
967
|
-
* A board without `orderProperty` cannot keep a card's position within a
|
|
968
|
-
* column, and the config validator says so on every generate — so a board is
|
|
969
|
-
* emitted only when the table already has somewhere to store the order. A
|
|
970
|
-
* legacy table almost never does; asking its owner to add a hidden column
|
|
971
|
-
* just to satisfy generated output was the wrong way round.
|
|
972
|
-
*/
|
|
973
|
-
function deriveKanbanOrderProperty(facts) {
|
|
974
|
-
for (const fact of facts.values()) {
|
|
975
|
-
if (fact.isPk || fact.isFk || fact.isGenerated || fact.enumValues) continue;
|
|
976
|
-
if (fact.propType !== "string") continue;
|
|
977
|
-
if (!/^(text|character varying)$/.test(fact.column.data_type)) continue;
|
|
978
|
-
if (ORDER_KEY_NAMES.has(fact.column.column_name.toLowerCase())) return fact.column.column_name;
|
|
979
|
-
}
|
|
980
|
-
}
|
|
981
|
-
/**
|
|
982
|
-
* The column a list should be sorted by, newest first.
|
|
983
|
-
*
|
|
984
|
-
* Only when the table has exactly one database-maintained timestamp. With two —
|
|
985
|
-
* a created and an updated stamp — the two orderings differ and the schema does
|
|
986
|
-
* not say which the user means, so neither is chosen.
|
|
987
|
-
*/
|
|
988
|
-
function deriveSort(facts) {
|
|
989
|
-
const stamps = Array.from(facts.values()).filter((f) => f.isAutoTimestamp);
|
|
990
|
-
if (stamps.length !== 1) return void 0;
|
|
991
|
-
return [stamps[0].column.column_name, "desc"];
|
|
992
|
-
}
|
|
993
|
-
/**
|
|
994
|
-
* The first `LIST_PROPERTIES_CAP` visible properties, or nothing.
|
|
995
|
-
*
|
|
996
|
-
* Returning nothing when the table is already narrow matters: `listProperties`
|
|
997
|
-
* that restates every column is config the reader has to check against the
|
|
998
|
-
* property list to discover it does nothing, and it silently stops new columns
|
|
999
|
-
* from appearing in the list view when someone adds one later.
|
|
1000
|
-
*
|
|
1001
|
-
* `hidden` names the properties already marked `hideFromCollection` — spending
|
|
1002
|
-
* one of six columns on a value the list does not render is worse than not
|
|
1003
|
-
* capping at all.
|
|
1004
|
-
*/
|
|
1005
|
-
function deriveListProperties(propertiesOrder, hidden = /* @__PURE__ */ new Set()) {
|
|
1006
|
-
const visible = propertiesOrder.filter((key) => !hidden.has(key));
|
|
1007
|
-
if (visible.length <= 6) return void 0;
|
|
1008
|
-
return visible.slice(0, 6);
|
|
1009
|
-
}
|
|
1010
|
-
//#endregion
|
|
1011
|
-
//#region src/schema/introspect-db-logic.ts
|
|
1012
|
-
/**
|
|
1013
|
-
* Introspection logic — pure functions and the pipeline that transforms
|
|
1014
|
-
* raw PostgreSQL metadata into Rebase collection definition files.
|
|
1015
|
-
*
|
|
1016
|
-
* This module contains NO side-effects: no fs writes, no pg.Client creation,
|
|
1017
|
-
* no process.exit. It is imported by introspect-db.ts (the CLI entry-point)
|
|
1018
|
-
* and consumed directly by tests.
|
|
1019
|
-
*/
|
|
1020
|
-
/**
|
|
1021
|
-
* Why a table keyed on several columns is not generated as a collection, or
|
|
1022
|
-
* `undefined` when it is.
|
|
1023
|
-
*
|
|
1024
|
-
* Several `isId` properties are one composite key, and the planner builds that
|
|
1025
|
-
* table under the same `PRIMARY KEY (a, b)` — so such a table round-trips when
|
|
1026
|
-
* two things hold:
|
|
1027
|
-
*
|
|
1028
|
-
* - **Every key column can carry `isId`,** which exists on string and number
|
|
1029
|
-
* properties, and on a date property over a `date` column (a calendar day).
|
|
1030
|
-
* Read from the column's SQL type, not a data sample: a
|
|
1031
|
-
* `line_no` holding only 1s is not a boolean. A key with a column of another
|
|
1032
|
-
* type — pagila's `payment` is keyed on a timestamp too — can be marked on
|
|
1033
|
-
* some of its columns only, and those would be read as the whole key.
|
|
1034
|
-
* - **Nothing points at it.** A foreign key into it, or a junction, is a link
|
|
1035
|
-
* into a composite key, which the planner refuses: the relation has one
|
|
1036
|
-
* column to point with.
|
|
1037
|
-
*/
|
|
1038
|
-
function compositeKeySkipReason(meta, allFks) {
|
|
1039
|
-
if (meta.pks.length < 2) return void 0;
|
|
1040
|
-
const unmarkable = meta.pks.filter((pk) => {
|
|
1041
|
-
const column = meta.columns.find((c) => c.column_name === pk);
|
|
1042
|
-
const type = column ? mapPgType(column.data_type) : void 0;
|
|
1043
|
-
return type !== "string" && type !== "number" && !(type === "date" && column?.data_type.toLowerCase() === "date");
|
|
1044
|
-
});
|
|
1045
|
-
if (unmarkable.length > 0) return `its key column${unmarkable.length > 1 ? "s" : ""} ${unmarkable.map((c) => `"${c}"`).join(", ")} cannot carry \`isId\`, which a string or number property takes, or a date property on a \`date\` column`;
|
|
1046
|
-
const referencing = [...new Set(allFks.filter((fk) => fk.foreign_table_name === meta.name && fk.table_name !== meta.name).map((fk) => fk.table_name))];
|
|
1047
|
-
if (referencing.length > 0) return `${referencing.map((t) => `"${t}"`).join(", ")} point${referencing.length > 1 ? "" : "s"} at it, and a link cannot point at a composite key`;
|
|
1048
|
-
}
|
|
1049
|
-
var IRREGULAR_SINGULARS = {
|
|
1050
|
-
people: "person",
|
|
1051
|
-
children: "child",
|
|
1052
|
-
men: "man",
|
|
1053
|
-
women: "woman",
|
|
1054
|
-
mice: "mouse",
|
|
1055
|
-
geese: "goose",
|
|
1056
|
-
teeth: "tooth",
|
|
1057
|
-
feet: "foot",
|
|
1058
|
-
data: "datum",
|
|
1059
|
-
media: "medium",
|
|
1060
|
-
criteria: "criterion",
|
|
1061
|
-
phenomena: "phenomenon"
|
|
1062
|
-
};
|
|
1063
|
-
/**
|
|
1064
|
-
* Plurals in "-ves" whose singular really ends in f/fe, and which of the two.
|
|
1065
|
-
*
|
|
1066
|
-
* A blanket "-ves" -> "-f" rule gets `knives` -> `knif`, and mangles every
|
|
1067
|
-
* ordinary "-ive" noun that happens to be plural along with it: `archives` ->
|
|
1068
|
-
* `archif`, `objectives` -> `objectif`. The set of English words that genuinely
|
|
1069
|
-
* swap f/fe for ves is small and closed, so it is listed rather than guessed —
|
|
1070
|
-
* anything else ending in "ves" drops the trailing 's' like any other plural.
|
|
1071
|
-
*
|
|
1072
|
-
* Matched on the whole word, not on the suffix: `olives` ends in `lives`.
|
|
1073
|
-
*/
|
|
1074
|
-
var VES_SINGULAR_ENDINGS = {
|
|
1075
|
-
calves: "f",
|
|
1076
|
-
dwarves: "f",
|
|
1077
|
-
elves: "f",
|
|
1078
|
-
halves: "f",
|
|
1079
|
-
hooves: "f",
|
|
1080
|
-
leaves: "f",
|
|
1081
|
-
loaves: "f",
|
|
1082
|
-
scarves: "f",
|
|
1083
|
-
selves: "f",
|
|
1084
|
-
sheaves: "f",
|
|
1085
|
-
shelves: "f",
|
|
1086
|
-
thieves: "f",
|
|
1087
|
-
wharves: "f",
|
|
1088
|
-
wolves: "f",
|
|
1089
|
-
knives: "fe",
|
|
1090
|
-
lives: "fe",
|
|
1091
|
-
wives: "fe"
|
|
1092
|
-
};
|
|
1093
|
-
/** Words ending in 's' that are already singular. */
|
|
1094
|
-
var UNCOUNTABLE = /* @__PURE__ */ new Set([
|
|
1095
|
-
"status",
|
|
1096
|
-
"campus",
|
|
1097
|
-
"virus",
|
|
1098
|
-
"bus",
|
|
1099
|
-
"plus",
|
|
1100
|
-
"census",
|
|
1101
|
-
"diagnosis",
|
|
1102
|
-
"analysis",
|
|
1103
|
-
"basis",
|
|
1104
|
-
"crisis",
|
|
1105
|
-
"thesis",
|
|
1106
|
-
"synopsis",
|
|
1107
|
-
"parenthesis",
|
|
1108
|
-
"hypothesis",
|
|
1109
|
-
"emphasis",
|
|
1110
|
-
"news",
|
|
1111
|
-
"series",
|
|
1112
|
-
"species",
|
|
1113
|
-
"means",
|
|
1114
|
-
"athletics",
|
|
1115
|
-
"economics",
|
|
1116
|
-
"electronics",
|
|
1117
|
-
"mathematics",
|
|
1118
|
-
"physics",
|
|
1119
|
-
"politics",
|
|
1120
|
-
"statistics"
|
|
1121
|
-
]);
|
|
1122
|
-
function singularize(word) {
|
|
1123
|
-
const lower = word.toLowerCase();
|
|
1124
|
-
if (IRREGULAR_SINGULARS[lower]) {
|
|
1125
|
-
const singular = IRREGULAR_SINGULARS[lower];
|
|
1126
|
-
return word[0] === word[0].toUpperCase() ? singular.charAt(0).toUpperCase() + singular.slice(1) : singular;
|
|
1127
|
-
}
|
|
1128
|
-
if (UNCOUNTABLE.has(lower)) return word;
|
|
1129
|
-
if (lower.endsWith("ices") && lower.length > 5) return word.slice(0, -4) + "ex";
|
|
1130
|
-
if (lower.endsWith("ies") && lower.length > 3) return word.slice(0, -3) + "y";
|
|
1131
|
-
if (VES_SINGULAR_ENDINGS[lower]) return word.slice(0, -3) + VES_SINGULAR_ENDINGS[lower];
|
|
1132
|
-
if (lower.endsWith("ches") || lower.endsWith("shes") || lower.endsWith("sses") || lower.endsWith("xes") || lower.endsWith("zes")) return word.slice(0, -2);
|
|
1133
|
-
if (lower.endsWith("ses") && !lower.endsWith("sses")) return word.slice(0, -1);
|
|
1134
|
-
if (lower.endsWith("s") && !lower.endsWith("ss") && !lower.endsWith("us") && !lower.endsWith("is")) return word.slice(0, -1);
|
|
1135
|
-
return word;
|
|
1136
|
-
}
|
|
1137
|
-
/**
|
|
1138
|
-
* Convert a snake_case table name to a camelCase + "Collection" variable name.
|
|
1139
|
-
* e.g. "company_token" -> "companyTokenCollection"
|
|
1140
|
-
*/
|
|
1141
|
-
function toCollectionVarName(tableName) {
|
|
1142
|
-
const camel = tableName.replace(/_([a-z])/g, (_g, letter) => letter.toUpperCase()) + "Collection";
|
|
1143
|
-
if (JS_IDENTIFIER.test(camel)) return camel;
|
|
1144
|
-
const sanitized = camel.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
1145
|
-
return /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
|
|
1146
|
-
}
|
|
1147
|
-
function getIconForTable(tableName) {
|
|
1148
|
-
const table = tableName.toLowerCase();
|
|
1149
|
-
if (table.includes("user") || table.includes("account") || table.includes("member") || table.includes("customer") || table.includes("client") || table.includes("patient")) return "Users";
|
|
1150
|
-
if (table.includes("post") || table.includes("article") || table.includes("blog") || table.includes("page")) return "FileText";
|
|
1151
|
-
if (table.includes("product") || table.includes("item")) return "Package";
|
|
1152
|
-
if (table.includes("order") || table.includes("cart") || table.includes("purchase") || table.includes("invoice")) return "ShoppingCart";
|
|
1153
|
-
if (table.includes("setting") || table.includes("config")) return "Settings";
|
|
1154
|
-
if (table.includes("tag") || table.includes("categor")) return "Tag";
|
|
1155
|
-
if (table.includes("image") || table.includes("photo") || table.includes("media") || table.includes("asset")) return "Image";
|
|
1156
|
-
if (table.includes("notification") || table.includes("message") || table.includes("email")) return "Mail";
|
|
1157
|
-
if (table.includes("log") || table.includes("audit") || table.includes("event")) return "Activity";
|
|
1158
|
-
if (table.includes("subscription") || table.includes("plan") || table.includes("billing")) return "CreditCard";
|
|
1159
|
-
if (table.includes("comment") || table.includes("review") || table.includes("feedback")) return "MessageCircle";
|
|
1160
|
-
return "Database";
|
|
1161
|
-
}
|
|
1162
|
-
function buildEnumMap(enumValues) {
|
|
1163
|
-
const enumMap = /* @__PURE__ */ new Map();
|
|
1164
|
-
for (const ev of enumValues) {
|
|
1165
|
-
const existing = enumMap.get(ev.enum_name);
|
|
1166
|
-
if (existing) existing.push(ev.enum_value);
|
|
1167
|
-
else enumMap.set(ev.enum_name, [ev.enum_value]);
|
|
1168
|
-
}
|
|
1169
|
-
return enumMap;
|
|
1170
|
-
}
|
|
1171
|
-
function buildTablesMap(tables, columns, pks, fks) {
|
|
1172
|
-
const tablesMap = /* @__PURE__ */ new Map();
|
|
1173
|
-
for (const t of tables) tablesMap.set(t.table_name, {
|
|
1174
|
-
name: t.table_name,
|
|
1175
|
-
columns: columns.filter((c) => c.table_name === t.table_name),
|
|
1176
|
-
pks: pks.filter((pk) => pk.table_name === t.table_name).map((pk) => pk.column_name),
|
|
1177
|
-
fks: fks.filter((fk) => fk.table_name === t.table_name)
|
|
1178
|
-
});
|
|
1179
|
-
return tablesMap;
|
|
1180
|
-
}
|
|
1181
|
-
/**
|
|
1182
|
-
* Join tables, identified by column name.
|
|
1183
|
-
*
|
|
1184
|
-
* Superseded for the CLI by `classifyTables` in `./introspect-db-structure`,
|
|
1185
|
-
* which asks the database instead: two single-column keys, unique together, no
|
|
1186
|
-
* payload column, nothing referencing the table. This rule folds away
|
|
1187
|
-
* `northwind.order_details` — which has the key shape and carries unit price,
|
|
1188
|
-
* quantity and discount — because it recognises `id`, `created_at` and
|
|
1189
|
-
* `updated_at` by name and calls everything else a foreign key.
|
|
1190
|
-
*
|
|
1191
|
-
* Still used by `./introspect-runtime`, which builds collections in memory from
|
|
1192
|
-
* a narrower set of catalog queries and has no unique-constraint or row-count
|
|
1193
|
-
* data to reason with.
|
|
1194
|
-
*/
|
|
1195
|
-
function identifyJoinTables(tablesMap) {
|
|
1196
|
-
const joinTables = /* @__PURE__ */ new Set();
|
|
1197
|
-
for (const [tableName, meta] of tablesMap.entries()) if (meta.fks.length === 2) {
|
|
1198
|
-
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);
|
|
1199
|
-
}
|
|
1200
|
-
return joinTables;
|
|
1201
|
-
}
|
|
1202
|
-
var IDENTITY_EXACT = {
|
|
1203
|
-
id: 0,
|
|
1204
|
-
uuid: 1,
|
|
1205
|
-
_id: 2
|
|
1206
|
-
};
|
|
1207
|
-
var TITLE_EXACT = {
|
|
1208
|
-
name: 10,
|
|
1209
|
-
title: 11,
|
|
1210
|
-
label: 12,
|
|
1211
|
-
display_name: 13,
|
|
1212
|
-
displayname: 13,
|
|
1213
|
-
headline: 14,
|
|
1214
|
-
subject: 15,
|
|
1215
|
-
heading: 16
|
|
1216
|
-
};
|
|
1217
|
-
var HUMAN_IDENTITY_EXACT = {
|
|
1218
|
-
first_name: 20,
|
|
1219
|
-
firstname: 20,
|
|
1220
|
-
last_name: 21,
|
|
1221
|
-
lastname: 21,
|
|
1222
|
-
full_name: 22,
|
|
1223
|
-
fullname: 22,
|
|
1224
|
-
given_name: 22,
|
|
1225
|
-
family_name: 23,
|
|
1226
|
-
middle_name: 24,
|
|
1227
|
-
username: 25,
|
|
1228
|
-
user_name: 25,
|
|
1229
|
-
email: 26,
|
|
1230
|
-
email_address: 26,
|
|
1231
|
-
phone: 27,
|
|
1232
|
-
phone_number: 27,
|
|
1233
|
-
mobile: 27
|
|
1234
|
-
};
|
|
1235
|
-
var DESCRIPTOR_EXACT = {
|
|
1236
|
-
slug: 30,
|
|
1237
|
-
code: 31,
|
|
1238
|
-
sku: 32,
|
|
1239
|
-
reference: 33,
|
|
1240
|
-
ref: 33,
|
|
1241
|
-
type: 34,
|
|
1242
|
-
kind: 34,
|
|
1243
|
-
status: 35,
|
|
1244
|
-
state: 35,
|
|
1245
|
-
role: 36,
|
|
1246
|
-
category: 37,
|
|
1247
|
-
group: 38,
|
|
1248
|
-
priority: 39,
|
|
1249
|
-
order: 39,
|
|
1250
|
-
sort_order: 39,
|
|
1251
|
-
position: 39
|
|
1252
|
-
};
|
|
1253
|
-
var SYSTEM_TIMESTAMP_EXACT = {
|
|
1254
|
-
created_at: 120,
|
|
1255
|
-
createdat: 120,
|
|
1256
|
-
creation_date: 120,
|
|
1257
|
-
inserted_at: 121,
|
|
1258
|
-
updated_at: 122,
|
|
1259
|
-
updatedat: 122,
|
|
1260
|
-
modified_at: 122,
|
|
1261
|
-
last_modified: 122,
|
|
1262
|
-
deleted_at: 123,
|
|
1263
|
-
deletedat: 123,
|
|
1264
|
-
archived_at: 124
|
|
1265
|
-
};
|
|
1266
|
-
var TITLE_PATTERNS = [
|
|
1267
|
-
"name",
|
|
1268
|
-
"title",
|
|
1269
|
-
"label"
|
|
1270
|
-
];
|
|
1271
|
-
var LONG_TEXT_NAMES = /* @__PURE__ */ new Set([
|
|
1272
|
-
"description",
|
|
1273
|
-
"summary",
|
|
1274
|
-
"excerpt",
|
|
1275
|
-
"abstract",
|
|
1276
|
-
"overview",
|
|
1277
|
-
"bio",
|
|
1278
|
-
"biography",
|
|
1279
|
-
"about"
|
|
1280
|
-
]);
|
|
1281
|
-
var RICH_CONTENT_NAMES = /* @__PURE__ */ new Set([
|
|
1282
|
-
"content",
|
|
1283
|
-
"body",
|
|
1284
|
-
"html",
|
|
1285
|
-
"markup",
|
|
1286
|
-
"text",
|
|
1287
|
-
"article_body",
|
|
1288
|
-
"post_body"
|
|
1289
|
-
]);
|
|
1290
|
-
var MEDIA_PATTERNS = [
|
|
1291
|
-
"image",
|
|
1292
|
-
"avatar",
|
|
1293
|
-
"photo",
|
|
1294
|
-
"logo",
|
|
1295
|
-
"cover",
|
|
1296
|
-
"thumbnail",
|
|
1297
|
-
"banner",
|
|
1298
|
-
"icon",
|
|
1299
|
-
"picture",
|
|
1300
|
-
"poster"
|
|
1301
|
-
];
|
|
1302
|
-
var JSON_MAP_NAMES = /* @__PURE__ */ new Set([
|
|
1303
|
-
"metadata",
|
|
1304
|
-
"meta",
|
|
1305
|
-
"config",
|
|
1306
|
-
"configuration",
|
|
1307
|
-
"settings",
|
|
1308
|
-
"options",
|
|
1309
|
-
"preferences",
|
|
1310
|
-
"data",
|
|
1311
|
-
"payload",
|
|
1312
|
-
"attributes",
|
|
1313
|
-
"extra",
|
|
1314
|
-
"additional_info"
|
|
1315
|
-
]);
|
|
1316
|
-
/**
|
|
1317
|
-
* Compute a numeric priority score for a property.
|
|
1318
|
-
* Lower scores appear first in the generated `propertiesOrder` array.
|
|
1319
|
-
*
|
|
1320
|
-
* The system uses 14 tiers (0–139), with the original column index
|
|
1321
|
-
* added as a fractional tiebreaker (originalIndex / 10000) to
|
|
1322
|
-
* guarantee stable ordering within the same tier.
|
|
1323
|
-
*
|
|
1324
|
-
* Pure function — no side effects.
|
|
1325
|
-
*/
|
|
1326
|
-
function computePropertyPriority(columnName, ctx) {
|
|
1327
|
-
const col = columnName.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
1328
|
-
const tiebreaker = ctx.originalIndex / 1e4;
|
|
1329
|
-
if (ctx.isPk) return (IDENTITY_EXACT[col] ?? 5) + tiebreaker;
|
|
1330
|
-
const systemTs = SYSTEM_TIMESTAMP_EXACT[col];
|
|
1331
|
-
if (systemTs !== void 0) return systemTs + tiebreaker;
|
|
1332
|
-
const titleExact = TITLE_EXACT[col];
|
|
1333
|
-
if (titleExact !== void 0) return titleExact + tiebreaker;
|
|
1334
|
-
const humanExact = HUMAN_IDENTITY_EXACT[col];
|
|
1335
|
-
if (humanExact !== void 0) return humanExact + tiebreaker;
|
|
1336
|
-
const descriptorExact = DESCRIPTOR_EXACT[col];
|
|
1337
|
-
if (descriptorExact !== void 0) return descriptorExact + tiebreaker;
|
|
1338
|
-
for (const pattern of TITLE_PATTERNS) if (col.includes(pattern) && col !== pattern) return 17 + tiebreaker;
|
|
1339
|
-
if (ctx.isStorage) return 90 + tiebreaker;
|
|
1340
|
-
for (const pattern of MEDIA_PATTERNS) if (col.includes(pattern)) return 91 + tiebreaker;
|
|
1341
|
-
if (col.endsWith("_url") || col.endsWith("_uri") || col.endsWith("_link")) return 92 + tiebreaker;
|
|
1342
|
-
if (LONG_TEXT_NAMES.has(col)) return 70 + tiebreaker;
|
|
1343
|
-
if (RICH_CONTENT_NAMES.has(col)) return 80 + tiebreaker;
|
|
1344
|
-
if (ctx.propType === "map") return JSON_MAP_NAMES.has(col) ? 100 + tiebreaker : 105 + tiebreaker;
|
|
1345
|
-
if (ctx.propType === "array") return 110 + tiebreaker;
|
|
1346
|
-
if (ctx.propType === "relation") return 60 + tiebreaker;
|
|
1347
|
-
if (ctx.isEnum) return 40 + tiebreaker;
|
|
1348
|
-
if (ctx.propType === "boolean") return 45 + tiebreaker;
|
|
1349
|
-
if (ctx.propType === "string" && ctx.pgDataType !== "text") return 42 + tiebreaker;
|
|
1350
|
-
if (ctx.propType === "number") return 50 + tiebreaker;
|
|
1351
|
-
if (ctx.propType === "date") return 55 + tiebreaker;
|
|
1352
|
-
if (ctx.propType === "string" && ctx.pgDataType === "text") return 75 + tiebreaker;
|
|
1353
|
-
return 130 + tiebreaker;
|
|
1354
|
-
}
|
|
1355
|
-
function sortPropertiesOrder(entries) {
|
|
1356
|
-
return [...entries].sort((a, b) => computePropertyPriority(a.key, a.ctx) - computePropertyPriority(b.key, b.ctx)).map((e) => e.key);
|
|
1357
|
-
}
|
|
1358
|
-
/**
|
|
1359
|
-
* The package specifiers the generated files name, spelled once.
|
|
1360
|
-
*
|
|
1361
|
-
* Written as constants rather than inline in the import templates below because
|
|
1362
|
-
* `scripts/headless-guard/check-types.mjs` scans core sources for `from
|
|
1363
|
-
* "@rebasepro/cms-types"` and cannot tell a real import from one this module
|
|
1364
|
-
* *writes*. It is right to be that blunt — the guard's whole value is that it
|
|
1365
|
-
* cannot be reasoned around — so the string simply never appears in that shape
|
|
1366
|
-
* here. Inlining them back into the templates re-breaks `check:types-headless`.
|
|
1367
|
-
*/
|
|
1368
|
-
var ADMIN_TYPES_PACKAGE = "@rebasepro/cms-types";
|
|
1369
|
-
var COMMON_PACKAGE = "@rebasepro/common";
|
|
1370
|
-
var TYPES_PACKAGE = "@rebasepro/types";
|
|
1371
|
-
/**
|
|
1372
|
-
* The table's row-level security policies, as the collection's `securityRules`.
|
|
1373
|
-
*
|
|
1374
|
-
* A table's policies are its access model, and a collection that describes
|
|
1375
|
-
* none leaves every one of them an "orphan": `doctor` fails on it, every push
|
|
1376
|
-
* warns about it, and a push drops one whose name has the shape an unnamed
|
|
1377
|
-
* rule compiles to (`<table>_<op>_<hash>`, which is every rule on a database
|
|
1378
|
-
* Rebase built). Described here, each is recreated from its rule as it was.
|
|
1379
|
-
*
|
|
1380
|
-
* Read back with `policyToSecurityRule` — what Studio's "Import from table"
|
|
1381
|
-
* and "Import to codebase" use — so the `TO` list, the mode and both clauses
|
|
1382
|
-
* come back as they are. The framework's own defaults
|
|
1383
|
-
* (`<table>_default_admin_read` and friends) are left out when the collection
|
|
1384
|
-
* keeps them (see {@link ownsItsAccess}): it is given them anyway, and
|
|
1385
|
-
* described twice they would be written twice.
|
|
1386
|
-
*/
|
|
1387
|
-
function renderSecurityRules(tableName, policies, keepsBaseline) {
|
|
1388
|
-
const injected = keepsBaseline ? adminBaselineNames(tableName) : /* @__PURE__ */ new Set();
|
|
1389
|
-
const own = policies.filter((policy) => policy.table_name === tableName && !injected.has(policy.policy_name));
|
|
1390
|
-
if (own.length === 0) return "";
|
|
1391
|
-
return `
|
|
1392
|
-
// The table's row-level security policies, read from the database. \`rebase db push\`
|
|
1393
|
-
// recreates each from its rule, so a policy is changed here from now on.\n securityRules: [${own.map((policy) => {
|
|
1394
|
-
const rule = policyToSecurityRule({
|
|
1395
|
-
policyname: policy.policy_name,
|
|
1396
|
-
cmd: toPolicyCommand(policy.cmd),
|
|
1397
|
-
permissive: policy.permissive.toUpperCase() === "RESTRICTIVE" ? "RESTRICTIVE" : "PERMISSIVE",
|
|
1398
|
-
roles: policy.roles,
|
|
1399
|
-
qual: policy.qual,
|
|
1400
|
-
with_check: policy.with_check
|
|
1401
|
-
});
|
|
1402
|
-
return `\n {\n${Object.entries(rule).map(([key, value]) => {
|
|
1403
|
-
return ` ${key}: ${Array.isArray(value) ? `[${value.map((item) => quote(String(item))).join(", ")}]` : quote(String(value))}`;
|
|
1404
|
-
}).join(",\n")}\n },`;
|
|
1405
|
-
}).join("")}\n ],`;
|
|
1406
|
-
}
|
|
1407
|
-
/** The policies every collection is given unless it opts out: `<table>_default_admin_read` and friends. */
|
|
1408
|
-
var adminBaselineNames = (tableName) => getGeneratedPolicyNames({
|
|
1409
|
-
name: tableName,
|
|
1410
|
-
slug: tableName,
|
|
1411
|
-
table: tableName,
|
|
1412
|
-
properties: {}
|
|
1413
|
-
});
|
|
1414
|
-
/**
|
|
1415
|
-
* Whether a table's access is its own, so that its collection must opt out of
|
|
1416
|
-
* the admin baseline: row-level security on, and not every baseline policy
|
|
1417
|
-
* there.
|
|
1418
|
-
*
|
|
1419
|
-
* Every collection is given the baseline (`<table>_default_admin_read`,
|
|
1420
|
-
* `_write_insert`, `_update`, `_delete`), permissive policies that let the
|
|
1421
|
-
* server and the `admin` role read and write every row. On a table whose
|
|
1422
|
-
* policies grant no such thing, the push after an introspection created them,
|
|
1423
|
-
* and an admin who had read no row of `orders` read them all. With
|
|
1424
|
-
* `disableDefaultPolicies: true` the push writes the table's own policies and
|
|
1425
|
-
* nothing else; a table that does hold the baseline (one Rebase built) keeps
|
|
1426
|
-
* it as it is.
|
|
1427
|
-
*
|
|
1428
|
-
* A table with RLS off keeps the baseline: the push switches RLS on whatever
|
|
1429
|
-
* the collection says, and that table had no policy narrowing anyone to begin
|
|
1430
|
-
* with. {@link describeRlsOffTables} says so. `undefined` RLS — a caller that did not
|
|
1431
|
-
* read it — is decided by the policies alone.
|
|
1432
|
-
*/
|
|
1433
|
-
function ownsItsAccess(tableName, table, policies) {
|
|
1434
|
-
if (!policies || table?.rls_enabled === false) return false;
|
|
1435
|
-
const present = new Set(policies.filter((policy) => policy.table_name === tableName).map((policy) => policy.policy_name));
|
|
1436
|
-
if (table?.rls_enabled !== true && present.size === 0) return false;
|
|
1437
|
-
return ![...adminBaselineNames(tableName)].every((name) => present.has(name));
|
|
1438
|
-
}
|
|
1439
|
-
/**
|
|
1440
|
-
* What `rebase db push` does to tables whose row-level security is off, for
|
|
1441
|
-
* the introspection to say once — or `undefined` when there are none.
|
|
1442
|
-
*/
|
|
1443
|
-
function describeRlsOffTables(tableNames) {
|
|
1444
|
-
if (tableNames.length === 0) return void 0;
|
|
1445
|
-
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 collection's securityRules grant.`;
|
|
1446
|
-
}
|
|
1447
|
-
/** The comment a collection whose table has row-level security off opens with. */
|
|
1448
|
-
function rlsOffComment(table) {
|
|
1449
|
-
if (table?.rls_enabled !== false) return "";
|
|
1450
|
-
return "\n// ⚠ Row-level security is off on this table, so every request reaches every row. `rebase db push`\n// switches it on: from then on the server and admins reach its rows, and anyone else what\n// securityRules grant.\n";
|
|
1451
|
-
}
|
|
1452
|
-
/** `pg_policies.cmd`, narrowed to the commands a policy can have. */
|
|
1453
|
-
function toPolicyCommand(cmd) {
|
|
1454
|
-
switch (cmd.toUpperCase()) {
|
|
1455
|
-
case "SELECT": return "SELECT";
|
|
1456
|
-
case "INSERT": return "INSERT";
|
|
1457
|
-
case "UPDATE": return "UPDATE";
|
|
1458
|
-
case "DELETE": return "DELETE";
|
|
1459
|
-
case "ALL": return "ALL";
|
|
1460
|
-
default: return;
|
|
1461
|
-
}
|
|
1462
|
-
}
|
|
1463
|
-
/** Adds entries to a property's `validation` block, creating it if absent. */
|
|
1464
|
-
function withValidation(extra, entries) {
|
|
1465
|
-
if (entries.length === 0) return extra;
|
|
1466
|
-
const block = entries.map((e) => ` ${e}`).join(",\n");
|
|
1467
|
-
if (extra.includes("validation: {")) return extra.replace("validation: {", `validation: {\n${block},`);
|
|
1468
|
-
return `${extra}\n validation: {\n${block}\n },`;
|
|
1469
|
-
}
|
|
1470
|
-
/**
|
|
1471
|
-
* Whether a property's generated text already sets `key:` as an object key.
|
|
1472
|
-
*
|
|
1473
|
-
* A bare `extra.includes("min:")` looks like it answers this and does not:
|
|
1474
|
-
* `admin:` ends in `min:`, so every property with an admin block claimed to
|
|
1475
|
-
* have a minimum already and silently lost the one the database declared. The
|
|
1476
|
-
* leading-delimiter requirement is the whole point — a key is preceded by a
|
|
1477
|
-
* newline, a brace or a comma, never by another identifier character.
|
|
1478
|
-
*/
|
|
1479
|
-
function hasGeneratedKey(extra, key) {
|
|
1480
|
-
return new RegExp(`(^|[\\s{,])${key}\\s*:`).test(extra);
|
|
1481
|
-
}
|
|
1482
|
-
/**
|
|
1483
|
-
* Adds entries to a property's `admin` block, creating it if absent.
|
|
1484
|
-
*
|
|
1485
|
-
* `emitAdmin` is false for the headless flavours, where `BaseProperty` has no
|
|
1486
|
-
* `admin` field to put them in — see {@link CollectionBuilder}. The options are
|
|
1487
|
-
* dropped rather than relocated: every one of them (`readOnly`, `multiline`,
|
|
1488
|
-
* `hideFromCollection`, `urlPreview`) describes a form widget, and there is no
|
|
1489
|
-
* form.
|
|
1490
|
-
*/
|
|
1491
|
-
function withAdminOptions(extra, entries, emitAdmin = true) {
|
|
1492
|
-
if (!emitAdmin) return extra;
|
|
1493
|
-
if (entries.length === 0) return extra;
|
|
1494
|
-
const block = entries.map((e) => ` ${e}`).join(",\n");
|
|
1495
|
-
if (extra.includes("admin: {")) return extra.replace("admin: {", `admin: {\n${block},`);
|
|
1496
|
-
return `${extra}\n admin: {\n${block}\n },`;
|
|
1497
|
-
}
|
|
1498
|
-
/** A SQL string literal. */
|
|
1499
|
-
var quoteSqlString = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
1500
|
-
/** A TypeScript string literal, escaped. */
|
|
1501
|
-
function quote(value) {
|
|
1502
|
-
return JSON.stringify(value);
|
|
1503
|
-
}
|
|
1504
|
-
var JS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
1505
|
-
/**
|
|
1506
|
-
* An object key for the generated file: verbatim when the name is a JavaScript
|
|
1507
|
-
* identifier, quoted otherwise.
|
|
1508
|
-
*
|
|
1509
|
-
* Postgres constrains an identifier only by quoting, so `order`, `full name`
|
|
1510
|
-
* and `2fa_enabled` are all ordinary column names — and all three produced a
|
|
1511
|
-
* file that did not parse when written as a bare key.
|
|
1512
|
-
*
|
|
1513
|
-
* Still needed now that keys are camel-cased rather than copied from the
|
|
1514
|
-
* column: `toWireKey` splits on separators and joins, which fixes `full name`
|
|
1515
|
-
* but cannot fix a name that is not an identifier for some other reason —
|
|
1516
|
-
* `2fa_enabled` becomes `2faEnabled`, still leading with a digit, and `order`
|
|
1517
|
-
* was never a separator problem at all.
|
|
1518
|
-
*/
|
|
1519
|
-
function propKey(name) {
|
|
1520
|
-
return JS_IDENTIFIER.test(name) ? name : quote(name);
|
|
1521
|
-
}
|
|
1522
|
-
/**
|
|
1523
|
-
* Text safe to put after `//`.
|
|
1524
|
-
*
|
|
1525
|
-
* A table comment or a classification reason is free text out of the database.
|
|
1526
|
-
* A newline in one ended the comment and let the rest of the value continue as
|
|
1527
|
-
* code.
|
|
1528
|
-
*/
|
|
1529
|
-
function commentText(value) {
|
|
1530
|
-
return value.replace(/\s*[\r\n]+\s*/g, " ");
|
|
1531
|
-
}
|
|
1532
|
-
/** A property-key array, one key per line, indented for the admin block. */
|
|
1533
|
-
function formatKeyList(keys) {
|
|
1534
|
-
if (keys.length === 0) return "[]";
|
|
1535
|
-
return `[\n${keys.map((k) => ` ${quote(k)}`).join(",\n")}\n ]`;
|
|
1536
|
-
}
|
|
1537
|
-
/**
|
|
1538
|
-
* Generate the full TypeScript file content for a single collection.
|
|
1539
|
-
* Pure function — no I/O.
|
|
1540
|
-
*/
|
|
1541
|
-
function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap, enumMap, sampleData, context = {}) {
|
|
1542
|
-
const collectionName = humanize(tableName);
|
|
1543
|
-
const singular = singularize(collectionName);
|
|
1544
|
-
const icon = getIconForTable(tableName);
|
|
1545
|
-
const classification = context.classifications?.get(tableName);
|
|
1546
|
-
const checkFacts = context.checkFacts ?? /* @__PURE__ */ new Map();
|
|
1547
|
-
const tableChecks = checkFacts.get(tableName);
|
|
1548
|
-
const columnComments = /* @__PURE__ */ new Map();
|
|
1549
|
-
let tableComment;
|
|
1550
|
-
for (const comment of context.metadata?.comments ?? []) {
|
|
1551
|
-
if (comment.table_name !== tableName) continue;
|
|
1552
|
-
if (comment.column_name === null) tableComment = comment.comment;
|
|
1553
|
-
else columnComments.set(comment.column_name, comment.comment);
|
|
1554
|
-
}
|
|
1555
|
-
const singleColumnUniques = new Set((context.metadata?.uniques ?? []).filter((u) => u.table_name === tableName && u.column_names.length === 1).map((u) => u.column_names[0]));
|
|
1556
|
-
const builder = context.builder ?? "admin-types";
|
|
1557
|
-
/** Whether the target project has an `admin` field to write into at all. */
|
|
1558
|
-
const emitAdmin = builder === "admin-types";
|
|
1559
|
-
const BUILDER_IMPORT = {
|
|
1560
|
-
"admin-types": `import { defineCollection } from ${quote(ADMIN_TYPES_PACKAGE)};`,
|
|
1561
|
-
common: `import { defineCollection } from ${quote(COMMON_PACKAGE)};`,
|
|
1562
|
-
annotation: `import { PostgresCollectionConfig } from ${quote(TYPES_PACKAGE)};`
|
|
1563
|
-
};
|
|
1564
|
-
const imports = /* @__PURE__ */ new Set([BUILDER_IMPORT[builder]]);
|
|
1565
|
-
/**
|
|
1566
|
-
* Imports the collection a relation points at — unless it is this one.
|
|
1567
|
-
*
|
|
1568
|
-
* A self-referencing key (`employees.reports_to -> employees`, which both
|
|
1569
|
-
* northwind and chinook have) otherwise made the file import its own default
|
|
1570
|
-
* export under the name it declares three lines later: `TS2440: Import
|
|
1571
|
-
* declaration conflicts with local declaration`. The relation target is a
|
|
1572
|
-
* thunk, so referring to the local const directly is fine — it is only
|
|
1573
|
-
* dereferenced after the module has finished evaluating.
|
|
1574
|
-
*/
|
|
1575
|
-
const importCollection = (otherTable) => {
|
|
1576
|
-
const varName = toCollectionVarName(otherTable);
|
|
1577
|
-
if (otherTable !== tableName) imports.add(`import ${varName} from ${quote(`./${otherTable}`)};`);
|
|
1578
|
-
return varName;
|
|
1579
|
-
};
|
|
1580
|
-
/**
|
|
1581
|
-
* A relation's `target` thunk, with its return type spelled out.
|
|
1582
|
-
*
|
|
1583
|
-
* The annotation is what makes `defineCollection` survive a relational schema.
|
|
1584
|
-
* Without an explicit type on the const, the collection's type is *inferred*,
|
|
1585
|
-
* and a relation cycle — `posts` belongs to `authors`, `authors` has many
|
|
1586
|
-
* `posts`; or `employees.reports_to -> employees`, which northwind, chinook and
|
|
1587
|
-
* musicbrainz all have — makes that inference circular: `TS7022: implicitly has
|
|
1588
|
-
* type 'any' because it is referenced directly or indirectly in its own
|
|
1589
|
-
* initializer`, plus `TS7023` on the thunk and `TS2303` on the import alias.
|
|
1590
|
-
* Naming the return type lets the checker type the thunk without resolving the
|
|
1591
|
-
* collection it points at, which breaks the cycle. Nothing else is given up:
|
|
1592
|
-
* the inference that matters runs over `properties`, not over `relations`.
|
|
1593
|
-
*
|
|
1594
|
-
* The annotated flavour has no cycle to break — its const is already typed — so
|
|
1595
|
-
* it keeps the plainer thunk it has always emitted.
|
|
1596
|
-
*/
|
|
1597
|
-
const relationTarget = (targetVarName) => {
|
|
1598
|
-
if (builder === "annotation") return `() => ${targetVarName}`;
|
|
1599
|
-
imports.add(`import type { AnyCollectionConfig } from ${quote(TYPES_PACKAGE)};`);
|
|
1600
|
-
return `(): AnyCollectionConfig => ${targetVarName}`;
|
|
1601
|
-
};
|
|
1602
|
-
let propsOutput = "";
|
|
1603
|
-
let relationsOutput = "";
|
|
1604
|
-
/** What the planner will not reproduce exactly, column by column. */
|
|
1605
|
-
const fileNotes = [];
|
|
1606
|
-
const skippedTables = context.skippedTables ?? /* @__PURE__ */ new Set();
|
|
1607
|
-
const orderEntries = [];
|
|
1608
|
-
const propertyBlocks = /* @__PURE__ */ new Map();
|
|
1609
|
-
/**
|
|
1610
|
-
* Column → the property key it was generated under.
|
|
1611
|
-
*
|
|
1612
|
-
* Needed because the structural helpers below (`deriveTitleProperty`,
|
|
1613
|
-
* `deriveKanbanProperty`, `deriveSort`) answer in *columns* — they read
|
|
1614
|
-
* `pg_attribute` — while `display.title`, `kanban.columnProperty` and
|
|
1615
|
-
* `sort` name **properties**. The two used to be the same string, so
|
|
1616
|
-
* nothing carried the translation; now `full_name` is generated as
|
|
1617
|
-
* `fullName` and a title pointing at `full_name` points at nothing.
|
|
1618
|
-
*/
|
|
1619
|
-
const keyByColumn = /* @__PURE__ */ new Map();
|
|
1620
|
-
/** Properties the list view will not render, so `listProperties` skips them. */
|
|
1621
|
-
const hiddenFromCollection = /* @__PURE__ */ new Set();
|
|
1622
|
-
let columnIndex = 0;
|
|
1623
|
-
const isCompositePk = meta.pks.length > 1;
|
|
1624
|
-
/**
|
|
1625
|
-
* The property type a column is generated as, with what the data sample
|
|
1626
|
-
* adds to it. A column of a composite key keeps its SQL type's reading:
|
|
1627
|
-
* it carries `isId`, which only a string or number property takes, and a
|
|
1628
|
-
* key column holding only 1s and 0s is still a key, not a boolean.
|
|
1629
|
-
*/
|
|
1630
|
-
const propertyTypeOf = (col) => {
|
|
1631
|
-
const isEnumColumn = col.data_type === "USER-DEFINED" && enumMap.get(col.udt_name) !== void 0;
|
|
1632
|
-
const propType = isEnumColumn ? "string" : col.udt_name === "vector" ? "vector" : mapPgType(col.data_type);
|
|
1633
|
-
if (isEnumColumn || !sampleData || sampleData.length === 0 || isCompositePk && meta.pks.includes(col.column_name)) return {
|
|
1634
|
-
propType,
|
|
1635
|
-
finalPropType: propType,
|
|
1636
|
-
inferenceExtra: ""
|
|
1637
|
-
};
|
|
1638
|
-
const values = sampleData.map((r) => r[col.column_name]);
|
|
1639
|
-
const inferred = inferPropertyFromData(col.column_name, col.data_type, propType, values, meta.pks.includes(col.column_name), emitAdmin);
|
|
1640
|
-
return {
|
|
1641
|
-
propType,
|
|
1642
|
-
finalPropType: inferred.propType || propType,
|
|
1643
|
-
inferenceExtra: inferred.extra || ""
|
|
1644
|
-
};
|
|
1645
|
-
};
|
|
1646
|
-
const compositeKeyMarkable = isCompositePk && meta.pks.every((pk) => {
|
|
1647
|
-
const keyColumn = meta.columns.find((c) => c.column_name === pk);
|
|
1648
|
-
if (!keyColumn) return false;
|
|
1649
|
-
const { finalPropType } = propertyTypeOf(keyColumn);
|
|
1650
|
-
return finalPropType === "string" || finalPropType === "number" || finalPropType === "date" && keyColumn.data_type.toLowerCase() === "date";
|
|
1651
|
-
});
|
|
1652
|
-
for (const col of meta.columns) {
|
|
1653
|
-
if (col.is_generated === "ALWAYS" && (columnComments.get(col.column_name) ?? "").startsWith("rebase:search:v1:")) continue;
|
|
1654
|
-
if (meta.fks.some((fk) => fk.column_name === col.column_name) && !meta.pks.includes(col.column_name)) continue;
|
|
1655
|
-
const currentIndex = columnIndex++;
|
|
1656
|
-
const propertyKey = firstFreeKey([toWireKey(col.column_name), col.column_name], propertyBlocks);
|
|
1657
|
-
keyByColumn.set(col.column_name, propertyKey);
|
|
1658
|
-
const colEnumValues = enumMap.get(col.udt_name);
|
|
1659
|
-
const isEnumColumn = col.data_type === "USER-DEFINED" && colEnumValues !== void 0;
|
|
1660
|
-
let extra = "";
|
|
1661
|
-
const colNameLower = col.column_name.toLowerCase();
|
|
1662
|
-
const { propType, finalPropType, inferenceExtra } = propertyTypeOf(col);
|
|
1663
|
-
const columnChecks = tableChecks?.get(col.column_name);
|
|
1664
|
-
if (isEnumColumn && colEnumValues) {
|
|
1665
|
-
const enumEntries = colEnumValues.map((v) => `{ id: ${quote(v)}, label: ${quote(humanize(v))} }`).join(", ");
|
|
1666
|
-
extra += `\n enum: [${enumEntries}],`;
|
|
1667
|
-
} else if (columnChecks?.enumValues && !inferenceExtra.includes("enum:") && propType === "string") {
|
|
1668
|
-
const enumEntries = columnChecks.enumValues.map((v) => `{ id: ${quote(v)}, label: ${quote(humanize(v))} }`).join(", ");
|
|
1669
|
-
extra += `\n enum: [${enumEntries}],`;
|
|
1670
|
-
const enumType = toPostgresIdentifier(`${tableName}_${col.column_name}`);
|
|
1671
|
-
const labels = columnChecks.enumValues.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ");
|
|
1672
|
-
const check = (context.metadata?.checks ?? []).find((c) => c.table_name === tableName && c.definition.includes(col.column_name));
|
|
1673
|
-
const table = `"${tableName}"`;
|
|
1674
|
-
const column = `"${col.column_name}"`;
|
|
1675
|
-
const restoreDefault = literalDefaultOf(col, "string");
|
|
1676
|
-
fileNotes.push(`"${col.column_name}" is text with CHECK (… IN …), declared here as an \`enum\`, which Rebase stores as the enum type "${enumType}". Convert the column before pushing: CREATE TYPE "${enumType}" AS ENUM (${labels}); ALTER TABLE ${table} ${check ? `DROP CONSTRAINT "${check.constraint_name}", ` : ""}ALTER COLUMN ${column} DROP DEFAULT, ALTER COLUMN ${column} TYPE "${enumType}" USING ${column}::"${enumType}"` + (restoreDefault && "source" in restoreDefault ? `, ALTER COLUMN ${column} SET DEFAULT ${quoteSqlString(JSON.parse(restoreDefault.source))}` : "") + "; — or delete the `enum` to keep the column as it is.");
|
|
1677
|
-
}
|
|
1678
|
-
if (finalPropType === "date") {
|
|
1679
|
-
if (colNameLower === "created_at" || colNameLower === "createdat") {
|
|
1680
|
-
extra += "\n autoValue: \"on_create\",";
|
|
1681
|
-
extra = withAdminOptions(extra, ["readOnly: true", "hideFromCollection: true"], emitAdmin);
|
|
1682
|
-
hiddenFromCollection.add(propertyKey);
|
|
1683
|
-
} else if (colNameLower === "updated_at" || colNameLower === "updatedat") {
|
|
1684
|
-
extra += "\n autoValue: \"on_update\",";
|
|
1685
|
-
extra = withAdminOptions(extra, ["readOnly: true", "hideFromCollection: true"], emitAdmin);
|
|
1686
|
-
hiddenFromCollection.add(propertyKey);
|
|
1687
|
-
} else if (col.column_default && (col.column_default.includes("now()") || col.column_default.includes("CURRENT_TIMESTAMP"))) {
|
|
1688
|
-
extra += "\n autoValue: \"on_create\",";
|
|
1689
|
-
extra = withAdminOptions(extra, ["readOnly: true"], emitAdmin);
|
|
1690
|
-
}
|
|
1691
|
-
}
|
|
1692
|
-
if (finalPropType === "array" && !inferenceExtra.includes("of: {")) {
|
|
1693
|
-
const stored = arrayStorage(col);
|
|
1694
|
-
if (stored.columnType) extra += `\n columnType: ${quote(stored.columnType)},`;
|
|
1695
|
-
if (stored.note) fileNotes.push(stored.note);
|
|
1696
|
-
extra += `\n of: { name: ${quote(`${humanize(col.column_name)} Item`)}, type: ${quote(stored.innerType)} },`;
|
|
1697
|
-
} else if (finalPropType === "map" && !inferenceExtra.includes("keyValue: true") && !inferenceExtra.includes("properties: {")) extra += "\n keyValue: true,";
|
|
1698
|
-
if (finalPropType === "string" && !isEnumColumn && !inferenceExtra) {
|
|
1699
|
-
const isUrl = colNameLower.endsWith("_url") || colNameLower.endsWith("_uri") || colNameLower.endsWith("_link");
|
|
1700
|
-
if (colNameLower.includes("image") || colNameLower.includes("avatar") || colNameLower.includes("photo") || colNameLower.includes("logo") || colNameLower.includes("cover")) extra += `\n storage: {\n storagePath: ${quote(`${tableName}/${col.column_name}`)}\n },`;
|
|
1701
|
-
else if (isUrl) extra += "\n url: true,";
|
|
1702
|
-
else if (colNameLower === "description" || colNameLower === "summary" || colNameLower === "excerpt") extra = withAdminOptions(extra, ["multiline: true"], emitAdmin);
|
|
1703
|
-
else if (colNameLower === "content" || colNameLower === "body") extra = withAdminOptions(extra, ["multiline: true", "markdown: true"], emitAdmin);
|
|
1704
|
-
else if (col.data_type === "text") extra = withAdminOptions(extra, ["multiline: true"], emitAdmin);
|
|
1705
|
-
}
|
|
1706
|
-
if (inferenceExtra) {
|
|
1707
|
-
extra += inferenceExtra;
|
|
1708
|
-
if (!extra.endsWith(",")) extra += ",";
|
|
1709
|
-
}
|
|
1710
|
-
if (!meta.pks.includes(col.column_name) && !isReadOnlyColumn(col)) {
|
|
1711
|
-
const enumTypeName = toPostgresIdentifier(`${tableName}_${col.column_name}`);
|
|
1712
|
-
const enumTypeShared = isEnumColumn && (context.metadata?.columns ?? meta.columns).filter((other) => other.udt_name === col.udt_name && other.data_type === "USER-DEFINED").length > 1;
|
|
1713
|
-
const stored = finalPropType === "array" ? { keys: [] } : columnStorage(col, finalPropType, {
|
|
1714
|
-
isEnumColumn,
|
|
1715
|
-
enumTypeName,
|
|
1716
|
-
enumTypeShared
|
|
1717
|
-
});
|
|
1718
|
-
for (const key of stored.keys) {
|
|
1719
|
-
const name = key.slice(0, key.indexOf(":"));
|
|
1720
|
-
if (!hasGeneratedKey(extra, name) && !hasGeneratedKey(inferenceExtra, name)) extra += `\n ${key},`;
|
|
1721
|
-
}
|
|
1722
|
-
if (stored.note) fileNotes.push(stored.note);
|
|
1723
|
-
if (!hasGeneratedKey(extra, "autoValue") && !hasGeneratedKey(extra, "defaultValue")) {
|
|
1724
|
-
const fallback = literalDefaultOf(col, finalPropType);
|
|
1725
|
-
if (fallback && "source" in fallback) extra += `\n defaultValue: ${fallback.source},`;
|
|
1726
|
-
else if (fallback) {
|
|
1727
|
-
const expression = col.column_default?.trim();
|
|
1728
|
-
if (col.is_nullable === "NO" && expression) extra += `\n databaseDefault: ${JSON.stringify(`sql\`${expression}\``)},`;
|
|
1729
|
-
else fileNotes.push(fallback.note);
|
|
1730
|
-
}
|
|
1731
|
-
}
|
|
1732
|
-
}
|
|
1733
|
-
const declaredValidation = [];
|
|
1734
|
-
if (finalPropType === "string" && typeof col.character_maximum_length === "number" && col.character_maximum_length > 0 && !hasGeneratedKey(extra, "max")) declaredValidation.push(`max: ${col.character_maximum_length}`);
|
|
1735
|
-
if (columnChecks) {
|
|
1736
|
-
if (finalPropType === "number") {
|
|
1737
|
-
if (columnChecks.min !== void 0 && !hasGeneratedKey(extra, "min")) declaredValidation.push(`min: ${columnChecks.min}`);
|
|
1738
|
-
if (columnChecks.max !== void 0 && !hasGeneratedKey(extra, "max")) declaredValidation.push(`max: ${columnChecks.max}`);
|
|
1739
|
-
if (columnChecks.moreThan !== void 0) declaredValidation.push(`moreThan: ${columnChecks.moreThan}`);
|
|
1740
|
-
if (columnChecks.lessThan !== void 0) declaredValidation.push(`lessThan: ${columnChecks.lessThan}`);
|
|
1741
|
-
}
|
|
1742
|
-
if (finalPropType === "string") {
|
|
1743
|
-
if (columnChecks.lengthMin !== void 0 && !hasGeneratedKey(extra, "min")) declaredValidation.push(`min: ${columnChecks.lengthMin}`);
|
|
1744
|
-
if (columnChecks.lengthMax !== void 0 && !declaredValidation.some((v) => v.startsWith("max:")) && !hasGeneratedKey(extra, "max")) declaredValidation.push(`max: ${columnChecks.lengthMax}`);
|
|
1745
|
-
}
|
|
1746
|
-
}
|
|
1747
|
-
if (singleColumnUniques.has(col.column_name) && !meta.pks.includes(col.column_name)) declaredValidation.push("unique: true");
|
|
1748
|
-
extra = withValidation(extra, declaredValidation);
|
|
1749
|
-
if (isReadOnlyColumn(col) && !hasGeneratedKey(extra, "readOnly")) {
|
|
1750
|
-
const options = ["readOnly: true"];
|
|
1751
|
-
if (isDerivedIndexColumn(col) && !hasGeneratedKey(extra, "hideFromCollection")) {
|
|
1752
|
-
options.push("hideFromCollection: true");
|
|
1753
|
-
hiddenFromCollection.add(propertyKey);
|
|
1754
|
-
}
|
|
1755
|
-
extra = withAdminOptions(extra, options, emitAdmin);
|
|
1756
|
-
}
|
|
1757
|
-
const columnComment = columnComments.get(col.column_name);
|
|
1758
|
-
if (columnComment) extra = `\n description: ${quote(columnComment)},${extra}`;
|
|
1759
|
-
if (meta.pks.includes(col.column_name)) {
|
|
1760
|
-
if (isCompositePk) {
|
|
1761
|
-
extra += `\n // Part of composite primary key (${commentText(meta.pks.join(", "))})`;
|
|
1762
|
-
if (compositeKeyMarkable && !inferenceExtra.includes("isId:")) {
|
|
1763
|
-
const stored = primaryKeyStorage(col, finalPropType);
|
|
1764
|
-
for (const key of stored.keys) {
|
|
1765
|
-
const name = key.slice(0, key.indexOf(":"));
|
|
1766
|
-
if (!hasGeneratedKey(extra, name)) extra += `\n ${key},`;
|
|
1767
|
-
}
|
|
1768
|
-
if (stored.note) fileNotes.push(stored.note);
|
|
1769
|
-
}
|
|
1770
|
-
} else if (!inferenceExtra.includes("isId:")) {
|
|
1771
|
-
const stored = primaryKeyStorage(col, finalPropType);
|
|
1772
|
-
for (const key of stored.keys) {
|
|
1773
|
-
const name = key.slice(0, key.indexOf(":"));
|
|
1774
|
-
if (!hasGeneratedKey(extra, name)) extra += `\n ${key},`;
|
|
1775
|
-
}
|
|
1776
|
-
if (stored.note) fileNotes.push(stored.note);
|
|
1777
|
-
}
|
|
1778
|
-
}
|
|
1779
|
-
if (finalPropType === "vector") {
|
|
1780
|
-
const dims = col.atttypmod && col.atttypmod > 0 ? col.atttypmod : 1536;
|
|
1781
|
-
extra += `\n dimensions: ${dims},`;
|
|
1782
|
-
}
|
|
1783
|
-
if (col.is_nullable === "NO" && !meta.pks.includes(col.column_name) && !isReadOnlyColumn(col)) if (extra.includes("validation: {")) extra = extra.replace("validation: {", "validation: {\n required: true,");
|
|
1784
|
-
else extra += "\n validation: {\n required: true\n },";
|
|
1785
|
-
const humanName = humanize(col.column_name);
|
|
1786
|
-
orderEntries.push({
|
|
1787
|
-
key: propertyKey,
|
|
1788
|
-
ctx: {
|
|
1789
|
-
propType: finalPropType,
|
|
1790
|
-
isPk: meta.pks.includes(col.column_name),
|
|
1791
|
-
isEnum: isEnumColumn,
|
|
1792
|
-
isStorage: extra.includes("storage: {") || inferenceExtra.includes("storage: {"),
|
|
1793
|
-
pgDataType: col.data_type,
|
|
1794
|
-
originalIndex: currentIndex
|
|
1795
|
-
}
|
|
1796
|
-
});
|
|
1797
|
-
propertyBlocks.set(propertyKey, `
|
|
1798
|
-
${propKey(propertyKey)}: {
|
|
1799
|
-
name: ${quote(humanName)},
|
|
1800
|
-
columnName: ${quote(col.column_name)},
|
|
1801
|
-
type: ${quote(finalPropType)},${extra}
|
|
1802
|
-
},`);
|
|
1803
|
-
}
|
|
1804
|
-
for (const fk of meta.fks) {
|
|
1805
|
-
const targetTableName = fk.foreign_table_name;
|
|
1806
|
-
if (skippedTables.has(targetTableName)) continue;
|
|
1807
|
-
if (!joinTables.has(targetTableName)) {
|
|
1808
|
-
const stripped = toWireKey(fk.column_name.replace(/_id$/, ""));
|
|
1809
|
-
const relName = firstFreeKey([
|
|
1810
|
-
stripped,
|
|
1811
|
-
toWireKey(targetTableName),
|
|
1812
|
-
`${stripped}Relation`
|
|
1813
|
-
], propertyBlocks);
|
|
1814
|
-
orderEntries.push({
|
|
1815
|
-
key: relName,
|
|
1816
|
-
ctx: {
|
|
1817
|
-
propType: "relation",
|
|
1818
|
-
isPk: false,
|
|
1819
|
-
isEnum: false,
|
|
1820
|
-
isStorage: false,
|
|
1821
|
-
pgDataType: "",
|
|
1822
|
-
originalIndex: columnIndex++
|
|
1823
|
-
}
|
|
1824
|
-
});
|
|
1825
|
-
const targetCollectionCamel = importCollection(targetTableName);
|
|
1826
|
-
const relHumanName = humanize(relName);
|
|
1827
|
-
const required = meta.columns.find((c) => c.column_name === fk.column_name)?.is_nullable === "NO";
|
|
1828
|
-
const onDelete = onDeleteOf(fk, required);
|
|
1829
|
-
const requiredLine = required ? "\n validation: { required: true }," : "";
|
|
1830
|
-
const onDeleteLine = onDelete ? `,\n onDelete: ${quote(onDelete)}` : "";
|
|
1831
|
-
const derivedIndex = foreignKeyIndexSpec(context.metadata?.schema ?? "public", tableName, fk.column_name);
|
|
1832
|
-
const tableIndexes = context.metadata?.indexes?.filter((i) => i.table_name === tableName);
|
|
1833
|
-
const indexMissing = tableIndexes !== void 0 && meta.pks[0] !== fk.column_name && !tableIndexes.some((i) => i.index_name === derivedIndex.indexName);
|
|
1834
|
-
const servedBy = tableIndexes?.find((i) => i.leading_column === fk.column_name && i.serves_leading_column);
|
|
1835
|
-
const indexReason = servedBy ? `${commentText(servedBy.index_name)} already indexes ${commentText(fk.column_name)}, so Rebase builds none of its own. Without this line, \`rebase db push\` would build a second.` : `The database has no index on ${commentText(fk.column_name)}. Delete this line to have one built.`;
|
|
1836
|
-
const indexLine = indexMissing ? `,\n // ${indexReason}\n index: false` : "";
|
|
1837
|
-
propertyBlocks.set(relName, `
|
|
1838
|
-
${propKey(relName)}: {
|
|
1839
|
-
name: ${quote(relHumanName)},
|
|
1840
|
-
type: "relation",${requiredLine}
|
|
1841
|
-
// mapped from foreign key: ${commentText(fk.column_name)} -> ${commentText(targetTableName)}(${commentText(fk.foreign_column_name)})
|
|
1842
|
-
relation: {
|
|
1843
|
-
kind: "belongsTo",
|
|
1844
|
-
target: ${relationTarget(targetCollectionCamel)},
|
|
1845
|
-
localKey: ${quote(fk.column_name)}${onDeleteLine}${indexLine}
|
|
1846
|
-
}
|
|
1847
|
-
},`);
|
|
1848
|
-
}
|
|
1849
|
-
}
|
|
1850
|
-
/**
|
|
1851
|
-
* A name for an entry in the `relations` array that no property and no
|
|
1852
|
-
* earlier entry has taken.
|
|
1853
|
-
*
|
|
1854
|
-
* Relations and properties share one namespace — a relation is found by
|
|
1855
|
-
* name — so a `belongsTo` property called `series` beside a many-to-many
|
|
1856
|
-
* also called `series` left one of them unreachable: the planner resolved
|
|
1857
|
-
* the property's name to the many-to-many, planned no `series_id` column,
|
|
1858
|
-
* and the first push dropped it.
|
|
1859
|
-
*/
|
|
1860
|
-
const usedRelationNames = /* @__PURE__ */ new Set();
|
|
1861
|
-
const relationNameFor = (preferred, fallback) => {
|
|
1862
|
-
const name = firstFreeKey([preferred, fallback], { has: (key) => propertyBlocks.has(key) || usedRelationNames.has(key) });
|
|
1863
|
-
usedRelationNames.add(name);
|
|
1864
|
-
return name;
|
|
1865
|
-
};
|
|
1866
|
-
const inverseFks = allFks.filter((fk) => fk.foreign_table_name === tableName && !joinTables.has(fk.table_name) && !skippedTables.has(fk.table_name));
|
|
1867
|
-
for (const fk of inverseFks) {
|
|
1868
|
-
const sourceTableName = fk.table_name;
|
|
1869
|
-
const targetCollectionCamel = importCollection(sourceTableName);
|
|
1870
|
-
relationsOutput += `
|
|
1871
|
-
{
|
|
1872
|
-
kind: "hasMany",
|
|
1873
|
-
relationName: ${quote(relationNameFor(sourceTableName, `${sourceTableName}_by_${fk.column_name}`))},
|
|
1874
|
-
target: ${relationTarget(targetCollectionCamel)},
|
|
1875
|
-
// the ${commentText(sourceTableName)}.${commentText(fk.column_name)} FK points back here
|
|
1876
|
-
foreignKeyOnTarget: ${quote(fk.column_name)}
|
|
1877
|
-
},`;
|
|
1878
|
-
}
|
|
1879
|
-
const relatedJoinTables = Array.from(joinTables).filter((jt) => {
|
|
1880
|
-
const jtMeta = tablesMap.get(jt);
|
|
1881
|
-
return jtMeta ? jtMeta.fks.some((fk) => fk.foreign_table_name === tableName) : false;
|
|
1882
|
-
});
|
|
1883
|
-
for (const jt of relatedJoinTables) {
|
|
1884
|
-
const jtMeta = tablesMap.get(jt);
|
|
1885
|
-
if (!jtMeta) continue;
|
|
1886
|
-
const joinFks = jtMeta.fks;
|
|
1887
|
-
const keyPosition = (fk) => {
|
|
1888
|
-
const position = jtMeta.pks.indexOf(fk.column_name);
|
|
1889
|
-
return position === -1 ? Number.MAX_SAFE_INTEGER : position;
|
|
1890
|
-
};
|
|
1891
|
-
const selfRefFks = joinFks.filter((fk) => fk.foreign_table_name === tableName).sort((a, b) => keyPosition(a) - keyPosition(b));
|
|
1892
|
-
if (selfRefFks.length === 2) {
|
|
1893
|
-
const thisFk = selfRefFks[0];
|
|
1894
|
-
const otherFk = selfRefFks[1];
|
|
1895
|
-
const relPropName = `${tableName}_via_${otherFk.column_name.replace(/_id$/, "")}`;
|
|
1896
|
-
relationsOutput += `
|
|
1897
|
-
{
|
|
1898
|
-
kind: "manyToMany",
|
|
1899
|
-
relationName: ${quote(relationNameFor(relPropName, `${relPropName}_${jt}`))},
|
|
1900
|
-
target: ${relationTarget(toCollectionVarName(tableName))},
|
|
1901
|
-
through: {
|
|
1902
|
-
table: ${quote(jt)},
|
|
1903
|
-
sourceColumn: ${quote(thisFk.column_name)},
|
|
1904
|
-
targetColumn: ${quote(otherFk.column_name)}
|
|
1905
|
-
}
|
|
1906
|
-
},`;
|
|
1907
|
-
continue;
|
|
1908
|
-
}
|
|
1909
|
-
const otherFk = joinFks.find((fk) => fk.foreign_table_name !== tableName);
|
|
1910
|
-
const leadingTable = joinFks.find((fk) => fk.column_name === jtMeta.pks[0])?.foreign_table_name;
|
|
1911
|
-
const sortsFirst = otherFk ? [tableName, otherFk.foreign_table_name].sort()[0] : tableName;
|
|
1912
|
-
const declareHere = !leadingTable || leadingTable === sortsFirst || leadingTable === tableName;
|
|
1913
|
-
if (otherFk && !declareHere) relationsOutput += `
|
|
1914
|
-
// The many-to-many with ${commentText(otherFk.foreign_table_name)} through ${commentText(jt)} is declared on
|
|
1915
|
-
// ${commentText(otherFk.foreign_table_name)} only: declaring it here too would re-key ${commentText(jt)}
|
|
1916
|
-
// from (${commentText(jtMeta.pks.join(", "))}) on the next push.`;
|
|
1917
|
-
if (otherFk && declareHere && !skippedTables.has(otherFk.foreign_table_name)) {
|
|
1918
|
-
const targetTableName = otherFk.foreign_table_name;
|
|
1919
|
-
const targetCollectionCamel = importCollection(targetTableName);
|
|
1920
|
-
const thisFk = joinFks.find((fk) => fk.foreign_table_name === tableName);
|
|
1921
|
-
const throughCode = thisFk ? `\n through: {\n table: ${quote(jt)},\n sourceColumn: ${quote(thisFk.column_name)},\n targetColumn: ${quote(otherFk.column_name)}\n }` : "";
|
|
1922
|
-
relationsOutput += `
|
|
1923
|
-
{
|
|
1924
|
-
kind: "manyToMany",
|
|
1925
|
-
relationName: ${quote(relationNameFor(targetTableName, `${targetTableName}_via_${jt}`))},
|
|
1926
|
-
target: ${relationTarget(targetCollectionCamel)},${throughCode}
|
|
1927
|
-
},`;
|
|
1928
|
-
}
|
|
1929
|
-
}
|
|
1930
|
-
const search = reconstructSearchBlock({
|
|
1931
|
-
schema: context.metadata?.schema ?? "public",
|
|
1932
|
-
table: tableName,
|
|
1933
|
-
columns: meta.columns,
|
|
1934
|
-
comments: columnComments,
|
|
1935
|
-
keyByColumn
|
|
1936
|
-
});
|
|
1937
|
-
if (search.note) fileNotes.push(search.note);
|
|
1938
|
-
const searchBlock = search.block ?? "";
|
|
1939
|
-
const relationsBlock = relationsOutput ? `\n relations: [${relationsOutput}\n ],` : "";
|
|
1940
|
-
const tableRow = context.metadata?.tables?.find((table) => table.table_name === tableName);
|
|
1941
|
-
const ownsAccess = ownsItsAccess(tableName, tableRow, context.metadata?.policies);
|
|
1942
|
-
const securityRulesBlock = renderSecurityRules(tableName, context.metadata?.policies ?? [], !ownsAccess);
|
|
1943
|
-
const defaultPoliciesBlock = ownsAccess ? "\n // The table's policies are its whole access model: without this line `rebase db push`\n // would add the admin baseline (`<table>_default_admin_*`), letting the server and\n // admins read and write every row. Delete it to give them that.\n disableDefaultPolicies: true," : "";
|
|
1944
|
-
const sortedPropertiesOrder = sortPropertiesOrder(orderEntries);
|
|
1945
|
-
for (const key of sortedPropertiesOrder) propsOutput += propertyBlocks.get(key) || "";
|
|
1946
|
-
const adminEntries = [`icon: ${quote(icon)}`];
|
|
1947
|
-
if (classification) {
|
|
1948
|
-
const derivedFacts = context.metadata ? buildColumnFacts(meta, context.metadata, enumMap, checkFacts) : void 0;
|
|
1949
|
-
if (classification.role === "owned-child") adminEntries.push("hideFromNavigation: true");
|
|
1950
|
-
else if (classification.role === "lookup") adminEntries.push("group: \"Reference\"");
|
|
1951
|
-
if (derivedFacts) {
|
|
1952
|
-
const asProperty = (column) => keyByColumn.get(column) ?? toWireKey(column);
|
|
1953
|
-
const titleProperty = deriveTitleProperty(derivedFacts);
|
|
1954
|
-
if (titleProperty) adminEntries.push(`display: { title: ${quote(asProperty(titleProperty))} }`);
|
|
1955
|
-
const kanbanProperty = deriveKanbanProperty(derivedFacts);
|
|
1956
|
-
const orderProperty = kanbanProperty ? deriveKanbanOrderProperty(derivedFacts) : void 0;
|
|
1957
|
-
if (kanbanProperty && orderProperty) {
|
|
1958
|
-
adminEntries.push(`kanban: {\n columnProperty: ${quote(asProperty(kanbanProperty))}\n }`);
|
|
1959
|
-
adminEntries.push(`orderProperty: ${quote(asProperty(orderProperty))}`);
|
|
1960
|
-
} else if (kanbanProperty) adminEntries.push(`// A board over ${quote(asProperty(kanbanProperty))} fits this table, but a board needs a string column to keep each card's order in. Add one, then declare kanban: { columnProperty: ${quote(asProperty(kanbanProperty))} } and orderProperty: "<that property>".`);
|
|
1961
|
-
const sort = deriveSort(derivedFacts);
|
|
1962
|
-
if (sort) adminEntries.push(`sort: [${quote(asProperty(sort[0]))}, "desc"]`);
|
|
1963
|
-
}
|
|
1964
|
-
const listProperties = deriveListProperties(sortedPropertiesOrder, hiddenFromCollection);
|
|
1965
|
-
if (listProperties) adminEntries.push(`listProperties: ${formatKeyList(listProperties)}`);
|
|
1966
|
-
}
|
|
1967
|
-
adminEntries.push(`propertiesOrder: ${formatKeyList(sortedPropertiesOrder)}`);
|
|
1968
|
-
const adminBlock = emitAdmin ? `\n admin: {\n ${adminEntries.join(",\n ")}\n }` : "";
|
|
1969
|
-
const descriptionBlock = tableComment ? `\n description: ${quote(tableComment)},` : "";
|
|
1970
|
-
const pgSchema = context.metadata?.schema;
|
|
1971
|
-
const schemaBlock = pgSchema && pgSchema !== "public" ? `\n schema: ${quote(pgSchema)},` : "";
|
|
1972
|
-
const classificationNote = classification && classification.role !== "entity" ? `\n// Introspected as ${/^[aeiou]/.test(classification.role) ? "an" : "a"} ${commentText(classification.role)}: ${commentText(classification.reason)}.\n` : "";
|
|
1973
|
-
for (const note of fileNotes) context.notes?.push(`${tableName}: ${note}`);
|
|
1974
|
-
const storageNote = fileNotes.length > 0 ? `\n// ⚠ Not reproduced exactly by \`rebase db push\` — read before pushing:\n${fileNotes.map((n) => `// - ${commentText(n)}`).join("\n")}\n` : "";
|
|
1975
|
-
const collectionVarName = toCollectionVarName(tableName);
|
|
1976
|
-
const [open, close] = builder === "annotation" ? [`const ${collectionVarName}: PostgresCollectionConfig = {`, "};"] : [`const ${collectionVarName} = defineCollection({`, "});"];
|
|
1977
|
-
const importLines = Array.from(imports);
|
|
1978
|
-
return `${[...importLines.filter((line) => !line.includes("from \"./")), ...importLines.filter((line) => line.includes("from \"./"))].join("\n")}
|
|
1979
|
-
${classificationNote}${storageNote}${rlsOffComment(tableRow)}
|
|
1980
|
-
${open}
|
|
1981
|
-
name: ${quote(collectionName)},
|
|
1982
|
-
singularName: ${quote(singular)},
|
|
1983
|
-
slug: ${quote(tableName)},
|
|
1984
|
-
table: ${quote(tableName)},${schemaBlock}${descriptionBlock}${searchBlock}
|
|
1985
|
-
properties: {${propsOutput}
|
|
1986
|
-
},${relationsBlock}${defaultPoliciesBlock}${securityRulesBlock}${adminBlock}
|
|
1987
|
-
${close}
|
|
1988
|
-
|
|
1989
|
-
export default ${collectionVarName};
|
|
1990
|
-
`;
|
|
1991
|
-
}
|
|
1992
|
-
/**
|
|
1993
|
-
* Generate the content for an index.ts file that re-exports all collections.
|
|
1994
|
-
*/
|
|
1995
|
-
function generateIndexContent(fileNames) {
|
|
1996
|
-
const sorted = [...fileNames].sort();
|
|
1997
|
-
let imports = "";
|
|
1998
|
-
let arrayElements = "";
|
|
1999
|
-
for (const f of sorted) {
|
|
2000
|
-
const varName = toCollectionVarName(f);
|
|
2001
|
-
imports += `import ${varName} from ${quote(`./${f}`)};\n`;
|
|
2002
|
-
arrayElements += ` ${varName},\n`;
|
|
2003
|
-
}
|
|
2004
|
-
return `${imports}\nexport const collections = [\n${arrayElements}];\n`;
|
|
2005
|
-
}
|
|
2006
|
-
/**
|
|
2007
|
-
* Merge new exports into existing index.ts content.
|
|
2008
|
-
* Returns the merged content string.
|
|
2009
|
-
*/
|
|
2010
|
-
function mergeIndexContent(existingContent, newFileNames) {
|
|
2011
|
-
const existingImports = new Set([...existingContent.matchAll(/import\s+([a-zA-Z0-9_]+)\s+from\s+"\.\/([^"]+)"/g)].map((m) => m[2]));
|
|
2012
|
-
const sorted = [...newFileNames].sort();
|
|
2013
|
-
let newImports = "";
|
|
2014
|
-
let newElements = "";
|
|
2015
|
-
for (const f of sorted) if (!existingImports.has(f)) {
|
|
2016
|
-
const varName = toCollectionVarName(f);
|
|
2017
|
-
newImports += `import ${varName} from ${quote(`./${f}`)};\n`;
|
|
2018
|
-
newElements += ` ${varName},\n`;
|
|
2019
|
-
}
|
|
2020
|
-
if (!newImports) return existingContent;
|
|
2021
|
-
const importRegex = /import\s+.*?;/g;
|
|
2022
|
-
let lastImportMatch;
|
|
2023
|
-
let match;
|
|
2024
|
-
while ((match = importRegex.exec(existingContent)) !== null) lastImportMatch = match;
|
|
2025
|
-
let contentWithImports = existingContent;
|
|
2026
|
-
if (lastImportMatch) {
|
|
2027
|
-
const pos = lastImportMatch.index + lastImportMatch[0].length;
|
|
2028
|
-
contentWithImports = existingContent.slice(0, pos) + "\n" + newImports.trimEnd() + existingContent.slice(pos);
|
|
2029
|
-
} else contentWithImports = newImports + "\n" + existingContent;
|
|
2030
|
-
return contentWithImports.replace(/export\s+const\s+collections\s*=\s*\[([\s\S]*?)\];/, (fullMatch, arrayContent) => {
|
|
2031
|
-
let mergedArray = arrayContent.trimEnd();
|
|
2032
|
-
if (mergedArray && !mergedArray.endsWith(",")) mergedArray += ",";
|
|
2033
|
-
if (mergedArray) mergedArray += "\n";
|
|
2034
|
-
mergedArray += newElements.trimEnd();
|
|
2035
|
-
return `export const collections = [\n ${mergedArray.trim()}\n];`;
|
|
2036
|
-
});
|
|
2037
|
-
}
|
|
2038
|
-
/**
|
|
2039
|
-
* Safely extract the host portion of a database URL for logging.
|
|
2040
|
-
*/
|
|
2041
|
-
function safeHostFromUrl(url) {
|
|
2042
|
-
return url.includes("@") ? url.split("@")[1] : "(local connection)";
|
|
2043
|
-
}
|
|
2044
|
-
//#endregion
|
|
2045
|
-
export { humanize as _, compositeKeySkipReason as a, generateIndexContent as c, mergeIndexContent as d, safeHostFromUrl as f, mapPgType as g, lookupCandidates as h, buildTablesMap as i, getIconForTable as l, classifyTables as m, COMMON_PACKAGE as n, describeRlsOffTables as o, singularize as p, buildEnumMap as r, generateCollectionFile as s, ADMIN_TYPES_PACKAGE as t, identifyJoinTables as u };
|
|
2046
|
-
|
|
2047
|
-
//# sourceMappingURL=introspect-db-logic-DWqAEURB.js.map
|