@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,12 +1,11 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import { DEFAULT_FUZZY_THRESHOLD, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT,
|
|
4
|
-
import {
|
|
5
|
-
import { toPostgresIdentifier, toSnakeCase } from "@rebasepro/utils";
|
|
3
|
+
import { DEFAULT_FUZZY_THRESHOLD, DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE, DEFAULT_SEARCH_MODE, DEFAULT_SEARCH_WEIGHT, columnTypeLabel, isTextColumnType } from "@rebasepro/types";
|
|
4
|
+
import { toPostgresIdentifier } from "@rebasepro/utils";
|
|
6
5
|
import { createHash } from "node:crypto";
|
|
7
6
|
//#region src/schema/search-column.ts
|
|
8
7
|
/**
|
|
9
|
-
* The one place a
|
|
8
|
+
* The one place a table's `search` block becomes SQL.
|
|
10
9
|
*
|
|
11
10
|
* Four things describe a Postgres table in this codebase — the DDL generator,
|
|
12
11
|
* the Drizzle schema generator, the runtime table builder for BaaS mode, and
|
|
@@ -66,82 +65,6 @@ var SearchConfigError = class extends Error {
|
|
|
66
65
|
this.name = "SearchConfigError";
|
|
67
66
|
}
|
|
68
67
|
};
|
|
69
|
-
/** The `search` block of a collection, or undefined when it has none. */
|
|
70
|
-
var getSearchConfig = (collection) => isPostgresCollectionConfig(collection) ? collection.search : void 0;
|
|
71
|
-
/**
|
|
72
|
-
* Refuse a `search` block on a collection this engine does not store.
|
|
73
|
-
*
|
|
74
|
-
* The type only permits one on a `PostgresCollectionConfig`, so TypeScript
|
|
75
|
-
* already stops the ordinary case. This catches the rest — a JS config, a cast,
|
|
76
|
-
* a collection whose `engine` was changed after the block was written — because
|
|
77
|
-
* the alternative is the exact failure the block exists to prevent: a developer
|
|
78
|
-
* who declared what to index, saw no error, and got the substring fallback.
|
|
79
|
-
*
|
|
80
|
-
* Called with *every* collection, before the Postgres ones are filtered out.
|
|
81
|
-
*/
|
|
82
|
-
var assertSearchIsPostgresOnly = (collections) => {
|
|
83
|
-
for (const collection of collections) {
|
|
84
|
-
if (isPostgresCollectionConfig(collection)) continue;
|
|
85
|
-
if (!collection.search) continue;
|
|
86
|
-
const engine = collection.engine ?? "non-postgres";
|
|
87
|
-
throw new SearchConfigError(`${collection.slug}.search: full-text search is a Postgres feature, and this collection is served by \`${engine}\`. Remove the block — it would otherwise look configured while \`.search()\` kept using the default substring match.`);
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
var columnNameOf = (propName, prop) => prop && "columnName" in prop && typeof prop.columnName === "string" ? prop.columnName : toSnakeCase(propName);
|
|
91
|
-
/**
|
|
92
|
-
* Classify a property for search purposes.
|
|
93
|
-
*
|
|
94
|
-
* Deliberately narrower than the schema plan's `PgType`: search only cares
|
|
95
|
-
* whether a value reaches text, and the mapping from property to *physical*
|
|
96
|
-
* type is asserted against the plan in the contract test rather than duplicated
|
|
97
|
-
* here.
|
|
98
|
-
*
|
|
99
|
-
* Returns null for anything that is not text-bearing, which the caller turns
|
|
100
|
-
* into a boot error naming the property.
|
|
101
|
-
*/
|
|
102
|
-
var classify = (prop) => {
|
|
103
|
-
switch (prop.type) {
|
|
104
|
-
case "string": {
|
|
105
|
-
const sp = prop;
|
|
106
|
-
if (sp.enum) return {
|
|
107
|
-
kind: "text",
|
|
108
|
-
reason: "enum"
|
|
109
|
-
};
|
|
110
|
-
if (sp.isId === "uuid" || sp.columnType === "uuid") return {
|
|
111
|
-
kind: "text",
|
|
112
|
-
reason: "uuid"
|
|
113
|
-
};
|
|
114
|
-
return { kind: "text" };
|
|
115
|
-
}
|
|
116
|
-
case "map":
|
|
117
|
-
if (prop.columnType === "json") return {
|
|
118
|
-
kind: "jsonb",
|
|
119
|
-
reason: "json"
|
|
120
|
-
};
|
|
121
|
-
return { kind: "jsonb" };
|
|
122
|
-
case "array": {
|
|
123
|
-
const ap = prop;
|
|
124
|
-
let colType = ap.columnType;
|
|
125
|
-
if (!colType && ap.of && !Array.isArray(ap.of)) {
|
|
126
|
-
const of = ap.of;
|
|
127
|
-
if (of.type === "string") colType = "text[]";
|
|
128
|
-
else if (of.type === "number") colType = of.validation?.integer ? "integer[]" : "numeric[]";
|
|
129
|
-
else if (of.type === "boolean") colType = "boolean[]";
|
|
130
|
-
}
|
|
131
|
-
if (colType === "text[]") return { kind: "text_array" };
|
|
132
|
-
if (colType === "json") return {
|
|
133
|
-
kind: "jsonb",
|
|
134
|
-
reason: "json"
|
|
135
|
-
};
|
|
136
|
-
if (colType === "integer[]" || colType === "boolean[]" || colType === "numeric[]") return {
|
|
137
|
-
kind: "text_array",
|
|
138
|
-
reason: "non_text_array"
|
|
139
|
-
};
|
|
140
|
-
return { kind: "jsonb" };
|
|
141
|
-
}
|
|
142
|
-
default: return null;
|
|
143
|
-
}
|
|
144
|
-
};
|
|
145
68
|
var normalize = (inner, unaccent) => unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;
|
|
146
69
|
/** SQL reading one field as plain text, before normalization. */
|
|
147
70
|
var rawTextSql = (field) => {
|
|
@@ -159,22 +82,22 @@ var quote = (v) => `'${v.replace(/'/g, "''")}'`;
|
|
|
159
82
|
* a guess again, and the failure — a search that returns nothing for content
|
|
160
83
|
* that is plainly in the row — is invisible from the outside.
|
|
161
84
|
*/
|
|
162
|
-
var resolveField = (entry,
|
|
85
|
+
var resolveField = (entry, source, cfg) => {
|
|
163
86
|
const path = typeof entry === "string" ? entry : entry.path;
|
|
164
87
|
const weight = (typeof entry === "string" ? void 0 : entry.weight) ?? DEFAULT_SEARCH_WEIGHT;
|
|
165
|
-
const where = `${
|
|
166
|
-
if (!path || typeof path !== "string") throw new SearchConfigError(`${where}: every entry in \`fields\` needs a
|
|
88
|
+
const where = `${source.slug}.search`;
|
|
89
|
+
if (!path || typeof path !== "string") throw new SearchConfigError(`${where}: every entry in \`fields\` needs a column path.`);
|
|
167
90
|
const [head, ...rest] = path.split(".");
|
|
168
|
-
const
|
|
169
|
-
if (!
|
|
170
|
-
const classified =
|
|
171
|
-
if (!classified) throw new SearchConfigError(`${where}: "${path}" is a
|
|
91
|
+
const field = source.head(head);
|
|
92
|
+
if (!field) throw new SearchConfigError(`${where}: "${path}" starts at column "${head}", which this table does not declare. Known columns: ${source.knownKeys().join(", ")}.`);
|
|
93
|
+
const classified = field.classified;
|
|
94
|
+
if (!classified) throw new SearchConfigError(`${where}: "${path}" is a ${field.label}, which holds no text to search. Searchable kinds are text, text arrays and JSON documents (or a path inside one).`);
|
|
172
95
|
if (classified.reason === "enum") throw new SearchConfigError(`${where}: "${path}" is an enum. Enums are a fixed vocabulary — filter on them with \`where\` instead, which is exact and uses an index.`);
|
|
173
96
|
if (classified.reason === "uuid") throw new SearchConfigError(`${where}: "${path}" is a UUID column. Look it up by id rather than searching it.`);
|
|
174
|
-
if (classified.reason === "json") throw new SearchConfigError(`${where}: "${path}" is a \`json\` column, and the cast from \`json\` to \`jsonb\` is not immutable, so it cannot feed a generated column. Declare
|
|
175
|
-
if (classified.reason === "non_text_array") throw new SearchConfigError(`${where}: "${path}" is an array of numbers or booleans. Only
|
|
176
|
-
if (rest.length > 0 && classified.kind !== "jsonb") throw new SearchConfigError(`${where}: "${path}" addresses a path inside "${head}", but "${head}" is a
|
|
177
|
-
const column =
|
|
97
|
+
if (classified.reason === "json") throw new SearchConfigError(`${where}: "${path}" is a \`json\` column, and the cast from \`json\` to \`jsonb\` is not immutable, so it cannot feed a generated column. Declare it \`jsonb\` (the default) to search it.`);
|
|
98
|
+
if (classified.reason === "non_text_array") throw new SearchConfigError(`${where}: "${path}" is an array of numbers or booleans. Only a text array carries text to search.`);
|
|
99
|
+
if (rest.length > 0 && classified.kind !== "jsonb") throw new SearchConfigError(`${where}: "${path}" addresses a path inside "${head}", but "${head}" is a ${field.label}, not a JSON document. Only JSON documents have paths inside them.`);
|
|
100
|
+
const column = field.column;
|
|
178
101
|
const raw = rawTextSql({
|
|
179
102
|
column,
|
|
180
103
|
jsonPath: rest,
|
|
@@ -194,24 +117,76 @@ var resolveField = (entry, collection, cfg) => {
|
|
|
194
117
|
};
|
|
195
118
|
};
|
|
196
119
|
/**
|
|
197
|
-
*
|
|
120
|
+
* How a column reaches text, for search: the descriptor counterpart of
|
|
121
|
+
* {@link classify}. `null` for a column that holds no text (a number, a date,
|
|
122
|
+
* a geopoint document, a vector, bytes, a custom SQL type).
|
|
123
|
+
*/
|
|
124
|
+
var classifyColumnType = (column) => {
|
|
125
|
+
const type = column.type;
|
|
126
|
+
if (isTextColumnType(type)) return { kind: "text" };
|
|
127
|
+
switch (type.kind) {
|
|
128
|
+
case "enum": return {
|
|
129
|
+
kind: "text",
|
|
130
|
+
reason: "enum"
|
|
131
|
+
};
|
|
132
|
+
case "uuid": return {
|
|
133
|
+
kind: "text",
|
|
134
|
+
reason: "uuid"
|
|
135
|
+
};
|
|
136
|
+
case "json": return {
|
|
137
|
+
kind: "jsonb",
|
|
138
|
+
reason: "json"
|
|
139
|
+
};
|
|
140
|
+
case "jsonb": return column.semantic === "geopoint" ? null : { kind: "jsonb" };
|
|
141
|
+
case "array": {
|
|
142
|
+
const element = type.of;
|
|
143
|
+
if (isTextColumnType(element)) return { kind: "text_array" };
|
|
144
|
+
if (element.kind === "integer" || element.kind === "boolean" || element.kind === "numeric") return {
|
|
145
|
+
kind: "text_array",
|
|
146
|
+
reason: "non_text_array"
|
|
147
|
+
};
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
default: return null;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
/**
|
|
154
|
+
* The search column a table's `search` block asks for, or `undefined` when
|
|
155
|
+
* it declares none — read from the table descriptor. What the planner calls.
|
|
198
156
|
*
|
|
199
|
-
* Throws {@link SearchConfigError} on a
|
|
200
|
-
*
|
|
201
|
-
* worse than one that refuses.
|
|
157
|
+
* Throws {@link SearchConfigError} on a block that cannot be honoured; the
|
|
158
|
+
* compiler refuses most of them first (`checkSearch`).
|
|
202
159
|
*/
|
|
203
|
-
var
|
|
204
|
-
const cfg =
|
|
160
|
+
var buildTableSearchColumnSpec = (table) => {
|
|
161
|
+
const cfg = table.search;
|
|
205
162
|
if (!cfg) return void 0;
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
163
|
+
return searchColumnSpecFrom(cfg, {
|
|
164
|
+
slug: table.slug,
|
|
165
|
+
schema: table.schema,
|
|
166
|
+
table: table.table,
|
|
167
|
+
head: (key) => {
|
|
168
|
+
const column = table.columns.find((candidate) => candidate.key === key);
|
|
169
|
+
if (!column) return void 0;
|
|
170
|
+
return {
|
|
171
|
+
column: column.column,
|
|
172
|
+
classified: classifyColumnType(column),
|
|
173
|
+
label: `\`${columnTypeLabel(column.type)}\` column`
|
|
174
|
+
};
|
|
175
|
+
},
|
|
176
|
+
knownKeys: () => table.columns.map((column) => column.key),
|
|
177
|
+
collides: (name) => table.columns.some((column) => column.key === name || column.column === name)
|
|
178
|
+
});
|
|
179
|
+
};
|
|
180
|
+
/** The spec, from a `search` block and the table it is declared on. */
|
|
181
|
+
var searchColumnSpecFrom = (cfg, source) => {
|
|
182
|
+
const { slug, schema, table } = source;
|
|
183
|
+
if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) throw new SearchConfigError(`${slug}.search: \`fields\` is empty. Name the columns to index, or remove the \`search\` block to keep the default ILIKE behaviour.`);
|
|
209
184
|
const column = cfg.column ?? DEFAULT_SEARCH_COLUMN;
|
|
210
|
-
if (
|
|
211
|
-
const fields = cfg.fields.map((entry) => resolveField(entry,
|
|
185
|
+
if (source.collides(column)) throw new SearchConfigError(`${slug}.search: the generated column "${column}" collides with a declared column of the same name. Set \`search.column\` to something else.`);
|
|
186
|
+
const fields = cfg.fields.map((entry) => resolveField(entry, source, cfg));
|
|
212
187
|
const seen = /* @__PURE__ */ new Set();
|
|
213
188
|
for (const f of fields) {
|
|
214
|
-
if (seen.has(f.path)) throw new SearchConfigError(`${
|
|
189
|
+
if (seen.has(f.path)) throw new SearchConfigError(`${slug}.search: "${f.path}" is listed twice.`);
|
|
215
190
|
seen.add(f.path);
|
|
216
191
|
}
|
|
217
192
|
const mode = cfg.mode ?? DEFAULT_SEARCH_MODE;
|
|
@@ -232,7 +207,7 @@ var buildSearchColumnSpec = (collection) => {
|
|
|
232
207
|
};
|
|
233
208
|
if (cfg.fuzzy) {
|
|
234
209
|
const fuzzyColumn = `${column}_text`;
|
|
235
|
-
if (
|
|
210
|
+
if (source.collides(fuzzyColumn)) throw new SearchConfigError(`${slug}.search: \`fuzzy\` needs the column "${fuzzyColumn}", which collides with a declared column. Set \`search.column\` to something else.`);
|
|
236
211
|
spec.fuzzy = {
|
|
237
212
|
column: fuzzyColumn,
|
|
238
213
|
expression: fields.map((f) => f.textSql).join(" || ' ' || "),
|
|
@@ -372,18 +347,13 @@ $rebase_search$;`;
|
|
|
372
347
|
*/
|
|
373
348
|
var searchIndexNames = (spec) => spec.fuzzy ? [spec.indexName, spec.fuzzy.indexName] : [spec.indexName];
|
|
374
349
|
/**
|
|
375
|
-
* The generated column names a
|
|
376
|
-
*
|
|
377
|
-
* These are physical columns on the table, so `SELECT *` returns them. They are
|
|
378
|
-
* an index in column form — a list of lexeme positions, or a concatenation of
|
|
379
|
-
* every searchable field on the row — and nothing outside the query planner has
|
|
380
|
-
* any use for them. Left in, every list response carries a second, larger copy
|
|
381
|
-
* of the row's text.
|
|
350
|
+
* The generated column names a table's search block adds, read from its
|
|
351
|
+
* descriptor: the search columns (`search_vector`, and the fuzzy column when there is one).
|
|
382
352
|
*/
|
|
383
|
-
var
|
|
353
|
+
var tableSearchColumnNames = (table) => {
|
|
384
354
|
let spec;
|
|
385
355
|
try {
|
|
386
|
-
spec =
|
|
356
|
+
spec = buildTableSearchColumnSpec(table);
|
|
387
357
|
} catch {
|
|
388
358
|
return [];
|
|
389
359
|
}
|
|
@@ -393,7 +363,7 @@ var searchColumnNames = (collection) => {
|
|
|
393
363
|
/**
|
|
394
364
|
* True for a column whose type only ever holds a search index.
|
|
395
365
|
*
|
|
396
|
-
* Independent of any
|
|
366
|
+
* Independent of any table declaration on purpose: an introspected database
|
|
397
367
|
* (BaaS mode) can carry a `tsvector` column this framework never created —
|
|
398
368
|
* Pagila's `film.fulltext` is the canonical one — and it should not be returned
|
|
399
369
|
* to callers either. `isDerivedIndexColumn` already keeps such a column out of
|
|
@@ -403,40 +373,7 @@ var isSearchIndexColumn = (column) => {
|
|
|
403
373
|
const sqlType = typeof column?.getSQLType === "function" ? column.getSQLType().toLowerCase() : "";
|
|
404
374
|
return sqlType === "tsvector" || sqlType === "tsquery";
|
|
405
375
|
};
|
|
406
|
-
/**
|
|
407
|
-
* A drizzle select projection over `table` with the search columns dropped.
|
|
408
|
-
*
|
|
409
|
-
* Returns undefined when nothing needs dropping, so the common case keeps using
|
|
410
|
-
* a plain `select()` and this stays invisible in the generated SQL.
|
|
411
|
-
*/
|
|
412
|
-
var visibleColumnProjection = (tableColumns, collection) => {
|
|
413
|
-
const excluded = excludedColumnNames(tableColumns, collection);
|
|
414
|
-
if (!tableColumns || excluded.length === 0) return void 0;
|
|
415
|
-
const projection = {};
|
|
416
|
-
for (const [name, column] of Object.entries(tableColumns)) if (!excluded.includes(name)) projection[name] = column;
|
|
417
|
-
return projection;
|
|
418
|
-
};
|
|
419
|
-
/** The same exclusion as a drizzle `db.query` `columns` denylist. */
|
|
420
|
-
var hiddenColumnsOption = (tableColumns, collection) => {
|
|
421
|
-
const excluded = excludedColumnNames(tableColumns, collection);
|
|
422
|
-
if (excluded.length === 0) return void 0;
|
|
423
|
-
return Object.fromEntries(excluded.map((name) => [name, false]));
|
|
424
|
-
};
|
|
425
|
-
/**
|
|
426
|
-
* The columns to keep out of a response, by name.
|
|
427
|
-
*
|
|
428
|
-
* `tableColumns` is whatever `getTableColumns` returned, which is `undefined`
|
|
429
|
-
* for anything that is not a real drizzle table — a stub in a test, a derived
|
|
430
|
-
* or nested path with no table behind it. Nothing to exclude is the right
|
|
431
|
-
* answer there, and it has to be an answer rather than a throw: this runs on
|
|
432
|
-
* the read path of every collection, opted in or not.
|
|
433
|
-
*/
|
|
434
|
-
var excludedColumnNames = (tableColumns, collection) => {
|
|
435
|
-
if (!tableColumns || typeof tableColumns !== "object") return [];
|
|
436
|
-
const byName = new Set(collection ? searchColumnNames(collection) : []);
|
|
437
|
-
return Object.keys(tableColumns).filter((name) => byName.has(name) || isSearchIndexColumn(tableColumns[name]));
|
|
438
|
-
};
|
|
439
376
|
//#endregion
|
|
440
|
-
export {
|
|
377
|
+
export { fuzzyColumnDefinition as a, searchColumnStamps as c, searchHelperFunctions as d, searchIndexNames as f, tableSearchColumnNames as h, buildTableSearchColumnSpec as i, searchColumnTypeSql as l, searchStampGuards as m, SEARCH_TEXT_FN as n, isSearchIndexColumn as o, searchIndexStatements as p, SEARCH_UNACCENT_FN as r, searchColumnDefinition as s, SEARCH_STAMP_PREFIX as t, searchExtensionStatements as u };
|
|
441
378
|
|
|
442
|
-
//# sourceMappingURL=search-column-
|
|
379
|
+
//# sourceMappingURL=search-column-BO-WND-B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"search-column-BO-WND-B.js","names":[],"sources":["../src/schema/search-column.ts"],"sourcesContent":["/**\n * The one place a table's `search` block becomes SQL.\n *\n * Four things describe a Postgres table in this codebase — the DDL generator,\n * the Drizzle schema generator, the runtime table builder for BaaS mode, and\n * the boot-time schema ensure — and each of them has, at some point, described\n * a column differently from the others. The `varchar(255)` note in\n * `generate-postgres-ddl-logic` is one such scar: the same property produced a\n * capped column down one path and an uncapped one down the other, and nothing\n * failed until a user hit the cap.\n *\n * So the search column is not implemented four times. It is computed once,\n * here, and every generator renders the same {@link SearchColumnSpec}. There is\n * a test asserting exactly that (`search-column-contract.test.ts`); the point of\n * this module is that the test has something to assert *about*.\n *\n * ## Why the expressions look the way they do\n *\n * A `GENERATED ALWAYS AS … STORED` expression must be strictly IMMUTABLE, and\n * Postgres is stricter here than intuition. Verified against PostgreSQL 18:\n *\n * | expression | immutable |\n * |-----------------------------------------|-----------|\n * | `to_tsvector('spanish', col)` | yes |\n * | `to_tsvector(col)` (1-arg) | **no** — depends on `default_text_search_config` |\n * | `array_to_string(col, ' ')` | **no** |\n * | `col::text` on `text[]` | **no** |\n * | `to_jsonb(col)` | **no** |\n * | `unaccent(col)` | **no** — dictionary lookup is STABLE |\n * | `jsonb_to_tsvector('spanish', j, '[\"string\"]')` | yes |\n * | `setweight(...) || setweight(...)` | yes |\n *\n * Three of the four things a real search column needs are therefore unavailable\n * directly, which is why {@link searchHelperFunctions} exists: each wraps a\n * stable built-in in an SQL function declared IMMUTABLE. That declaration is a\n * promise, and it is a true one for these three — array joining, JSON string\n * extraction and accent folding are all deterministic for a given input; the\n * built-ins are marked stable only because they must account for element types\n * and dictionaries in general.\n *\n * The alternative was to skip `unaccent` and text arrays entirely. That is not\n * a real option in an accented language: Postgres stems `auditoría` to\n * `auditor` and `auditoria` to `auditori` — *different lexemes* — so a query\n * typed without accents misses every row that carries them.\n */\nimport {\n SearchConfig,\n SearchField,\n SearchMode,\n SearchWeight,\n DEFAULT_SEARCH_COLUMN,\n DEFAULT_SEARCH_MODE,\n DEFAULT_SEARCH_LANGUAGE,\n DEFAULT_SEARCH_WEIGHT,\n DEFAULT_FUZZY_THRESHOLD,\n columnTypeLabel,\n isTextColumnType,\n type ColumnDescriptor,\n type ColumnType,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport { createHash } from \"node:crypto\";\nimport { toSnakeCase, toPostgresIdentifier } from \"@rebasepro/utils\";\n\n/** Schema-qualified so a collection outside `public` still resolves them. */\nconst HELPER_SCHEMA = \"public\";\n\n/**\n * Names of the helper functions. Frozen: they are recorded in the stored\n * generation expression of every search column ever created, so renaming one\n * orphans every table that already has a search column.\n */\nexport const SEARCH_TEXT_FN = `${HELPER_SCHEMA}.rebase_search_text`;\nexport const SEARCH_UNACCENT_FN = `${HELPER_SCHEMA}.rebase_search_unaccent`;\n\n/** How a declared path reaches text, which decides the SQL that extracts it. */\ntype FieldKind = \"text\" | \"text_array\" | \"jsonb\";\n\n/** One resolved field: where it lives, how to read it, what it is worth. */\nexport interface ResolvedSearchField {\n /** The path exactly as the author wrote it, for error messages. */\n path: string;\n /** The physical column the path starts at. */\n column: string;\n /** Dotted remainder addressed inside a JSONB column, if any. */\n jsonPath: string[];\n kind: FieldKind;\n weight: SearchWeight;\n /** The `setweight(to_tsvector(…), 'X')` term this field contributes. */\n sql: string;\n /** The plain-text term this field contributes, for the fuzzy column. */\n textSql: string;\n /**\n * The same text with accents folded **unconditionally**, for the substring\n * half of {@link SearchMode} `\"hybrid\"`.\n *\n * Separate from {@link textSql} rather than replacing it, and that\n * separation is the whole migration story for `mode`. `textSql` feeds the\n * *stored* generated columns, so changing it changes their generation\n * expression, which changes the fingerprint, which makes the next boot\n * refuse (see `searchStampGuards`). This one is only ever interpolated into\n * a WHERE clause, so a collection can switch to `\"hybrid\"` — and gain\n * accent folding on the substring half — without rebuilding a column or\n * taking an ACCESS EXCLUSIVE lock.\n */\n foldedTextSql: string;\n}\n\n/** Everything the generators need to render one collection's search column. */\nexport interface SearchColumnSpec {\n schema: string;\n table: string;\n /** The generated `tsvector` column. */\n column: string;\n language: string;\n unaccent: boolean;\n /**\n * How the query side matches. Deliberately absent from\n * {@link SearchColumnSpec.expression} and from every fingerprint: it\n * describes the WHERE clause, not the column.\n */\n mode: SearchMode;\n fields: ResolvedSearchField[];\n /** Body of `GENERATED ALWAYS AS ( … ) STORED` for the tsvector column. */\n expression: string;\n indexName: string;\n /** Extensions that must exist before the column can be created. */\n extensions: string[];\n fuzzy?: {\n column: string;\n expression: string;\n indexName: string;\n threshold: number;\n };\n}\n\n/** Raised when a `search` block names something that cannot be searched. */\nexport class SearchConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SearchConfigError\";\n }\n}\n\nconst normalize = (inner: string, unaccent: boolean): string =>\n unaccent ? `${SEARCH_UNACCENT_FN}(${inner})` : inner;\n\n/** SQL reading one field as plain text, before normalization. */\nconst rawTextSql = (field: { column: string; jsonPath: string[]; kind: FieldKind }): string => {\n const col = `\"${field.column}\"`;\n if (field.kind === \"text\") return `coalesce(${col}, '')`;\n if (field.kind === \"text_array\") return `${SEARCH_TEXT_FN}(coalesce(${col}, '{}'::text[]))`;\n // JSONB, optionally addressed at a path inside the document.\n const target = field.jsonPath.length === 0\n ? col\n : field.jsonPath.length === 1\n ? `${col} -> ${quote(field.jsonPath[0])}`\n : `${col} #> ${quote(`{${field.jsonPath.join(\",\")}}`)}`;\n return `${SEARCH_TEXT_FN}(coalesce(${target}, '{}'::jsonb))`;\n};\n\nconst quote = (v: string): string => `'${v.replace(/'/g, \"''\")}'`;\n\n/**\n * What a `search` field's first segment names, as the spec builder reads it:\n * the column it starts at, how that column reaches text (`null`: it does\n * not), and how a refusal names it.\n */\ninterface SearchFieldHead {\n column: string;\n classified: { kind: FieldKind; reason?: string } | null;\n /** `\\`text\\` column`, `\\`integer[]\\` column` — for a refusal. */\n label: string;\n}\n\n/** The table a spec is built for. */\ninterface SearchSpecSource {\n slug: string;\n schema: string;\n table: string;\n /** The field a path starts at, or `undefined` when the table declares none of that key. */\n head(key: string): SearchFieldHead | undefined;\n /** Every key a path may start at, for a refusal. */\n knownKeys(): string[];\n /** Whether a generated column of this name would collide with a declared one. */\n collides(column: string): boolean;\n}\n\n/**\n * Resolve and validate one declared field path.\n *\n * A path that does not resolve throws. The whole point of an explicit block is\n * that the author knows what is indexed; a silently dropped field would make it\n * a guess again, and the failure — a search that returns nothing for content\n * that is plainly in the row — is invisible from the outside.\n */\nconst resolveField = (\n entry: string | SearchField,\n source: SearchSpecSource,\n cfg: SearchConfig\n): ResolvedSearchField => {\n const path = typeof entry === \"string\" ? entry : entry.path;\n const weight = (typeof entry === \"string\" ? undefined : entry.weight) ?? DEFAULT_SEARCH_WEIGHT;\n const where = `${source.slug}.search`;\n\n if (!path || typeof path !== \"string\") {\n throw new SearchConfigError(`${where}: every entry in \\`fields\\` needs a column path.`);\n }\n\n const [head, ...rest] = path.split(\".\");\n const field = source.head(head);\n if (!field) {\n const known = source.knownKeys().join(\", \");\n throw new SearchConfigError(\n `${where}: \"${path}\" starts at column \"${head}\", which this table does not declare. Known columns: ${known}.`\n );\n }\n\n const classified = field.classified;\n if (!classified) {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a ${field.label}, which holds no text to search. ` +\n \"Searchable kinds are text, text arrays and JSON documents (or a path inside one).\"\n );\n }\n if (classified.reason === \"enum\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an enum. Enums are a fixed vocabulary — filter on them with \\`where\\` instead, which is exact and uses an index.`\n );\n }\n if (classified.reason === \"uuid\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a UUID column. Look it up by id rather than searching it.`\n );\n }\n if (classified.reason === \"json\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is a \\`json\\` column, and the cast from \\`json\\` to \\`jsonb\\` is not immutable, so it cannot feed a generated column. Declare it \\`jsonb\\` (the default) to search it.`\n );\n }\n if (classified.reason === \"non_text_array\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" is an array of numbers or booleans. Only a text array carries text to search.`\n );\n }\n\n if (rest.length > 0 && classified.kind !== \"jsonb\") {\n throw new SearchConfigError(\n `${where}: \"${path}\" addresses a path inside \"${head}\", but \"${head}\" is a ${field.label}, not a JSON document. Only JSON documents have paths inside them.`\n );\n }\n\n const column = field.column;\n const resolved = { column, jsonPath: rest, kind: classified.kind };\n const raw = rawTextSql(resolved);\n const textSql = normalize(raw, cfg.unaccent === true);\n const language = cfg.language ?? DEFAULT_SEARCH_LANGUAGE;\n\n return {\n path,\n column,\n jsonPath: rest,\n kind: classified.kind,\n weight,\n sql: `setweight(to_tsvector(${quote(language)}, ${textSql}), ${quote(weight)})`,\n textSql,\n foldedTextSql: normalize(raw, true)\n };\n};\n\n/**\n * How a column reaches text, for search: the descriptor counterpart of\n * {@link classify}. `null` for a column that holds no text (a number, a date,\n * a geopoint document, a vector, bytes, a custom SQL type).\n */\nconst classifyColumnType = (column: ColumnDescriptor): { kind: FieldKind; reason?: string } | null => {\n const type: ColumnType = column.type;\n if (isTextColumnType(type)) return { kind: \"text\" };\n switch (type.kind) {\n case \"enum\": return { kind: \"text\", reason: \"enum\" };\n case \"uuid\": return { kind: \"text\", reason: \"uuid\" };\n case \"json\": return { kind: \"jsonb\", reason: \"json\" };\n case \"jsonb\": return column.semantic === \"geopoint\" ? null : { kind: \"jsonb\" };\n case \"array\": {\n const element = type.of;\n if (isTextColumnType(element)) return { kind: \"text_array\" };\n if (element.kind === \"integer\" || element.kind === \"boolean\" || element.kind === \"numeric\") {\n return { kind: \"text_array\", reason: \"non_text_array\" };\n }\n return null;\n }\n default: return null;\n }\n};\n\n/**\n * The search column a table's `search` block asks for, or `undefined` when\n * it declares none — read from the table descriptor. What the planner calls.\n *\n * Throws {@link SearchConfigError} on a block that cannot be honoured; the\n * compiler refuses most of them first (`checkSearch`).\n */\nexport const buildTableSearchColumnSpec = (table: TableDescriptor): SearchColumnSpec | undefined => {\n const cfg = table.search;\n if (!cfg) return undefined;\n return searchColumnSpecFrom(cfg, {\n slug: table.slug,\n schema: table.schema,\n table: table.table,\n head: key => {\n const column = table.columns.find(candidate => candidate.key === key);\n if (!column) return undefined;\n return { column: column.column, classified: classifyColumnType(column), label: `\\`${columnTypeLabel(column.type)}\\` column` };\n },\n knownKeys: () => table.columns.map(column => column.key),\n collides: name => table.columns.some(column => column.key === name || column.column === name)\n });\n};\n\n/** The spec, from a `search` block and the table it is declared on. */\nconst searchColumnSpecFrom = (cfg: SearchConfig, source: SearchSpecSource): SearchColumnSpec => {\n const { slug, schema, table } = source;\n if (!Array.isArray(cfg.fields) || cfg.fields.length === 0) {\n throw new SearchConfigError(\n `${slug}.search: \\`fields\\` is empty. Name the columns to index, or remove the \\`search\\` block to keep the default ILIKE behaviour.`\n );\n }\n\n const column = cfg.column ?? DEFAULT_SEARCH_COLUMN;\n\n if (source.collides(column)) {\n throw new SearchConfigError(\n `${slug}.search: the generated column \"${column}\" collides with a declared column of the same name. Set \\`search.column\\` to something else.`\n );\n }\n\n const fields = cfg.fields.map(entry => resolveField(entry, source, cfg));\n\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.path)) {\n throw new SearchConfigError(`${slug}.search: \"${f.path}\" is listed twice.`);\n }\n seen.add(f.path);\n }\n\n const mode = cfg.mode ?? DEFAULT_SEARCH_MODE;\n\n const extensions: string[] = [];\n // `hybrid` folds accents on its substring half whatever `unaccent` says, so\n // it needs the dictionary and the helper even on a block that never asked\n // for folding in the stored column. Both statements are idempotent, which\n // is what keeps turning the mode on out of the column-rebuild business.\n if (cfg.unaccent || mode === \"hybrid\") extensions.push(\"unaccent\");\n if (cfg.fuzzy) extensions.push(\"pg_trgm\");\n\n const spec: SearchColumnSpec = {\n schema,\n table,\n column,\n language: cfg.language ?? DEFAULT_SEARCH_LANGUAGE,\n unaccent: cfg.unaccent === true,\n mode,\n fields,\n expression: fields.map(f => f.sql).join(\" || \"),\n indexName: toPostgresIdentifier(`${table}_${column}_gin`),\n extensions\n };\n\n if (cfg.fuzzy) {\n const fuzzyColumn = `${column}_text`;\n if (source.collides(fuzzyColumn)) {\n throw new SearchConfigError(\n `${slug}.search: \\`fuzzy\\` needs the column \"${fuzzyColumn}\", which collides with a declared column. Set \\`search.column\\` to something else.`\n );\n }\n spec.fuzzy = {\n column: fuzzyColumn,\n // Concatenated with spaces so a trigram never spans two fields.\n expression: fields.map(f => f.textSql).join(\" || ' ' || \"),\n indexName: toPostgresIdentifier(`${table}_${fuzzyColumn}_trgm`),\n threshold: cfg.fuzzyThreshold ?? DEFAULT_FUZZY_THRESHOLD\n };\n }\n\n return spec;\n};\n\n/**\n * The IMMUTABLE wrappers the generated expressions call.\n *\n * `CREATE OR REPLACE` so a boot against an existing database is a no-op rather\n * than an error, and idempotent for the same reason every other boot-time DDL\n * statement here is.\n *\n * The bodies are stable built-ins wrapped in an immutable promise — see the\n * module comment for why that promise is sound. `STRICT` matters: it makes NULL\n * in mean NULL out without executing the body, which is what the `coalesce` at\n * each call site then absorbs.\n */\nexport const searchHelperFunctions = (spec: SearchColumnSpec): string[] => {\n const statements: string[] = [\n // text[] → \" \"-joined text.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(text[]) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT array_to_string($1, ' ') $$;`,\n // jsonb → every string value at or below the node, space-joined. Keys\n // are not values: indexing them would make `certifications` itself a\n // search term on every row that has the field at all.\n `CREATE OR REPLACE FUNCTION ${SEARCH_TEXT_FN}(jsonb) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT coalesce(string_agg(v, ' '), '')\\n` +\n ` FROM jsonb_array_elements_text(jsonb_path_query_array($1, 'strict $.**?(@.type() == \"string\")')) AS v $$;`\n ];\n if (spec.unaccent || spec.mode === \"hybrid\") {\n // The two-argument form with an explicit dictionary is the one that can\n // honestly be called immutable: the single-argument form resolves the\n // dictionary through the current search_path at call time.\n statements.push(\n `CREATE OR REPLACE FUNCTION ${SEARCH_UNACCENT_FN}(text) RETURNS text\\n` +\n ` LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS\\n` +\n ` $$ SELECT ${HELPER_SCHEMA}.unaccent('${HELPER_SCHEMA}.unaccent'::regdictionary, $1) $$;`\n );\n }\n return statements;\n};\n\n/**\n * `CREATE EXTENSION` statements the spec's expressions depend on.\n *\n * `WITH SCHEMA public` is load-bearing, not tidiness. An unqualified\n * `CREATE EXTENSION` installs into the first schema on `search_path`, which\n * defaults to `\"$user\", public` — and the scaffold's database role is named\n * `rebase`, the same as the schema the generator creates one statement earlier.\n * So the moment that schema exists, `CREATE EXTENSION unaccent` puts the\n * dictionary in `rebase`, and every reference to `public.unaccent` below fails\n * with \"text search dictionary does not exist\". Observed, not theorised.\n */\nexport const searchExtensionStatements = (spec: SearchColumnSpec): string[] =>\n spec.extensions.map(e => `CREATE EXTENSION IF NOT EXISTS ${e} WITH SCHEMA ${HELPER_SCHEMA};`);\n\n/**\n * Everything after the column name — the type and the generation expression.\n *\n * Split out because four emitters need it and only two of them have a place to\n * put the name: `CREATE TABLE` and `ADD COLUMN` write `\"col\" <this>`, while the\n * schema plan carries it as the column's SQL definition and the boot-time\n * rebuild statement interpolates it on its own.\n */\nexport const searchColumnTypeSql = (expression: string, kind: \"tsvector\" | \"text\"): string =>\n `${kind} GENERATED ALWAYS AS (${expression}) STORED`;\n\n/** The column definition as it appears inside `CREATE TABLE`. */\nexport const searchColumnDefinition = (spec: SearchColumnSpec): string =>\n `\"${spec.column}\" ${searchColumnTypeSql(spec.expression, \"tsvector\")}`;\n\n/** The fuzzy column definition, when the spec asks for one. */\nexport const fuzzyColumnDefinition = (spec: SearchColumnSpec): string | undefined =>\n spec.fuzzy ? `\"${spec.fuzzy.column}\" ${searchColumnTypeSql(spec.fuzzy.expression, \"text\")}` : undefined;\n\n/**\n * Index statements for the spec.\n *\n * `CONCURRENTLY` is deliberately *not* used here. This form is emitted into a\n * SQL file replayed as one unit — a migration, or `search.sql` — where a\n * concurrent build is not allowed. The boot-time ensure path runs statement by\n * statement against tables that are live and populated, and uses the\n * concurrent form instead; see `ensureSearchColumns`.\n */\nexport const searchIndexStatements = (spec: SearchColumnSpec): string[] => {\n const statements = [\n `CREATE INDEX IF NOT EXISTS \"${spec.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.column}\");`\n ];\n if (spec.fuzzy) {\n statements.push(\n // The operator class is resolved through `search_path` like any\n // other object, so it is qualified for the same reason the\n // extension is installed explicitly.\n `CREATE INDEX IF NOT EXISTS \"${spec.fuzzy.indexName}\" ON \"${spec.schema}\".\"${spec.table}\" USING GIN (\"${spec.fuzzy.column}\" ${HELPER_SCHEMA}.gin_trgm_ops);`\n );\n }\n return statements;\n};\n\n// ── Telling a changed `search` block from an unchanged one ──────────────────\n\n/**\n * Marker on the comment of every generated search column this module creates.\n *\n * Versioned because the fingerprint below is only comparable against itself: a\n * future change to how it is computed has to read as \"not stamped by this\n * version\" rather than as drift on every existing column.\n */\nexport const SEARCH_STAMP_PREFIX = \"rebase:search:v1:\";\n\n/**\n * A stable fingerprint of one generated column's expression.\n *\n * Why a stamp rather than reading the expression back: Postgres stores a\n * generated column's expression *parsed*, and hands it back deparsed — casts\n * made explicit, identifiers requoted, schema qualifications added or dropped\n * according to `search_path`. Comparing that text to the text we generated\n * would report drift on wording, and this comparison decides whether a boot\n * refuses, so a false positive is an outage. The stamp is written by the same\n * code that writes the column, so equality means what it says.\n */\nexport const searchExpressionFingerprint = (expression: string): string =>\n `${SEARCH_STAMP_PREFIX}${createHash(\"sha256\").update(expression).digest(\"hex\").slice(0, 16)}`;\n\n/** One generated column, with the fingerprint that identifies its expression. */\nexport interface SearchColumnStamp {\n column: string;\n /** The expression the column is generated from. */\n expression: string;\n fingerprint: string;\n /** `COMMENT ON COLUMN …`, which is where the fingerprint is recorded. */\n sql: string;\n}\n\n/**\n * The stamps for a spec's generated columns — one per column, never shared.\n *\n * Per column on purpose: turning `fuzzy` on adds a second column and changes\n * nothing about the first, and a spec-wide fingerprint would report the\n * untouched `tsvector` column as drifted and refuse a boot over a change that\n * is purely additive.\n */\nexport const searchColumnStamps = (spec: SearchColumnSpec): SearchColumnStamp[] => {\n const stamp = (column: string, expression: string): SearchColumnStamp => {\n const fingerprint = searchExpressionFingerprint(expression);\n return {\n column,\n expression,\n fingerprint,\n sql: `COMMENT ON COLUMN \"${spec.schema}\".\"${spec.table}\".\"${column}\" IS ${quote(fingerprint)};`\n };\n };\n const stamps = [stamp(spec.column, spec.expression)];\n if (spec.fuzzy) stamps.push(stamp(spec.fuzzy.column, spec.fuzzy.expression));\n return stamps;\n};\n\n/**\n * The same drift check as the boot ensure, for the SQL file.\n *\n * Needed because {@link searchColumnStamps} would otherwise *launder* drift on\n * the migration path: `ADD COLUMN IF NOT EXISTS` does nothing to a column that\n * exists, so a re-generated `search.sql` would stamp a stale column with the\n * new block's fingerprint and the next boot would find them in agreement.\n * Guarding first means the file refuses instead — `rebase db push` is attended,\n * and the operator reading the failure is the person who changed the block.\n */\nexport const searchStampGuards = (spec: SearchColumnSpec): string[] =>\n searchColumnStamps(spec).map(stamp => {\n const relation = quote(`\"${spec.schema}\".\"${spec.table}\"`);\n return `DO $rebase_search$\nDECLARE recorded text;\nBEGIN\n SELECT col_description(a.attrelid, a.attnum) INTO recorded\n FROM pg_attribute a\n WHERE a.attrelid = ${relation}::regclass AND a.attname = ${quote(stamp.column)} AND NOT a.attisdropped;\n IF recorded LIKE ${quote(`${SEARCH_STAMP_PREFIX}%`)} AND recorded <> ${quote(stamp.fingerprint)} THEN\n RAISE EXCEPTION 'Rebase: the search block for ${spec.schema}.${spec.table} changed after the generated column \"${stamp.column}\" was built (recorded %, expected ${stamp.fingerprint}). Postgres cannot alter a generated expression in place. Drop the column and re-apply this file — it rewrites the table and rebuilds the index: ALTER TABLE ${relation.slice(1, -1)} DROP COLUMN \"${stamp.column}\";', recorded;\n END IF;\nEND\n$rebase_search$;`;\n });\n\n/**\n * The index names the spec creates.\n *\n * Needed by name, not just by statement, so Atlas can be told to exclude them\n * from its diff — see `searchExcludePatterns`.\n */\nexport const searchIndexNames = (spec: SearchColumnSpec): string[] =>\n spec.fuzzy ? [spec.indexName, spec.fuzzy.indexName] : [spec.indexName];\n\n// ── Keeping the generated columns out of responses ──────────────────────────\n\n/**\n * The generated column names a table's search block adds, read from its\n * descriptor: the search columns (`search_vector`, and the fuzzy column when there is one).\n */\nexport const tableSearchColumnNames = (table: TableDescriptor): string[] => {\n let spec: SearchColumnSpec | undefined;\n try {\n spec = buildTableSearchColumnSpec(table);\n } catch {\n // A malformed block is reported at boot, loudly. A read is the wrong\n // place to raise it a second time, and returning the row without the\n // exclusion would be worse than returning it with.\n return [];\n }\n if (!spec) return [];\n return spec.fuzzy ? [spec.column, spec.fuzzy.column] : [spec.column];\n};\n\n/**\n * True for a column whose type only ever holds a search index.\n *\n * Independent of any table declaration on purpose: an introspected database\n * (BaaS mode) can carry a `tsvector` column this framework never created —\n * Pagila's `film.fulltext` is the canonical one — and it should not be returned\n * to callers either. `isDerivedIndexColumn` already keeps such a column out of\n * the *properties*; this keeps it out of the *rows*.\n */\nexport const isSearchIndexColumn = (column: { getSQLType?: () => string }): boolean => {\n const sqlType = typeof column?.getSQLType === \"function\" ? column.getSQLType().toLowerCase() : \"\";\n return sqlType === \"tsvector\" || sqlType === \"tsquery\";\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,IAAM,gBAAgB;;;;;;AAOtB,IAAa,iBAAiB,GAAG,cAAc;AAC/C,IAAa,qBAAqB,GAAG,cAAc;;AAgEnD,IAAa,oBAAb,cAAuC,MAAM;CACzC,YAAY,SAAiB;EACzB,MAAM,OAAO;EACb,KAAK,OAAO;CAChB;AACJ;AAEA,IAAM,aAAa,OAAe,aAC9B,WAAW,GAAG,mBAAmB,GAAG,MAAM,KAAK;;AAGnD,IAAM,cAAc,UAA2E;CAC3F,MAAM,MAAM,IAAI,MAAM,OAAO;CAC7B,IAAI,MAAM,SAAS,QAAQ,OAAO,YAAY,IAAI;CAClD,IAAI,MAAM,SAAS,cAAc,OAAO,GAAG,eAAe,YAAY,IAAI;CAO1E,OAAO,GAAG,eAAe,YALV,MAAM,SAAS,WAAW,IACnC,MACA,MAAM,SAAS,WAAW,IACtB,GAAG,IAAI,MAAM,MAAM,MAAM,SAAS,EAAE,MACpC,GAAG,IAAI,MAAM,MAAM,IAAI,MAAM,SAAS,KAAK,GAAG,EAAE,EAAE,IAChB;AAChD;AAEA,IAAM,SAAS,MAAsB,IAAI,EAAE,QAAQ,MAAM,IAAI,EAAE;;;;;;;;;AAmC/D,IAAM,gBACF,OACA,QACA,QACsB;CACtB,MAAM,OAAO,OAAO,UAAU,WAAW,QAAQ,MAAM;CACvD,MAAM,UAAU,OAAO,UAAU,WAAW,KAAA,IAAY,MAAM,WAAW;CACzE,MAAM,QAAQ,GAAG,OAAO,KAAK;CAE7B,IAAI,CAAC,QAAQ,OAAO,SAAS,UACzB,MAAM,I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7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The columns a caller may not read, taken out of what their SQL returned.
|
|
3
3
|
*
|
|
4
|
-
* Per-
|
|
4
|
+
* Per-column read rules (`.access({ read })`, and `.private()`, which is
|
|
5
5
|
* `read: []`) are not something Postgres can hold for one request role shared
|
|
6
6
|
* by every user, so the SDK applies them to each row it serves
|
|
7
7
|
* (`stripUnreadable`). SQL run as the caller (`DataDriver.sql`) returns rows
|
|
@@ -11,8 +11,9 @@
|
|
|
11
11
|
* Postgres says where each result column came from: the row description
|
|
12
12
|
* carries the table's oid and the column's number for every column that is a
|
|
13
13
|
* plain reference to one, aliased or not, `RETURNING` included. A column whose
|
|
14
|
-
* origin is a
|
|
15
|
-
* every row, the way the API
|
|
14
|
+
* origin is a table column this caller cannot read (or the foreign key of a
|
|
15
|
+
* to-one relation they cannot read) is dropped from every row, the way the API
|
|
16
|
+
* drops it.
|
|
16
17
|
*
|
|
17
18
|
* What it cannot see is a value computed from such a column — `md5(hash)`,
|
|
18
19
|
* `hash || ''` — whose origin Postgres reports as none. That is the query
|
|
@@ -21,11 +22,11 @@
|
|
|
21
22
|
*
|
|
22
23
|
* A driver that reports no origins at all (PGlite) has its result columns
|
|
23
24
|
* matched by name instead, against every restricted column of every
|
|
24
|
-
*
|
|
25
|
+
* table: it may drop a column of the same name from another table, never
|
|
25
26
|
* keep one it should drop.
|
|
26
27
|
*/
|
|
27
28
|
import { type FieldViewer } from "@rebasepro/common";
|
|
28
|
-
import {
|
|
29
|
+
import type { TableDescriptor } from "@rebasepro/types";
|
|
29
30
|
/** A result column as the driver describes it. */
|
|
30
31
|
export interface ResultField {
|
|
31
32
|
name: string;
|
|
@@ -56,5 +57,7 @@ export declare class ColumnOrigins {
|
|
|
56
57
|
* `rows` without the columns `viewer` may not read, by the origins `fields`
|
|
57
58
|
* describe. The rows are changed in place and returned.
|
|
58
59
|
*/
|
|
59
|
-
export declare function withoutUnreadableColumns(rows: Record<string, unknown>[], fields: ResultField[], viewer: FieldViewer,
|
|
60
|
+
export declare function withoutUnreadableColumns(rows: Record<string, unknown>[], fields: ResultField[], viewer: FieldViewer,
|
|
61
|
+
/** Every table the driver serves, as described: the rules are read off their columns and relations. */
|
|
62
|
+
tables: readonly TableDescriptor[], origins: ColumnOrigins, run: CatalogueRunner): Promise<Record<string, unknown>[]>;
|
|
60
63
|
export {};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Compare the RLS policies a database actually has against the ones the
|
|
3
|
-
*
|
|
3
|
+
* tables describe.
|
|
4
4
|
*
|
|
5
|
-
* Policies live in Postgres; the
|
|
5
|
+
* Policies live in Postgres; the table definitions are only their *source*.
|
|
6
6
|
* Nothing reconciled the two, which is how the demo database served empty
|
|
7
|
-
*
|
|
7
|
+
* tables indefinitely: its policies granted `TO authenticated` (a Supabase
|
|
8
8
|
* role name) while requests run as `rebase_user`, so RLS filtered every row.
|
|
9
9
|
* The config was later corrected and the database never noticed — an empty
|
|
10
10
|
* table is indistinguishable from a table with no data.
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* function `db push` uses to write `.rebase/sql/policies.sql`, so this compares
|
|
14
14
|
* against exactly what would be applied rather than a reimplementation.
|
|
15
15
|
*/
|
|
16
|
-
import { type
|
|
16
|
+
import { type CompiledTable } from "@rebasepro/types";
|
|
17
17
|
export interface PolicyRef {
|
|
18
18
|
schema: string;
|
|
19
19
|
table: string;
|
|
@@ -50,9 +50,9 @@ export interface PolicyRef {
|
|
|
50
50
|
withCheck?: string | null;
|
|
51
51
|
}
|
|
52
52
|
export interface PolicyDrift {
|
|
53
|
-
/** Described by the
|
|
53
|
+
/** Described by the tables, absent from the database. */
|
|
54
54
|
missing: PolicyRef[];
|
|
55
|
-
/** In the database, described by no
|
|
55
|
+
/** In the database, described by no table — stale pushes live here. */
|
|
56
56
|
orphaned: PolicyRef[];
|
|
57
57
|
/** Same policy name, different roles or command. */
|
|
58
58
|
diverged: {
|
|
@@ -77,7 +77,7 @@ export interface PolicyDrift {
|
|
|
77
77
|
reason: string;
|
|
78
78
|
}[];
|
|
79
79
|
/**
|
|
80
|
-
* A table the
|
|
80
|
+
* A table the tables describe whose RLS switch is off.
|
|
81
81
|
*
|
|
82
82
|
* `ALTER TABLE posts DISABLE ROW LEVEL SECURITY` leaves every row in
|
|
83
83
|
* `pg_policies` untouched, so before this category every expected policy
|
|
@@ -121,12 +121,12 @@ export declare function parseExpectedPolicies(ddl: string): PolicyRef[];
|
|
|
121
121
|
export type AdminPoliciesExpectation = boolean | "detect";
|
|
122
122
|
export declare function resolveAdminPolicies(client: Queryable, expectation: AdminPoliciesExpectation | undefined): Promise<boolean>;
|
|
123
123
|
/**
|
|
124
|
-
* The policies the
|
|
124
|
+
* The policies the tables declare, parsed from the DDL `db push` writes —
|
|
125
125
|
* with the ones the compiler put `TO rebase_admin` read as `TO public` where
|
|
126
126
|
* `adminRoleAvailable` is false, as the boot and the push then write them. A
|
|
127
127
|
* rule that names `rebase_admin` itself keeps it.
|
|
128
128
|
*/
|
|
129
|
-
export declare function expectedPolicies(
|
|
129
|
+
export declare function expectedPolicies(compiledTables: readonly CompiledTable[], adminRoleAvailable: boolean): PolicyRef[];
|
|
130
130
|
/**
|
|
131
131
|
* Diff expected against live.
|
|
132
132
|
*
|
|
@@ -143,7 +143,7 @@ export declare function expectedPolicies(collections: CollectionConfig[], adminR
|
|
|
143
143
|
* whose `qual` was NULL, matching on every field this checked and denying 100%
|
|
144
144
|
* of reads. The same blindness would hide a policy that fails open.
|
|
145
145
|
*/
|
|
146
|
-
export declare function checkPolicyDrift(client: Queryable,
|
|
146
|
+
export declare function checkPolicyDrift(client: Queryable, compiledTables: readonly CompiledTable[], options?: {
|
|
147
147
|
adminRoleAvailable?: AdminPoliciesExpectation;
|
|
148
148
|
}): Promise<PolicyDrift>;
|
|
149
149
|
/**
|
|
@@ -171,16 +171,16 @@ export interface OrphanCleanup {
|
|
|
171
171
|
/**
|
|
172
172
|
* Drop the policies an earlier push superseded but never removed.
|
|
173
173
|
*
|
|
174
|
-
* Only touches tables the
|
|
174
|
+
* Only touches tables the tables describe — a table with no expected
|
|
175
175
|
* policy is not ours to reconcile, and scanning by schema alone would sweep up
|
|
176
176
|
* policies belonging to something else sharing the database.
|
|
177
177
|
*/
|
|
178
|
-
export declare function dropOrphanedPolicies(client: Queryable, drift: PolicyDrift,
|
|
178
|
+
export declare function dropOrphanedPolicies(client: Queryable, drift: PolicyDrift, compiledTables: readonly CompiledTable[]): Promise<OrphanCleanup>;
|
|
179
179
|
/**
|
|
180
180
|
* Which orphans {@link dropOrphanedPolicies} drops and which it keeps, decided
|
|
181
181
|
* without dropping anything: what `db push --dry-run` lists.
|
|
182
182
|
*/
|
|
183
|
-
export declare function partitionOrphans(drift: PolicyDrift,
|
|
183
|
+
export declare function partitionOrphans(drift: PolicyDrift, compiledTables: readonly CompiledTable[]): OrphanCleanup;
|
|
184
184
|
/**
|
|
185
185
|
* Drop the admin-request companions no current rule earns, and nothing else:
|
|
186
186
|
* the `_ar_` policies on managed tables `checkPolicyDrift` reports as orphans.
|
|
@@ -191,7 +191,7 @@ export declare function partitionOrphans(drift: PolicyDrift, collections: Collec
|
|
|
191
191
|
* stay, admitting every admin to every row, on a deployment whose boot never
|
|
192
192
|
* provisions. `rebase db migrate` runs this after it applies.
|
|
193
193
|
*/
|
|
194
|
-
export declare function dropStaleAdminRequestCompanions(client: Queryable,
|
|
194
|
+
export declare function dropStaleAdminRequestCompanions(client: Queryable, compiledTables: readonly CompiledTable[], options?: {
|
|
195
195
|
adminRoleAvailable?: AdminPoliciesExpectation;
|
|
196
196
|
}): Promise<PolicyRef[]>;
|
|
197
197
|
export declare const hasDrift: (d: PolicyDrift) => boolean;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SQL } from "drizzle-orm";
|
|
2
|
-
import {
|
|
2
|
+
import { type TableDescriptor } from "@rebasepro/types";
|
|
3
3
|
import { REBASE_USER_ROLE } from "@rebasepro/common";
|
|
4
4
|
import { type GrantsMode, type ProvisionRoleMode, type RequestIdentity, type RlsSettings } from "./rls-settings.js";
|
|
5
5
|
/**
|
|
@@ -10,9 +10,9 @@ import { type GrantsMode, type ProvisionRoleMode, type RequestIdentity, type Rls
|
|
|
10
10
|
* - **User context** — a request authenticated (or anonymous) via
|
|
11
11
|
* `driver.withAuth(user)`. Runs as the restricted `rebase_user` role: a
|
|
12
12
|
* non-owner, NOSUPERUSER, NOBYPASSRLS role, so Postgres RLS binds *every*
|
|
13
|
-
* statement (SELECT, INSERT, UPDATE, DELETE). The
|
|
14
|
-
*
|
|
15
|
-
*
|
|
13
|
+
* statement (SELECT, INSERT, UPDATE, DELETE). The table's `rls` rules
|
|
14
|
+
* are the whole authorization model; app-layer hooks are
|
|
15
|
+
* validation/side-effects, not a security boundary.
|
|
16
16
|
*
|
|
17
17
|
* - **Server context** — the base (owner) connection: auth flows, migrations,
|
|
18
18
|
* and raw `rebase.sql`. As table owner it bypasses RLS. This is the trusted
|
|
@@ -332,16 +332,16 @@ export declare function ensureAppRole(run: RawSqlRunner, schemas: string[], opti
|
|
|
332
332
|
* "Can reach" is what the role can actually do — through a grant to it, to a
|
|
333
333
|
* role it inherits, or to PUBLIC, on the table or on any of its columns —
|
|
334
334
|
* because that, not how the ACL is spelled, is what a request running as it
|
|
335
|
-
* gets. A table with RLS on is somebody's
|
|
335
|
+
* gets. A table with RLS on is somebody's declared table by that same rule as the
|
|
336
336
|
* sweep's, and is left out.
|
|
337
337
|
*/
|
|
338
338
|
export declare function findExposedInternalTables(run: RawSqlRunner, schemas: string[], role?: string): Promise<string[]>;
|
|
339
339
|
/**
|
|
340
|
-
*
|
|
340
|
+
* Served tables that the user role holds no privilege on
|
|
341
341
|
* and this connection cannot grant it, because another role owns them.
|
|
342
342
|
*
|
|
343
343
|
* The grant tier passes these over — it could only fail on them — so on a
|
|
344
|
-
* database another application shares, a
|
|
344
|
+
* database another application shares, a declared table over that application's
|
|
345
345
|
* table boots and then refuses every request with "permission denied". This
|
|
346
346
|
* names them, with the owner who can run the grant. Refusing rather than
|
|
347
347
|
* widening, so the boot warns instead of stopping: the rest of the project
|
|
@@ -563,6 +563,12 @@ export declare function authContextStatement(auth: AuthContext, userRole?: strin
|
|
|
563
563
|
text: string;
|
|
564
564
|
values: string[];
|
|
565
565
|
};
|
|
566
|
+
/**
|
|
567
|
+
* What the rule checks read of a table: its slug, to name it, and its
|
|
568
|
+
* row-level security, whose `rules` are what the policies are compiled from.
|
|
569
|
+
* A {@link TableDescriptor} is one.
|
|
570
|
+
*/
|
|
571
|
+
export type TableRules = Pick<TableDescriptor, "slug" | "rls">;
|
|
566
572
|
/**
|
|
567
573
|
* Warn about rules that read as "signed-in users only" but admit anonymous
|
|
568
574
|
* callers — `rebase.uid() IS NOT NULL`, or a comparison against another
|
|
@@ -581,12 +587,9 @@ export declare function authContextStatement(auth: AuthContext, userRole?: strin
|
|
|
581
587
|
* either — this is the escape hatch whose whole promise is that it means what it
|
|
582
588
|
* says. So: say so, loudly, and leave the rule alone.
|
|
583
589
|
*/
|
|
584
|
-
export declare function warnOnAnonymousGrants(
|
|
585
|
-
slug?: string;
|
|
586
|
-
securityRules?: readonly SecurityRule[];
|
|
587
|
-
}[]): void;
|
|
590
|
+
export declare function warnOnAnonymousGrants(tables: readonly TableRules[]): void;
|
|
588
591
|
/**
|
|
589
|
-
* Name the
|
|
592
|
+
* Name the tables whose raw policy SQL still calls the pre-1.0 helpers.
|
|
590
593
|
*
|
|
591
594
|
* The compiler rewrites `auth.uid()` to `rebase.uid()` on the way into the
|
|
592
595
|
* database, so nothing is broken and no policy is wrong — which is exactly why
|
|
@@ -597,10 +600,7 @@ export declare function warnOnAnonymousGrants(collections: {
|
|
|
597
600
|
* Only `raw` expressions can carry it. Structured rules (`policy.authUid()`,
|
|
598
601
|
* `policy.rolesOverlap(...)`) compile from the model and were never affected.
|
|
599
602
|
*/
|
|
600
|
-
export declare function warnOnLegacyRlsFunctions(
|
|
601
|
-
slug?: string;
|
|
602
|
-
securityRules?: readonly SecurityRule[];
|
|
603
|
-
}[]): void;
|
|
603
|
+
export declare function warnOnLegacyRlsFunctions(tables: readonly TableRules[]): void;
|
|
604
604
|
/**
|
|
605
605
|
* Reject `pgRoles` that this server can never satisfy.
|
|
606
606
|
*
|
|
@@ -617,15 +617,9 @@ export declare function warnOnLegacyRlsFunctions(collections: {
|
|
|
617
617
|
* has `r`'s privileges, which a member only gets by inheriting them, and
|
|
618
618
|
* `rebase_user` is `NOINHERIT`. This used to ask `pg_has_role(…, 'MEMBER')`, so
|
|
619
619
|
* `GRANT authenticated TO rebase_user` — the grant its own hint suggested —
|
|
620
|
-
* passed here and still read every
|
|
621
|
-
*/
|
|
622
|
-
export declare function validatePolicyPgRoles(run: RawSqlRunner,
|
|
623
|
-
slug?: string;
|
|
624
|
-
securityRules?: readonly {
|
|
625
|
-
name?: string;
|
|
626
|
-
pgRoles?: readonly string[];
|
|
627
|
-
}[];
|
|
628
|
-
}[],
|
|
620
|
+
* passed here and still read every table as empty.
|
|
621
|
+
*/
|
|
622
|
+
export declare function validatePolicyPgRoles(run: RawSqlRunner, tables: readonly TableRules[],
|
|
629
623
|
/** The role(s) requests actually run as: `rebase_user` (or the `rls.requestRole`
|
|
630
624
|
* roles) when the connection is privileged enough to switch, otherwise the
|
|
631
625
|
* connection role itself. With several, a role is usable when any reaches it. */
|
|
@@ -89,8 +89,8 @@ export interface PostgresRlsConfig {
|
|
|
89
89
|
adminPolicies?: AdminPoliciesMode;
|
|
90
90
|
/**
|
|
91
91
|
* `false` drops the injected server-or-admin baseline from every
|
|
92
|
-
*
|
|
93
|
-
* A
|
|
92
|
+
* table, as `defaultPolicies: false` does for one. Default `true`.
|
|
93
|
+
* A table's own `defaultPolicies: false` still decides for it.
|
|
94
94
|
*/
|
|
95
95
|
defaultPolicies?: boolean;
|
|
96
96
|
/**
|