@rebasepro/server-postgres 0.17.3 → 0.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +0 -1
- package/README.md +31 -0
- package/dist/BranchService-ByLfM_Tt.js +360 -0
- package/dist/BranchService-ByLfM_Tt.js.map +1 -0
- package/dist/__vite-browser-external-BnuHet1e.js +46 -0
- package/dist/__vite-browser-external-BnuHet1e.js.map +1 -0
- package/dist/arg-Dni7MzLB.js +87 -0
- package/dist/arg-Dni7MzLB.js.map +1 -0
- package/dist/auth-users-columns-D2LBFrMH.js +116 -0
- package/dist/auth-users-columns-D2LBFrMH.js.map +1 -0
- package/dist/backup-argv.d.ts +19 -0
- package/dist/backup-cli-oM9WQVlV.js +408 -0
- package/dist/backup-cli-oM9WQVlV.js.map +1 -0
- package/dist/backup-service-Br3tqwsy.js +715 -0
- package/dist/backup-service-Br3tqwsy.js.map +1 -0
- package/dist/branch-argv.d.ts +28 -0
- package/dist/branch-prune.d.ts +77 -0
- package/dist/cli-collections-path.d.ts +31 -0
- package/dist/cli-errors-DxN4yzdH.js +657 -0
- package/dist/cli-errors-DxN4yzdH.js.map +1 -0
- package/dist/cli-errors.d.ts +123 -0
- package/dist/cli-flags.d.ts +101 -0
- package/dist/cli-helpers.d.ts +94 -10
- package/dist/cli-output-CNdMql-L.js +47 -0
- package/dist/cli-output-CNdMql-L.js.map +1 -0
- package/dist/cli.js +2020 -0
- package/dist/cli.js.map +1 -0
- package/dist/collection-index-BHgT_TKd.js +276 -0
- package/dist/collection-index-BHgT_TKd.js.map +1 -0
- package/dist/{collections-schema-version-BMeu3cgv.js → collections-schema-version-T6cGvrDi.js} +1 -2
- package/dist/{collections-schema-version-BMeu3cgv.js.map → collections-schema-version-T6cGvrDi.js.map} +1 -1
- package/dist/{connection-GOKU3Hu5.js → databasePoolManager-Bj5FbeAs.js} +112 -40
- package/dist/databasePoolManager-Bj5FbeAs.js.map +1 -0
- package/dist/databasePoolManager.d.ts +27 -0
- package/dist/doctor-D7HWmGzs.js +974 -0
- package/dist/doctor-D7HWmGzs.js.map +1 -0
- package/dist/{ensure-collection-policies-UCqgv_8c.js → ensure-collection-policies-2c2NV8zX.js} +7 -27
- package/dist/ensure-collection-policies-2c2NV8zX.js.map +1 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js +820 -0
- package/dist/ensure-collection-tables-D4wJzM4y.js.map +1 -0
- package/dist/ensure-tables-CIojK-Rx.js +650 -0
- package/dist/ensure-tables-CIojK-Rx.js.map +1 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js +123 -0
- package/dist/generate-drizzle-schema-CwEgVyjO.js.map +1 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js +528 -0
- package/dist/generate-drizzle-schema-logic-so2Z_lyC.js.map +1 -0
- package/dist/{ensure-collection-tables-DgVixhX3.js → generate-postgres-ddl-logic-CtnpIBVv.js} +126 -984
- package/dist/generate-postgres-ddl-logic-CtnpIBVv.js.map +1 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js +157 -0
- package/dist/generated-schema-staleness-DQdfJl2A.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.es.js +7423 -1133
- package/dist/index.es.js.map +1 -1
- package/dist/introspect-db-logic-C6LQdTxj.js +1378 -0
- package/dist/introspect-db-logic-C6LQdTxj.js.map +1 -0
- package/dist/policy-drift-kNJ6X2Uj.js +313 -0
- package/dist/policy-drift-kNJ6X2Uj.js.map +1 -0
- package/dist/{backup-service-DCk7KhhL.js → rls-bootstrap-sql-DLDnUjtx.js} +737 -2689
- package/dist/rls-bootstrap-sql-DLDnUjtx.js.map +1 -0
- package/dist/{rls-enforcement-DvAbL9YJ.js → rls-enforcement-DeYEjYLt.js} +65 -190
- package/dist/rls-enforcement-DeYEjYLt.js.map +1 -0
- package/dist/schema/bin/generate-drizzle-schema.d.ts +1 -0
- package/dist/schema/bin/generate-postgres-ddl.d.ts +1 -0
- package/dist/schema/column-type-drift.d.ts +79 -0
- package/dist/schema/doctor-cli.js +129 -0
- package/dist/schema/doctor-cli.js.map +1 -0
- package/dist/schema/doctor.d.ts +42 -0
- package/dist/schema/ensure-collection-tables.d.ts +90 -0
- package/dist/schema/generate-drizzle-schema.d.ts +1 -1
- package/dist/schema/generate-drizzle-schema.js +24 -0
- package/dist/schema/generate-drizzle-schema.js.map +1 -0
- package/dist/schema/generate-next-step.d.ts +30 -0
- package/dist/schema/generate-postgres-ddl-logic.d.ts +28 -0
- package/dist/schema/generate-postgres-ddl.d.ts +1 -1
- package/dist/schema/generate-postgres-ddl.js +138 -0
- package/dist/schema/generate-postgres-ddl.js.map +1 -0
- package/dist/schema/generated-schema-staleness.d.ts +37 -0
- package/dist/schema/introspect-db-queries.d.ts +34 -0
- package/dist/schema/introspect-db.js +866 -0
- package/dist/schema/introspect-db.js.map +1 -0
- package/dist/security/rls-enforcement.d.ts +63 -2
- package/dist/services/BranchService.d.ts +86 -1
- package/dist/services/collection-helpers.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +30 -2
- package/dist/services/row-pipeline.d.ts +12 -1
- package/dist/source-Br7L7GOI.js +410 -0
- package/dist/source-Br7L7GOI.js.map +1 -0
- package/dist/utils/pg-error-utils.d.ts +3 -1
- package/dist/utils/pg-numeric-number-patch.d.ts +31 -0
- package/dist/vector-index-DkWxm2de.js +309 -0
- package/dist/vector-index-DkWxm2de.js.map +1 -0
- package/package.json +32 -27
- package/dist/backup-service-DCk7KhhL.js.map +0 -1
- package/dist/collection-index-BRUg10H5.js +0 -5690
- package/dist/collection-index-BRUg10H5.js.map +0 -1
- package/dist/connection-GOKU3Hu5.js.map +0 -1
- package/dist/ensure-collection-policies-UCqgv_8c.js.map +0 -1
- package/dist/ensure-collection-tables-DgVixhX3.js.map +0 -1
- package/dist/rls-bootstrap-sql-B5C9LoJ6.js +0 -244
- package/dist/rls-bootstrap-sql-B5C9LoJ6.js.map +0 -1
- package/dist/rls-enforcement-DvAbL9YJ.js.map +0 -1
- package/dist/src-DiB5RP2Z.js +0 -541
- package/dist/src-DiB5RP2Z.js.map +0 -1
- package/dist/websocket-BZ4H5wUz.js +0 -8198
- package/dist/websocket-BZ4H5wUz.js.map +0 -1
- package/src/PostgresAdapter.ts +0 -91
- package/src/PostgresBackendDriver.ts +0 -1857
- package/src/PostgresBootstrapper.ts +0 -1157
- package/src/auth/ensure-tables.ts +0 -896
- package/src/auth/schema-version.ts +0 -260
- package/src/auth/services.ts +0 -1610
- package/src/backup/backup-cli.ts +0 -520
- package/src/backup/backup-cron.ts +0 -212
- package/src/backup/backup-logic.ts +0 -93
- package/src/backup/backup-service.ts +0 -485
- package/src/backup/index.ts +0 -12
- package/src/backup/pg-tools.ts +0 -403
- package/src/backup/retention.ts +0 -86
- package/src/cli-errors.ts +0 -265
- package/src/cli-helpers.ts +0 -569
- package/src/cli-output.ts +0 -43
- package/src/cli.ts +0 -1339
- package/src/collections/PostgresCollectionRegistry.ts +0 -108
- package/src/collections/buildRegistry.ts +0 -68
- package/src/collections/validate-relations.ts +0 -402
- package/src/connection.ts +0 -333
- package/src/data-transformer.ts +0 -845
- package/src/databasePoolManager.ts +0 -95
- package/src/history/HistoryService.ts +0 -254
- package/src/history/ensure-history-table.ts +0 -53
- package/src/index.ts +0 -19
- package/src/interfaces.ts +0 -60
- package/src/module-dir.ts +0 -7
- package/src/schema/atlas-argv.ts +0 -94
- package/src/schema/auth-schema.ts +0 -298
- package/src/schema/auth-users-columns.ts +0 -131
- package/src/schema/carved-out-migration.ts +0 -404
- package/src/schema/classify-change.ts +0 -436
- package/src/schema/collection-index.ts +0 -427
- package/src/schema/collections-schema-version.ts +0 -103
- package/src/schema/destructive-sql.ts +0 -94
- package/src/schema/doctor-cli.ts +0 -66
- package/src/schema/doctor-policy-checks.ts +0 -105
- package/src/schema/doctor.ts +0 -837
- package/src/schema/drizzle-ddl.ts +0 -33
- package/src/schema/dynamic-tables.test.ts +0 -302
- package/src/schema/dynamic-tables.ts +0 -293
- package/src/schema/ensure-collection-policies.ts +0 -198
- package/src/schema/ensure-collection-tables.test.ts +0 -518
- package/src/schema/ensure-collection-tables.ts +0 -1267
- package/src/schema/generate-drizzle-schema-logic.ts +0 -957
- package/src/schema/generate-drizzle-schema.ts +0 -143
- package/src/schema/generate-postgres-ddl-logic.ts +0 -1339
- package/src/schema/generate-postgres-ddl.ts +0 -180
- package/src/schema/generate-schema-commit.ts +0 -267
- package/src/schema/generated-schema-staleness.ts +0 -284
- package/src/schema/introspect-db-constraints.ts +0 -385
- package/src/schema/introspect-db-inference.ts +0 -255
- package/src/schema/introspect-db-logic.ts +0 -1387
- package/src/schema/introspect-db-naming.ts +0 -15
- package/src/schema/introspect-db-project.ts +0 -78
- package/src/schema/introspect-db-queries.ts +0 -326
- package/src/schema/introspect-db-structure.ts +0 -670
- package/src/schema/introspect-db-types.ts +0 -56
- package/src/schema/introspect-db.ts +0 -257
- package/src/schema/introspect-runtime.test.ts +0 -260
- package/src/schema/introspect-runtime.ts +0 -327
- package/src/schema/non-sql-collections.test.ts +0 -131
- package/src/schema/rls-bootstrap-sql.ts +0 -288
- package/src/schema/search-column.ts +0 -643
- package/src/schema/test-schema.ts +0 -11
- package/src/schema/vector-index.ts +0 -491
- package/src/security/anonymous-grants.test.ts +0 -73
- package/src/security/policy-drift.test.ts +0 -435
- package/src/security/policy-drift.ts +0 -473
- package/src/security/rls-enforcement.ts +0 -505
- package/src/services/BranchService.ts +0 -326
- package/src/services/FetchService.ts +0 -2115
- package/src/services/PersistService.ts +0 -557
- package/src/services/RelationService.ts +0 -978
- package/src/services/RelationWriteService.ts +0 -653
- package/src/services/cdc/CdcListener.ts +0 -103
- package/src/services/cdc/junction-tables.ts +0 -91
- package/src/services/cdc/trigger-cdc.ts +0 -173
- package/src/services/channel-bus/ChannelBus.ts +0 -44
- package/src/services/channel-bus/PostgresChannelBus.ts +0 -299
- package/src/services/channel-bus/index.ts +0 -114
- package/src/services/channel-history.ts +0 -424
- package/src/services/channel-presence.ts +0 -185
- package/src/services/collection-helpers.ts +0 -420
- package/src/services/dataService.ts +0 -256
- package/src/services/index.ts +0 -14
- package/src/services/junction-writes.ts +0 -295
- package/src/services/nested-path.ts +0 -145
- package/src/services/pg-notify-listener.ts +0 -151
- package/src/services/realtimeService.ts +0 -2545
- package/src/services/row-pipeline.ts +0 -240
- package/src/services/write-denial.ts +0 -55
- package/src/types.ts +0 -4
- package/src/utils/connection-string.ts +0 -58
- package/src/utils/drizzle-conditions.ts +0 -2743
- package/src/utils/pg-array-null-patch.ts +0 -42
- package/src/utils/pg-error-utils.ts +0 -391
- package/src/websocket.ts +0 -855
|
@@ -1,1339 +0,0 @@
|
|
|
1
|
-
import { CollectionConfig, NumberProperty, Property, ResolvedRelation, RelationProperty, SecurityOperation, SecurityRule, StringProperty, isPostgresCollectionConfig, DateProperty, ArrayProperty, MapProperty, ReferenceProperty, VectorProperty, BinaryProperty, isManyToMany, type ResolvedManyToMany, type ResolvedBelongsTo } from "@rebasepro/types";
|
|
2
|
-
import { getEnumVarName, getTableName, resolveCollectionRelations, findRelation, securityRuleToConditions, policyToPostgres, getEffectiveSecurityRules, getInjectedSecurityRules, resolveJunctionSpecs, getJunctionSecurityRules, getJunctionCollectionConfig, resolveStringColumnLength, relationalCollections } from "@rebasepro/common";
|
|
3
|
-
import { toSnakeCase, getPolicyNamesForRule, generateForeignKeyName, legacyForeignKeyName, toPostgresIdentifier } from "@rebasepro/utils";
|
|
4
|
-
import { AUTH_USERS_COLUMNS, authUsersColumnDefinition, authUsersColumnSql, isAuthCollection } from "./auth-users-columns";
|
|
5
|
-
import {
|
|
6
|
-
buildSearchColumnSpec,
|
|
7
|
-
searchColumnDefinition,
|
|
8
|
-
fuzzyColumnDefinition,
|
|
9
|
-
searchIndexStatements,
|
|
10
|
-
searchHelperFunctions,
|
|
11
|
-
searchExtensionStatements,
|
|
12
|
-
searchColumnNames,
|
|
13
|
-
searchColumnStamps,
|
|
14
|
-
searchStampGuards,
|
|
15
|
-
searchIndexNames,
|
|
16
|
-
type SearchColumnSpec
|
|
17
|
-
} from "./search-column";
|
|
18
|
-
import {
|
|
19
|
-
buildVectorColumnSpecs,
|
|
20
|
-
buildVectorIndexPlan,
|
|
21
|
-
vectorColumnDefinition,
|
|
22
|
-
vectorDimensionGuard,
|
|
23
|
-
vectorExtensionDeclared,
|
|
24
|
-
vectorExtensionStatement,
|
|
25
|
-
vectorIndexStatements,
|
|
26
|
-
vectorObjectNames,
|
|
27
|
-
VECTOR_EXTENSION_OPT_IN,
|
|
28
|
-
type VectorIndexPlan
|
|
29
|
-
} from "./vector-index";
|
|
30
|
-
import { buildCollectionIndexSpecs, collectionIndexStatements } from "./collection-index";
|
|
31
|
-
import { REBASE_SCHEMA } from "@rebasepro/types";
|
|
32
|
-
|
|
33
|
-
// --- Helper Functions ---
|
|
34
|
-
|
|
35
|
-
export const resolveColumnName = (propName: string, prop?: Property | null): string => {
|
|
36
|
-
if (prop && "columnName" in prop && typeof prop.columnName === "string") {
|
|
37
|
-
return prop.columnName;
|
|
38
|
-
}
|
|
39
|
-
return toSnakeCase(propName);
|
|
40
|
-
};
|
|
41
|
-
|
|
42
|
-
export const getPrimaryKeyProp = (collection: CollectionConfig): { name: string, type: "string" | "number", isUuid: boolean } => {
|
|
43
|
-
if (collection.properties) {
|
|
44
|
-
const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => "isId" in (prop as unknown as object) && Boolean((prop as unknown as Record<string, unknown>).isId));
|
|
45
|
-
if (idPropEntry) {
|
|
46
|
-
const prop = idPropEntry[1] as unknown as Property;
|
|
47
|
-
const isUuid = prop.type === "string" && "isId" in prop && (prop as unknown as StringProperty).isId === "uuid";
|
|
48
|
-
return { name: idPropEntry[0], type: prop.type === "number" ? "number" : "string", isUuid };
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
const idProp = collection.properties?.["id"] as unknown as Property | undefined;
|
|
52
|
-
if (idProp?.type === "number") {
|
|
53
|
-
return { name: "id", type: "number", isUuid: false };
|
|
54
|
-
}
|
|
55
|
-
const isUuid = idProp?.type === "string" && "isId" in idProp && (idProp as unknown as StringProperty).isId === "uuid";
|
|
56
|
-
return { name: "id", type: "string", isUuid: isUuid ?? false };
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
export const isNumericId = (collection: CollectionConfig): boolean => {
|
|
60
|
-
return getPrimaryKeyProp(collection).type === "number";
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
export const getPrimaryKeyName = (collection: CollectionConfig): string => {
|
|
64
|
-
return getPrimaryKeyProp(collection).name;
|
|
65
|
-
};
|
|
66
|
-
|
|
67
|
-
/** The column type a junction holds for one endpoint's primary key. */
|
|
68
|
-
const junctionKeyType = (collection: CollectionConfig): string =>
|
|
69
|
-
isNumericId(collection) ? "INTEGER" : (getPrimaryKeyProp(collection).isUuid ? "UUID" : "TEXT");
|
|
70
|
-
|
|
71
|
-
export const isIdProperty = (propName: string, prop: Property, collection: CollectionConfig): boolean => {
|
|
72
|
-
if ("isId" in prop && Boolean(prop.isId)) return true;
|
|
73
|
-
const hasExplicitId = Object.values(collection.properties ?? {}).some(p => "isId" in (p as unknown as object) && Boolean((p as unknown as Record<string, unknown>).isId));
|
|
74
|
-
return !hasExplicitId && propName === "id";
|
|
75
|
-
};
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
type ResolveCollection = (slug: string) => CollectionConfig | undefined;
|
|
79
|
-
|
|
80
|
-
/**
|
|
81
|
-
* Render statements produced by {@link generatePolicyStatements} back into the
|
|
82
|
-
* exact string the DDL/policies files have always carried: each statement on
|
|
83
|
-
* its own line, terminated by a newline. Keeping the string form derived from
|
|
84
|
-
* the statement array means the two can never drift — the boot-time applier and
|
|
85
|
-
* the generated `policies.sql` emit the same SQL, from the same source.
|
|
86
|
-
*/
|
|
87
|
-
const statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\n`).join("");
|
|
88
|
-
|
|
89
|
-
const generatePolicyDdl = (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection): string =>
|
|
90
|
-
statementsToDdl(generatePolicyStatements(collection, rule, resolveCollection));
|
|
91
|
-
|
|
92
|
-
/**
|
|
93
|
-
* The individual SQL statements a single security rule compiles to: a
|
|
94
|
-
* `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete
|
|
95
|
-
* statement (terminated by `;`, no trailing newline).
|
|
96
|
-
*
|
|
97
|
-
* This is the primitive the boot-time RLS applier runs one statement at a time
|
|
98
|
-
* (the runtime's DB handle speaks the extended query protocol, which forbids
|
|
99
|
-
* multiple commands in one execute), while `db push` writes the joined string.
|
|
100
|
-
*/
|
|
101
|
-
export const generatePolicyStatements = (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection): string[] => {
|
|
102
|
-
const tableName = getTableName(collection);
|
|
103
|
-
const ops: readonly SecurityOperation[] = rule.operations && rule.operations.length > 0
|
|
104
|
-
? rule.operations
|
|
105
|
-
: [rule.operation ?? "all"];
|
|
106
|
-
|
|
107
|
-
const policyNames = getPolicyNamesForRule(rule, tableName);
|
|
108
|
-
|
|
109
|
-
return ops.flatMap((op, opIdx) => {
|
|
110
|
-
return generateSinglePolicyStatements(collection, rule, op, policyNames[opIdx], resolveCollection);
|
|
111
|
-
});
|
|
112
|
-
};
|
|
113
|
-
|
|
114
|
-
const generateSinglePolicyStatements = (collection: CollectionConfig, rule: SecurityRule, operation: SecurityOperation, policyName: string, resolveCollection: ResolveCollection): string[] => {
|
|
115
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
116
|
-
const tableName = getTableName(collection);
|
|
117
|
-
const mode = (rule.mode ?? "permissive").toUpperCase();
|
|
118
|
-
const operationUpper = operation.toUpperCase();
|
|
119
|
-
const pgRoles = rule.pgRoles ? [...rule.pgRoles].sort() : ["public"];
|
|
120
|
-
|
|
121
|
-
const needsUsing = operation !== "insert";
|
|
122
|
-
const needsWithCheck = operation !== "select" && operation !== "delete";
|
|
123
|
-
|
|
124
|
-
// Desugar the rule (access / ownerField / roles / structured condition / raw
|
|
125
|
-
// SQL) into the shared PolicyExpression model, then compile to SQL. This is
|
|
126
|
-
// the same normalization the client-side evaluator uses, so DDL and UI agree.
|
|
127
|
-
const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
|
|
128
|
-
|
|
129
|
-
let usingClause = needsUsing && usingExpr ? policyToPostgres(usingExpr, collection, { resolveCollection }) : null;
|
|
130
|
-
let withCheckClause = needsWithCheck && withCheckExpr ? policyToPostgres(withCheckExpr, collection, { resolveCollection }) : null;
|
|
131
|
-
|
|
132
|
-
if (!usingClause && needsUsing) {
|
|
133
|
-
usingClause = "false";
|
|
134
|
-
}
|
|
135
|
-
if (!withCheckClause && needsWithCheck) {
|
|
136
|
-
withCheckClause = "false";
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
const drop = `DROP POLICY IF EXISTS "${policyName}" ON "${schema}"."${tableName}";`;
|
|
140
|
-
let create = `CREATE POLICY "${policyName}" ON "${schema}"."${tableName}" AS ${mode} FOR ${operationUpper} TO ${pgRoles.map(r => `"${r}"`).join(", ")}`;
|
|
141
|
-
if (usingClause) create += ` USING (${usingClause})`;
|
|
142
|
-
if (withCheckClause) create += ` WITH CHECK (${withCheckClause})`;
|
|
143
|
-
create += ";";
|
|
144
|
-
return [drop, create];
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Single-quote escaping for a SQL string literal (PostgreSQL doubles the
|
|
149
|
-
* quote). Enum labels come straight from user-authored collection config, so a
|
|
150
|
-
* label like `it's` closes the literal early and the whole generated file stops
|
|
151
|
-
* parsing at the `CREATE TYPE`. Lives here rather than next to its other caller
|
|
152
|
-
* because ensure-collection-tables already imports from this module — the
|
|
153
|
-
* reverse would be a cycle.
|
|
154
|
-
*/
|
|
155
|
-
export const quoteSqlLiteral = (value: string): string => `'${value.replace(/'/g, "''")}'`;
|
|
156
|
-
|
|
157
|
-
export const getSqlColumnType = (propName: string, prop: Property, collection: CollectionConfig, collections: CollectionConfig[]): string => {
|
|
158
|
-
switch (prop.type) {
|
|
159
|
-
case "string": {
|
|
160
|
-
const stringProp = prop as StringProperty;
|
|
161
|
-
if (stringProp.enum) {
|
|
162
|
-
const tableName = getTableName(collection);
|
|
163
|
-
const colName = resolveColumnName(propName, prop);
|
|
164
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
165
|
-
return `"${schema}"."${tableName}_${colName}"`;
|
|
166
|
-
}
|
|
167
|
-
if (stringProp.isId === "uuid" || stringProp.columnType === "uuid") {
|
|
168
|
-
return "UUID";
|
|
169
|
-
}
|
|
170
|
-
// Width comes from `validation.max` when the property states one.
|
|
171
|
-
// It used to be a hardcoded 255 here and *absent* on the Drizzle
|
|
172
|
-
// path, so the same property produced a bounded column down one
|
|
173
|
-
// generator and an unbounded one down the other.
|
|
174
|
-
if (stringProp.columnType === "char") {
|
|
175
|
-
return `CHAR(${resolveStringColumnLength(stringProp)})`;
|
|
176
|
-
}
|
|
177
|
-
if (stringProp.columnType === "varchar") {
|
|
178
|
-
return `VARCHAR(${resolveStringColumnLength(stringProp)})`;
|
|
179
|
-
}
|
|
180
|
-
// `text` is the default. The two generators disagreed here before:
|
|
181
|
-
// this one emitted VARCHAR(255) while the drizzle path emitted a bare
|
|
182
|
-
// `varchar()`, which Postgres treats as unbounded — so the same
|
|
183
|
-
// property produced a capped column down one path and an uncapped one
|
|
184
|
-
// down the other.
|
|
185
|
-
return "TEXT";
|
|
186
|
-
}
|
|
187
|
-
case "number": {
|
|
188
|
-
const numProp = prop as NumberProperty;
|
|
189
|
-
const isId = isIdProperty(propName, prop, collection);
|
|
190
|
-
if ("isId" in numProp && numProp.isId === "increment") {
|
|
191
|
-
return "INTEGER GENERATED BY DEFAULT AS IDENTITY";
|
|
192
|
-
}
|
|
193
|
-
if (numProp.columnType) {
|
|
194
|
-
if (numProp.columnType === "double precision") return "DOUBLE PRECISION";
|
|
195
|
-
return numProp.columnType.toUpperCase();
|
|
196
|
-
}
|
|
197
|
-
return (numProp.validation?.integer || isId) ? "INTEGER" : "NUMERIC";
|
|
198
|
-
}
|
|
199
|
-
case "boolean":
|
|
200
|
-
return "BOOLEAN";
|
|
201
|
-
case "date": {
|
|
202
|
-
const dateProp = prop as DateProperty;
|
|
203
|
-
if (dateProp.columnType === "date") return "DATE";
|
|
204
|
-
if (dateProp.columnType === "time") return "TIME";
|
|
205
|
-
return "TIMESTAMP WITH TIME ZONE";
|
|
206
|
-
}
|
|
207
|
-
case "map": {
|
|
208
|
-
const mapProp = prop as MapProperty;
|
|
209
|
-
return mapProp.columnType === "json" ? "JSON" : "JSONB";
|
|
210
|
-
}
|
|
211
|
-
// `{ latitude, longitude }` — a document, like `map`. It used to fall to
|
|
212
|
-
// the `TEXT` default below while the Drizzle generator emitted no column
|
|
213
|
-
// at all, which is the divergence that made the type unpersistable.
|
|
214
|
-
case "geopoint":
|
|
215
|
-
return "JSONB";
|
|
216
|
-
case "array": {
|
|
217
|
-
const arrayProp = prop as ArrayProperty;
|
|
218
|
-
let colType = arrayProp.columnType;
|
|
219
|
-
if (!colType && arrayProp.of && !Array.isArray(arrayProp.of)) {
|
|
220
|
-
const ofProp = arrayProp.of as Property;
|
|
221
|
-
if (ofProp.type === "string") {
|
|
222
|
-
colType = "text[]";
|
|
223
|
-
} else if (ofProp.type === "number") {
|
|
224
|
-
colType = ofProp.validation?.integer ? "integer[]" : "numeric[]";
|
|
225
|
-
} else if (ofProp.type === "boolean") {
|
|
226
|
-
colType = "boolean[]";
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
if (colType === "json") return "JSON";
|
|
230
|
-
if (colType === "text[]") return "TEXT[]";
|
|
231
|
-
if (colType === "integer[]") return "INTEGER[]";
|
|
232
|
-
if (colType === "boolean[]") return "BOOLEAN[]";
|
|
233
|
-
if (colType === "numeric[]") return "NUMERIC[]";
|
|
234
|
-
return "JSONB";
|
|
235
|
-
}
|
|
236
|
-
case "vector": {
|
|
237
|
-
const vp = prop as VectorProperty;
|
|
238
|
-
return `VECTOR(${vp.dimensions})`;
|
|
239
|
-
}
|
|
240
|
-
case "binary": {
|
|
241
|
-
return "BYTEA";
|
|
242
|
-
}
|
|
243
|
-
case "relation": {
|
|
244
|
-
const refProp = prop as RelationProperty;
|
|
245
|
-
const resolvedRelations = resolveCollectionRelations(collection);
|
|
246
|
-
const relation = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);
|
|
247
|
-
if (relation?.kind !== "belongsTo") {
|
|
248
|
-
throw new Error(`Relation ${propName} does not put a column on this table (only \`belongsTo\` does)`);
|
|
249
|
-
}
|
|
250
|
-
let targetCollection: CollectionConfig;
|
|
251
|
-
try {
|
|
252
|
-
targetCollection = relation.target();
|
|
253
|
-
} catch {
|
|
254
|
-
return "TEXT";
|
|
255
|
-
}
|
|
256
|
-
const pkProp = getPrimaryKeyProp(targetCollection);
|
|
257
|
-
return pkProp.type === "number" ? "INTEGER" : (pkProp.isUuid ? "UUID" : "TEXT");
|
|
258
|
-
}
|
|
259
|
-
case "reference": {
|
|
260
|
-
const refProp = prop as ReferenceProperty;
|
|
261
|
-
const targetCollection = collections.find(c => c.slug === refProp.path || getTableName(c) === refProp.path);
|
|
262
|
-
if (!targetCollection) return "TEXT";
|
|
263
|
-
const pkProp = getPrimaryKeyProp(targetCollection);
|
|
264
|
-
return pkProp.type === "number" ? "INTEGER" : (pkProp.isUuid ? "UUID" : "TEXT");
|
|
265
|
-
}
|
|
266
|
-
default:
|
|
267
|
-
// A silent `TEXT` here is how the two generators drifted apart: the
|
|
268
|
-
// database got a column for `geopoint` and the Drizzle table did
|
|
269
|
-
// not, so the type looked supported and persisted nothing. Every
|
|
270
|
-
// member of `DataType` is handled above; anything else is a
|
|
271
|
-
// generator that has not been taught the type yet, and it should
|
|
272
|
-
// say so rather than invent a column.
|
|
273
|
-
throw new Error(
|
|
274
|
-
`No Postgres column type for property '${propName}' of type ` +
|
|
275
|
-
`'${(prop as Property).type}' in collection '${collection.slug}'. ` +
|
|
276
|
-
"Add a case to `getSqlColumnType` (and to `getDrizzleColumn`, which must agree)."
|
|
277
|
-
);
|
|
278
|
-
}
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
/**
|
|
282
|
-
* Everything a `search` block needs, as a file Rebase applies itself.
|
|
283
|
-
*
|
|
284
|
-
* Search is the one part of the schema Atlas does not own. Two independent
|
|
285
|
-
* reasons, and either alone would be enough:
|
|
286
|
-
*
|
|
287
|
-
* 1. Its free tier refuses to *parse* a desired-state file that so much as
|
|
288
|
-
* contains a function — "functions and procedures are available to
|
|
289
|
-
* logged-in users only". A generated `tsvector` column cannot avoid one:
|
|
290
|
-
* `unaccent` is STABLE and jsonb flattening needs a set-returning function,
|
|
291
|
-
* so both have to be wrapped in an IMMUTABLE helper to be legal in a
|
|
292
|
-
* generated column at all.
|
|
293
|
-
* 2. Even with the file accepted, Atlas *wipes* the dev database it diffs
|
|
294
|
-
* against, so a helper seeded there beforehand is gone by the time the plan
|
|
295
|
-
* is analysed. There is no hook to reinstate it.
|
|
296
|
-
*
|
|
297
|
-
* So the column, its index and its helpers are excluded from Atlas's view
|
|
298
|
-
* (`searchExcludePatterns`) and applied from here — the same arrangement the
|
|
299
|
-
* RLS policies already use, and for the same underlying reason.
|
|
300
|
-
*
|
|
301
|
-
* Ordered as it must run: extensions, then helpers, then the column whose
|
|
302
|
-
* expression calls them, then the index over that column. Every statement is
|
|
303
|
-
* `IF NOT EXISTS` / `OR REPLACE`, because this is replayed on every push and
|
|
304
|
-
* appended to migrations that run against databases at any stage of their
|
|
305
|
-
* life. Empty when nothing opted in — the caller writes no file then.
|
|
306
|
-
*
|
|
307
|
-
* The dev database Atlas plans against needs none of this. `searchExcludePatterns`
|
|
308
|
-
* removes the search column from the *inspected* state, so the state Atlas
|
|
309
|
-
* replays there never mentions the column and never calls a helper. Seeding the
|
|
310
|
-
* helpers into that database was tried and removed: measured on Atlas 1.2.3, a
|
|
311
|
-
* `schema apply --dry-run` produces byte-identical output seeded or not, and
|
|
312
|
-
* Atlas wipes the dev database before it plans anyway — so a seed could not have
|
|
313
|
-
* helped even where the excludes are missing, which is the case that really does
|
|
314
|
-
* fail with `function public.rebase_search_unaccent(text) does not exist`.
|
|
315
|
-
*/
|
|
316
|
-
export const generatePostgresSearchDdl = (allCollections: CollectionConfig[]): string => {
|
|
317
|
-
const collections = relationalCollections(allCollections);
|
|
318
|
-
const specs = collections
|
|
319
|
-
.map(c => buildSearchColumnSpec(c))
|
|
320
|
-
.filter((s): s is SearchColumnSpec => s !== undefined);
|
|
321
|
-
if (specs.length === 0) return "";
|
|
322
|
-
|
|
323
|
-
const extensions = Array.from(new Set(specs.flatMap(searchExtensionStatements)));
|
|
324
|
-
const helpers = Array.from(new Set(specs.flatMap(searchHelperFunctions)));
|
|
325
|
-
|
|
326
|
-
let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n";
|
|
327
|
-
ddl += "--\n";
|
|
328
|
-
ddl += "-- Full-text search for the collections declaring a `search` block.\n";
|
|
329
|
-
ddl += "-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\n\n";
|
|
330
|
-
|
|
331
|
-
extensions.forEach(s => { ddl += `${s}\n`; });
|
|
332
|
-
if (extensions.length > 0) ddl += "\n";
|
|
333
|
-
helpers.forEach(s => { ddl += `${s}\n\n`; });
|
|
334
|
-
|
|
335
|
-
for (const collection of collections) {
|
|
336
|
-
const spec = buildSearchColumnSpec(collection);
|
|
337
|
-
if (!spec) continue;
|
|
338
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
339
|
-
const table = `"${schema}"."${getTableName(collection)}"`;
|
|
340
|
-
|
|
341
|
-
// ADD COLUMN IF NOT EXISTS rather than the inline definition the
|
|
342
|
-
// CREATE TABLE would use: by the time this runs the table exists,
|
|
343
|
-
// whether Atlas just created it or it has been live for a year.
|
|
344
|
-
// Refuse before altering anything if the column in the database was
|
|
345
|
-
// generated from a different `search` block: `ADD COLUMN IF NOT EXISTS`
|
|
346
|
-
// is a no-op against an existing column, so without this the file would
|
|
347
|
-
// report success and leave the old expression in place — and then stamp
|
|
348
|
-
// it as current.
|
|
349
|
-
searchStampGuards(spec).forEach(s => { ddl += `${s}\n`; });
|
|
350
|
-
ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\n`;
|
|
351
|
-
const fuzzyDef = fuzzyColumnDefinition(spec);
|
|
352
|
-
if (fuzzyDef) ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${fuzzyDef};\n`;
|
|
353
|
-
// The fingerprint of the expression each column was built from — the
|
|
354
|
-
// only record of *which* block a generated column came from, and what
|
|
355
|
-
// the guard above and the boot-time ensure both compare against.
|
|
356
|
-
searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\n`; });
|
|
357
|
-
searchIndexStatements(spec).forEach(s => { ddl += `${s}\n`; });
|
|
358
|
-
ddl += "\n";
|
|
359
|
-
}
|
|
360
|
-
|
|
361
|
-
return ddl;
|
|
362
|
-
};
|
|
363
|
-
|
|
364
|
-
/**
|
|
365
|
-
* Glob patterns telling Atlas to leave the search column and its index alone.
|
|
366
|
-
*
|
|
367
|
-
* Without these, a desired state that omits search reads to Atlas as an
|
|
368
|
-
* instruction to drop the column — taking the index and the whole search
|
|
369
|
-
* feature with it on the next push.
|
|
370
|
-
*
|
|
371
|
-
* Fully qualified, `schema.table.object`, matching the include list. The
|
|
372
|
-
* two-part form is what Atlas wants when the connection URL scopes it to one
|
|
373
|
-
* schema and is *silently ignored* otherwise: it reads `posts.search_vector`
|
|
374
|
-
* as a table named `search_vector` in a schema named `posts`, matches nothing,
|
|
375
|
-
* and reports no error for the pattern that never fired.
|
|
376
|
-
*/
|
|
377
|
-
export const searchExcludePatterns = (allCollections: CollectionConfig[]): string[] => {
|
|
378
|
-
const patterns: string[] = [];
|
|
379
|
-
for (const collection of relationalCollections(allCollections)) {
|
|
380
|
-
const spec = buildSearchColumnSpec(collection);
|
|
381
|
-
if (!spec) continue;
|
|
382
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
383
|
-
const table = getTableName(collection);
|
|
384
|
-
for (const name of searchColumnNames(collection)) {
|
|
385
|
-
patterns.push(`${schema}.${table}.${name}`);
|
|
386
|
-
}
|
|
387
|
-
for (const index of searchIndexNames(spec)) {
|
|
388
|
-
patterns.push(`${schema}.${table}.${index}`);
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
return patterns;
|
|
392
|
-
};
|
|
393
|
-
|
|
394
|
-
/**
|
|
395
|
-
* Everything a `{ type: "vector" }` property needs, as a file Rebase applies
|
|
396
|
-
* itself.
|
|
397
|
-
*
|
|
398
|
-
* Vector is the second part of the schema Atlas does not own, and it is out for
|
|
399
|
-
* a narrower reason than search: not that Atlas refuses to parse the file, but
|
|
400
|
-
* that it cannot *execute* it. To compute a desired state Atlas materialises
|
|
401
|
-
* `schema.sql` in a dev database, that database is created empty, and Atlas
|
|
402
|
-
* empties it again at the start of every run — so `VECTOR(384)` resolves
|
|
403
|
-
* against a database that structurally cannot have pgvector, and every push
|
|
404
|
-
* dies with `type "vector" does not exist`. Seeding the extension beforehand
|
|
405
|
-
* does not survive the clean (measured: present before the run, gone after),
|
|
406
|
-
* putting `CREATE EXTENSION` in `schema.sql` is refused as an Atlas Pro
|
|
407
|
-
* feature, and `--exclude` alone cannot help because Atlas still parses and
|
|
408
|
-
* applies the whole file.
|
|
409
|
-
*
|
|
410
|
-
* So the column, its ANN indexes and the extension are excluded from Atlas's
|
|
411
|
-
* view ({@link vectorExcludePatterns}) and applied from here — the same
|
|
412
|
-
* arrangement search and the RLS policies already use.
|
|
413
|
-
*
|
|
414
|
-
* `CREATE EXTENSION` appears only when the project's database named `vector` in
|
|
415
|
-
* its `extensions` — see `DatabaseOptions.extensions`. Everything else is
|
|
416
|
-
* emitted either way: a database that already has pgvector installed by hand
|
|
417
|
-
* needs no permission from anyone, and one that does not gets the column
|
|
418
|
-
* refused by Postgres with a message this repo makes name the opt-in.
|
|
419
|
-
*
|
|
420
|
-
* Ordered as it must run: the extension, then the drift guard, then the column
|
|
421
|
-
* whose type needs the extension, then the indexes over that column. Every
|
|
422
|
-
* statement is `IF NOT EXISTS`, because this is replayed on every push and
|
|
423
|
-
* appended to migrations that run against databases at any stage of their life.
|
|
424
|
-
* Empty when no collection declares a vector — the caller writes no file then.
|
|
425
|
-
*/
|
|
426
|
-
export const generatePostgresVectorDdl = (
|
|
427
|
-
allCollections: CollectionConfig[],
|
|
428
|
-
options: { extensions?: readonly string[] } = {}
|
|
429
|
-
): string => {
|
|
430
|
-
const collections = relationalCollections(allCollections);
|
|
431
|
-
const withVectors = collections.filter(c => buildVectorColumnSpecs(c, resolveColumnName).length > 0);
|
|
432
|
-
if (withVectors.length === 0) return "";
|
|
433
|
-
|
|
434
|
-
let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n";
|
|
435
|
-
ddl += "--\n";
|
|
436
|
-
ddl += "-- Vector columns and their ANN indexes, for the collections declaring a\n";
|
|
437
|
-
ddl += "-- `vector` property. Applied by Rebase, not by Atlas — see\n";
|
|
438
|
-
ddl += "-- generatePostgresVectorDdl.\n\n";
|
|
439
|
-
// The note is not decoration. Someone reading this file after a failed push
|
|
440
|
-
// is looking for the reason the type does not exist, and "no CREATE
|
|
441
|
-
// EXTENSION here" is invisible unless it is written down.
|
|
442
|
-
ddl += vectorExtensionDeclared(options.extensions)
|
|
443
|
-
? `${vectorExtensionStatement()}\n\n`
|
|
444
|
-
: `-- pgvector is not installed from here: no database declared it. To let Rebase\n` +
|
|
445
|
-
`-- install it, add ${VECTOR_EXTENSION_OPT_IN} in config/resources.ts.\n` +
|
|
446
|
-
`-- Otherwise install it once by hand; the column below needs the type either way.\n\n`;
|
|
447
|
-
|
|
448
|
-
for (const collection of withVectors) {
|
|
449
|
-
const table = `"${isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public"}"."${getTableName(collection)}"`;
|
|
450
|
-
for (const spec of buildVectorColumnSpecs(collection, resolveColumnName)) {
|
|
451
|
-
// Guard before the ADD, so a changed `dimensions` is reported rather
|
|
452
|
-
// than skipped over — see `vectorDimensionGuard`.
|
|
453
|
-
ddl += `${vectorDimensionGuard(spec)}\n`;
|
|
454
|
-
// ADD COLUMN IF NOT EXISTS rather than the inline definition the
|
|
455
|
-
// CREATE TABLE would use: by the time this runs the table exists,
|
|
456
|
-
// whether Atlas just created it or it has been live for a year.
|
|
457
|
-
ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${vectorColumnDefinition(spec)};\n`;
|
|
458
|
-
}
|
|
459
|
-
const plan = buildVectorIndexPlan(collection, resolveColumnName);
|
|
460
|
-
vectorIndexStatements(plan).forEach(s => { ddl += `${s}\n`; });
|
|
461
|
-
for (const skip of plan.skipped) {
|
|
462
|
-
ddl += `-- No ANN index on "${skip.schema}"."${skip.table}"."${skip.column}": ${skip.reason}\n`;
|
|
463
|
-
}
|
|
464
|
-
ddl += "\n";
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
return ddl;
|
|
468
|
-
};
|
|
469
|
-
|
|
470
|
-
/**
|
|
471
|
-
* Glob patterns telling Atlas to leave the vector column and its ANN indexes
|
|
472
|
-
* alone.
|
|
473
|
-
*
|
|
474
|
-
* Without these, a desired state that omits the column reads to Atlas as an
|
|
475
|
-
* instruction to drop it, taking the embeddings and the indexes with it on the
|
|
476
|
-
* next push.
|
|
477
|
-
*
|
|
478
|
-
* Fully qualified, `schema.table.object`, for the reason spelled out on
|
|
479
|
-
* {@link searchExcludePatterns}: the two-part form matches nothing and reports
|
|
480
|
-
* no error, which turns a protection into a `DROP COLUMN`.
|
|
481
|
-
*/
|
|
482
|
-
export const vectorExcludePatterns = (allCollections: CollectionConfig[]): string[] => {
|
|
483
|
-
const patterns: string[] = [];
|
|
484
|
-
for (const collection of relationalCollections(allCollections)) {
|
|
485
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
486
|
-
const table = getTableName(collection);
|
|
487
|
-
for (const name of vectorObjectNames(collection, resolveColumnName)) {
|
|
488
|
-
patterns.push(`${schema}.${table}.${name}`);
|
|
489
|
-
}
|
|
490
|
-
}
|
|
491
|
-
return patterns;
|
|
492
|
-
};
|
|
493
|
-
|
|
494
|
-
export const generatePostgresDdl = async (
|
|
495
|
-
allCollections: CollectionConfig[],
|
|
496
|
-
options: { includePolicies?: boolean; includeSearch?: boolean; includeVector?: boolean } = {
|
|
497
|
-
includePolicies: true,
|
|
498
|
-
includeSearch: true,
|
|
499
|
-
includeVector: true
|
|
500
|
-
}
|
|
501
|
-
): Promise<string> => {
|
|
502
|
-
// Only the collections this engine stores. See `relationalCollections`.
|
|
503
|
-
const collections = relationalCollections(allCollections);
|
|
504
|
-
let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n\n";
|
|
505
|
-
|
|
506
|
-
// 1. Create custom schemas.
|
|
507
|
-
//
|
|
508
|
-
// `rebase` is unconditional and load-bearing. The RLS helper functions live
|
|
509
|
-
// in it, so the migration preamble creates it — which puts it in Atlas's
|
|
510
|
-
// replayed state, and anything in that state but absent from this desired
|
|
511
|
-
// schema gets a `DROP SCHEMA … CASCADE` planned against it. That would take
|
|
512
|
-
// the auth tables. It used to appear here only when some collection
|
|
513
|
-
// happened to declare `schema: "rebase"`; the scaffold's users collection
|
|
514
|
-
// does, which is why nobody hit it, but nothing guaranteed it.
|
|
515
|
-
const uniqueSchemas = Array.from(new Set([
|
|
516
|
-
REBASE_SCHEMA,
|
|
517
|
-
...collections.map(c => isPostgresCollectionConfig(c) ? c.schema : undefined).filter(Boolean)
|
|
518
|
-
]));
|
|
519
|
-
uniqueSchemas.forEach(schema => {
|
|
520
|
-
if (schema) ddl += `CREATE SCHEMA IF NOT EXISTS "${schema}";\n`;
|
|
521
|
-
});
|
|
522
|
-
if (uniqueSchemas.length > 0) ddl += "\n";
|
|
523
|
-
|
|
524
|
-
// 1b. Search support, for collections that opted in.
|
|
525
|
-
//
|
|
526
|
-
// Extensions and helper functions come before every CREATE TABLE because a
|
|
527
|
-
// generated column's expression is resolved at creation time: a table whose
|
|
528
|
-
// search column calls `rebase_search_text` cannot be created before that
|
|
529
|
-
// function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file
|
|
530
|
-
// replayed against a live database is a no-op here.
|
|
531
|
-
const searchSpecs = collections
|
|
532
|
-
.map(c => buildSearchColumnSpec(c))
|
|
533
|
-
.filter((s): s is SearchColumnSpec => s !== undefined);
|
|
534
|
-
|
|
535
|
-
if (searchSpecs.length > 0) {
|
|
536
|
-
if (options.includeSearch === false) {
|
|
537
|
-
// Everything search-related lives in `search.sql` — see
|
|
538
|
-
// `generatePostgresSearchDdl` for why Atlas is not shown any of it.
|
|
539
|
-
ddl += "-- Full-text search support lives in `search.sql`, applied separately.\n\n";
|
|
540
|
-
} else {
|
|
541
|
-
const extensions = Array.from(new Set(searchSpecs.flatMap(searchExtensionStatements)));
|
|
542
|
-
const helpers = Array.from(new Set(searchSpecs.flatMap(searchHelperFunctions)));
|
|
543
|
-
ddl += "-- Full-text search support (collections declaring a `search` block)\n";
|
|
544
|
-
extensions.forEach(s => { ddl += `${s}\n`; });
|
|
545
|
-
if (extensions.length > 0) ddl += "\n";
|
|
546
|
-
helpers.forEach(s => { ddl += `${s}\n\n`; });
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
// 1c. Vector support, for collections that declared a `vector` property.
|
|
551
|
-
//
|
|
552
|
-
// Only a note, never a statement — unlike 1b, which emits search's
|
|
553
|
-
// extensions when they are included. `CREATE EXTENSION vector` is the one
|
|
554
|
-
// thing this file must never carry whichever way the flag goes: Atlas
|
|
555
|
-
// rejects an extension in a desired state as a paid feature. The note is
|
|
556
|
-
// for whoever opens the generated file looking for the column.
|
|
557
|
-
if (options.includeVector === false
|
|
558
|
-
&& collections.some(c => buildVectorColumnSpecs(c, resolveColumnName).length > 0)) {
|
|
559
|
-
ddl += "-- Vector columns and their ANN indexes live in `vector.sql`, applied separately.\n\n";
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
// 2. Generate Enums
|
|
563
|
-
//
|
|
564
|
-
// The enum type name is derived from table + column, so two collections
|
|
565
|
-
// mapped onto the same table — or two properties whose `columnName`
|
|
566
|
-
// resolves to the same column — land on the same name. `CREATE TYPE` has no
|
|
567
|
-
// IF NOT EXISTS, so emitting it twice aborts the whole file on the second
|
|
568
|
-
// statement. Dedupe by name, matching planCollectionSchemaEnsure.
|
|
569
|
-
const emittedEnums = new Set<string>();
|
|
570
|
-
collections.forEach(collection => {
|
|
571
|
-
const collectionTable = getTableName(collection);
|
|
572
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
573
|
-
Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
|
|
574
|
-
if (("enum" in prop) && (prop.type === "string" || prop.type === "number") && prop.enum) {
|
|
575
|
-
const enumDbName = `${collectionTable}_${resolveColumnName(propName, prop)}`;
|
|
576
|
-
const values = Array.isArray(prop.enum)
|
|
577
|
-
? (prop.enum as (string | number | { id: string | number })[]).map((v: string | number | { id: string | number }) =>
|
|
578
|
-
String(typeof v === "object" && v !== null && "id" in v ? v.id : v)
|
|
579
|
-
)
|
|
580
|
-
: Object.keys(prop.enum);
|
|
581
|
-
if (values.length > 0 && !emittedEnums.has(`${schema}.${enumDbName}`)) {
|
|
582
|
-
emittedEnums.add(`${schema}.${enumDbName}`);
|
|
583
|
-
ddl += `CREATE TYPE "${schema}"."${enumDbName}" AS ENUM (${values.map(quoteSqlLiteral).join(", ")});\n`;
|
|
584
|
-
}
|
|
585
|
-
}
|
|
586
|
-
});
|
|
587
|
-
});
|
|
588
|
-
if (ddl.endsWith(";\n")) ddl += "\n";
|
|
589
|
-
|
|
590
|
-
// Junction policy derivation needs every declaring side of each junction,
|
|
591
|
-
// not just the first relation that reached it in the walk below.
|
|
592
|
-
const junctionSpecs = resolveJunctionSpecs(collections);
|
|
593
|
-
|
|
594
|
-
const allTablesToGenerate = new Map<string, {
|
|
595
|
-
collection: CollectionConfig,
|
|
596
|
-
isJunction?: boolean,
|
|
597
|
-
relation?: ResolvedRelation,
|
|
598
|
-
sourceCollection?: CollectionConfig
|
|
599
|
-
}>();
|
|
600
|
-
|
|
601
|
-
// Identify all tables
|
|
602
|
-
for (const collection of collections) {
|
|
603
|
-
const tableName = getTableName(collection);
|
|
604
|
-
if (tableName) {
|
|
605
|
-
allTablesToGenerate.set(tableName, { collection });
|
|
606
|
-
}
|
|
607
|
-
|
|
608
|
-
const resolvedRelations = resolveCollectionRelations(collection);
|
|
609
|
-
for (const relation of Object.values(resolvedRelations)) {
|
|
610
|
-
if (isManyToMany(relation)) {
|
|
611
|
-
const junctionTableName = relation.through.table;
|
|
612
|
-
if (!allTablesToGenerate.has(junctionTableName)) {
|
|
613
|
-
allTablesToGenerate.set(junctionTableName, {
|
|
614
|
-
collection: {
|
|
615
|
-
table: junctionTableName,
|
|
616
|
-
properties: {}
|
|
617
|
-
} as CollectionConfig,
|
|
618
|
-
isJunction: true,
|
|
619
|
-
relation: relation,
|
|
620
|
-
sourceCollection: collection
|
|
621
|
-
});
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
}
|
|
625
|
-
}
|
|
626
|
-
|
|
627
|
-
// 3. Generate tables
|
|
628
|
-
const fkStatements: string[] = [];
|
|
629
|
-
// Indexes follow the tables for the same reason the FK constraints do: the
|
|
630
|
-
// table has to exist first.
|
|
631
|
-
const indexStatements: string[] = [];
|
|
632
|
-
// Policies are emitted after every CREATE TABLE, like the FK constraints:
|
|
633
|
-
// a policy may reference other tables (a junction's derived policies always
|
|
634
|
-
// reference both endpoints; `policy.existsIn` references a join table), and
|
|
635
|
-
// CREATE POLICY validates those relations at creation time.
|
|
636
|
-
const policyStatements: string[] = [];
|
|
637
|
-
for (const [tableName, {
|
|
638
|
-
collection,
|
|
639
|
-
isJunction,
|
|
640
|
-
relation,
|
|
641
|
-
sourceCollection
|
|
642
|
-
}] of allTablesToGenerate.entries()) {
|
|
643
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
644
|
-
const baseTableName = tableName.includes(".") ? tableName.split(".").pop()! : tableName;
|
|
645
|
-
|
|
646
|
-
if (isJunction && relation && sourceCollection && isManyToMany(relation)) {
|
|
647
|
-
const targetCollection = relation.target();
|
|
648
|
-
const sourceTable = getTableName(sourceCollection);
|
|
649
|
-
const targetTable = getTableName(targetCollection);
|
|
650
|
-
const sourceSchema = isPostgresCollectionConfig(sourceCollection) && sourceCollection.schema ? sourceCollection.schema : "public";
|
|
651
|
-
const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
|
|
652
|
-
const { sourceColumn, targetColumn } = relation.through;
|
|
653
|
-
|
|
654
|
-
// TEXT, matching the string default: a junction column has to have the
|
|
655
|
-
// same type as the primary key it references.
|
|
656
|
-
const sourceColType = isNumericId(sourceCollection) ? "INTEGER" : (getPrimaryKeyProp(sourceCollection).isUuid ? "UUID" : "TEXT");
|
|
657
|
-
const targetColType = isNumericId(targetCollection) ? "INTEGER" : (getPrimaryKeyProp(targetCollection).isUuid ? "UUID" : "TEXT");
|
|
658
|
-
const sourceId = getPrimaryKeyName(sourceCollection);
|
|
659
|
-
const targetId = getPrimaryKeyName(targetCollection);
|
|
660
|
-
|
|
661
|
-
const onDelete = relation.onDelete ?? "CASCADE";
|
|
662
|
-
|
|
663
|
-
ddl += `CREATE TABLE "${schema}"."${baseTableName}" (\n`;
|
|
664
|
-
ddl += ` "${sourceColumn}" ${sourceColType} NOT NULL,\n`;
|
|
665
|
-
ddl += ` "${targetColumn}" ${targetColType} NOT NULL,\n`;
|
|
666
|
-
ddl += ` PRIMARY KEY ("${sourceColumn}", "${targetColumn}")\n`;
|
|
667
|
-
ddl += `);\n\n`;
|
|
668
|
-
|
|
669
|
-
fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${sourceColumn}_fkey`)}" FOREIGN KEY ("${sourceColumn}") REFERENCES "${sourceSchema}"."${sourceTable}" ("${sourceId}") ON DELETE ${onDelete.toUpperCase()};`);
|
|
670
|
-
fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${targetColumn}_fkey`)}" FOREIGN KEY ("${targetColumn}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDelete.toUpperCase()};`);
|
|
671
|
-
|
|
672
|
-
if (options.includePolicies) {
|
|
673
|
-
// Junction tables are generated tables like any other: locked by
|
|
674
|
-
// default, with derived policies — reads follow the endpoints'
|
|
675
|
-
// visibility, writes follow the declaring side's update rules.
|
|
676
|
-
// Without this they were the one kind of generated table with no
|
|
677
|
-
// RLS at all, readable and writable by every signed-in user.
|
|
678
|
-
ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
|
|
679
|
-
ddl += `\n`;
|
|
680
|
-
|
|
681
|
-
const spec = junctionSpecs.get(baseTableName);
|
|
682
|
-
if (spec) {
|
|
683
|
-
const junctionCollection = getJunctionCollectionConfig(spec);
|
|
684
|
-
const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);
|
|
685
|
-
getJunctionSecurityRules(spec).forEach((rule: SecurityRule) => {
|
|
686
|
-
policyStatements.push(generatePolicyDdl(junctionCollection, rule, resolveCollection));
|
|
687
|
-
});
|
|
688
|
-
}
|
|
689
|
-
}
|
|
690
|
-
} else if (!isJunction) {
|
|
691
|
-
ddl += `CREATE TABLE "${schema}"."${baseTableName}" (\n`;
|
|
692
|
-
const columns: string[] = [];
|
|
693
|
-
|
|
694
|
-
Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {
|
|
695
|
-
// A vector column is not Atlas's — `vector.sql` adds it. Skipped
|
|
696
|
-
// here rather than filtered upstream so the column keeps its
|
|
697
|
-
// place in the generator's order when it *is* included, which is
|
|
698
|
-
// what the derived-names contract renders.
|
|
699
|
-
if (prop.type === "vector" && options.includeVector === false) {
|
|
700
|
-
return;
|
|
701
|
-
}
|
|
702
|
-
if (prop.type === "relation") {
|
|
703
|
-
const refProp = prop as RelationProperty;
|
|
704
|
-
const resolvedRelations = resolveCollectionRelations(collection);
|
|
705
|
-
const relInfo = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);
|
|
706
|
-
|
|
707
|
-
if (relInfo?.kind !== "belongsTo") {
|
|
708
|
-
return;
|
|
709
|
-
}
|
|
710
|
-
|
|
711
|
-
if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) {
|
|
712
|
-
return;
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
let targetCollection: CollectionConfig;
|
|
716
|
-
try {
|
|
717
|
-
targetCollection = relInfo.target();
|
|
718
|
-
} catch {
|
|
719
|
-
return;
|
|
720
|
-
}
|
|
721
|
-
|
|
722
|
-
const targetTable = getTableName(targetCollection);
|
|
723
|
-
const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
|
|
724
|
-
const targetId = getPrimaryKeyName(targetCollection);
|
|
725
|
-
const fkColType = getSqlColumnType(propName, prop, collection, collections);
|
|
726
|
-
|
|
727
|
-
const onUpdate = relInfo.onUpdate ? ` ON UPDATE ${relInfo.onUpdate.toUpperCase()}` : "";
|
|
728
|
-
const required = prop.validation?.required;
|
|
729
|
-
const onDeleteVal = relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL");
|
|
730
|
-
|
|
731
|
-
let colDef = ` "${relInfo.localKey}" ${fkColType}`;
|
|
732
|
-
if (required) colDef += " NOT NULL";
|
|
733
|
-
columns.push(colDef);
|
|
734
|
-
|
|
735
|
-
fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${relInfo.localKey}_fkey`)}" FOREIGN KEY ("${relInfo.localKey}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDeleteVal.toUpperCase()}${onUpdate};`);
|
|
736
|
-
} else if (prop.type === "reference") {
|
|
737
|
-
const refProp = prop as ReferenceProperty;
|
|
738
|
-
const targetCollection = collections.find(c => c.slug === refProp.path || getTableName(c) === refProp.path);
|
|
739
|
-
const colName = resolveColumnName(propName, prop);
|
|
740
|
-
const colType = getSqlColumnType(propName, prop, collection, collections);
|
|
741
|
-
const required = prop.validation?.required;
|
|
742
|
-
|
|
743
|
-
if (!targetCollection) {
|
|
744
|
-
let colDef = ` "${colName}" ${colType}`;
|
|
745
|
-
if (required) colDef += " NOT NULL";
|
|
746
|
-
columns.push(colDef);
|
|
747
|
-
} else {
|
|
748
|
-
const targetTable = getTableName(targetCollection);
|
|
749
|
-
const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : "public";
|
|
750
|
-
const targetId = getPrimaryKeyName(targetCollection);
|
|
751
|
-
const onDelete = required ? "CASCADE" : "SET NULL";
|
|
752
|
-
|
|
753
|
-
let colDef = ` "${colName}" ${colType}`;
|
|
754
|
-
if (required) colDef += " NOT NULL";
|
|
755
|
-
columns.push(colDef);
|
|
756
|
-
|
|
757
|
-
fkStatements.push(`ALTER TABLE "${schema}"."${baseTableName}" ADD CONSTRAINT "${toPostgresIdentifier(`${baseTableName}_${colName}_fkey`)}" FOREIGN KEY ("${colName}") REFERENCES "${targetSchema}"."${targetTable}" ("${targetId}") ON DELETE ${onDelete.toUpperCase()};`);
|
|
758
|
-
}
|
|
759
|
-
} else {
|
|
760
|
-
const colName = resolveColumnName(propName, prop);
|
|
761
|
-
|
|
762
|
-
// On an auth collection, the columns auth reads and writes
|
|
763
|
-
// are defined once, in `auth-users-columns`, and every
|
|
764
|
-
// creator of this table emits that definition. Before this,
|
|
765
|
-
// the desired state here was built from the collection file
|
|
766
|
-
// alone — which knows nothing of `is_anonymous` or
|
|
767
|
-
// `tokens_valid_after` — so `db push` and the runtime
|
|
768
|
-
// disagreed about `email`'s nullability and about which
|
|
769
|
-
// columns exist at all.
|
|
770
|
-
const authDefinition = isAuthCollection(collection)
|
|
771
|
-
? authUsersColumnDefinition(colName)
|
|
772
|
-
: undefined;
|
|
773
|
-
if (authDefinition && !isIdProperty(propName, prop, collection)) {
|
|
774
|
-
columns.push(` "${colName}" ${authDefinition}`);
|
|
775
|
-
return;
|
|
776
|
-
}
|
|
777
|
-
|
|
778
|
-
const colType = getSqlColumnType(propName, prop, collection, collections);
|
|
779
|
-
let colDef = ` "${colName}" ${colType}`;
|
|
780
|
-
|
|
781
|
-
if (isIdProperty(propName, prop, collection)) {
|
|
782
|
-
colDef += " PRIMARY KEY";
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
if ("isId" in prop && prop.isId !== "manual" && prop.isId !== true && prop.isId !== "increment") {
|
|
786
|
-
if (prop.isId === "uuid") {
|
|
787
|
-
colDef += " DEFAULT gen_random_uuid()";
|
|
788
|
-
} else if (prop.isId === "cuid") {
|
|
789
|
-
colDef += " DEFAULT cuid()";
|
|
790
|
-
} else if (typeof prop.isId === "string") {
|
|
791
|
-
colDef += ` DEFAULT ${prop.isId}`;
|
|
792
|
-
}
|
|
793
|
-
}
|
|
794
|
-
|
|
795
|
-
if (!isIdProperty(propName, prop, collection) && prop.validation?.unique) {
|
|
796
|
-
colDef += " UNIQUE";
|
|
797
|
-
}
|
|
798
|
-
|
|
799
|
-
if (prop.type === "date") {
|
|
800
|
-
const dateProp = prop as DateProperty;
|
|
801
|
-
if (dateProp.autoValue === "on_create" || dateProp.autoValue === "on_update") {
|
|
802
|
-
colDef += " DEFAULT now()";
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
|
|
806
|
-
if (prop.validation?.required && !colDef.includes("PRIMARY KEY")) {
|
|
807
|
-
colDef += " NOT NULL";
|
|
808
|
-
}
|
|
809
|
-
|
|
810
|
-
columns.push(colDef);
|
|
811
|
-
}
|
|
812
|
-
});
|
|
813
|
-
|
|
814
|
-
// ── Auth columns the collection file never mentions ──────────────
|
|
815
|
-
// `db push` is declarative: Atlas diffs the database against exactly
|
|
816
|
-
// what is emitted here and drops anything else. The scaffold's users
|
|
817
|
-
// collection describes 12 columns while auth needs 14, so
|
|
818
|
-
// `is_anonymous` and `tokens_valid_after` — created at boot by
|
|
819
|
-
// `ensureAuthTablesExist` — read as unmanaged drift, and a push run
|
|
820
|
-
// after the server had started once planned to DROP them. The
|
|
821
|
-
// destructive gate catches it, which makes it a data-loss prompt on
|
|
822
|
-
// the auth table rather than silent damage; either way the desired
|
|
823
|
-
// state was wrong. Emit the full contract so the two agree.
|
|
824
|
-
if (isAuthCollection(collection)) {
|
|
825
|
-
const declared = new Set(
|
|
826
|
-
Object.entries(collection.properties ?? {})
|
|
827
|
-
.map(([name, prop]) => resolveColumnName(name, prop))
|
|
828
|
-
);
|
|
829
|
-
for (const spec of AUTH_USERS_COLUMNS) {
|
|
830
|
-
if (declared.has(spec.column)) continue;
|
|
831
|
-
columns.push(` "${spec.column}" ${authUsersColumnSql(spec)}`);
|
|
832
|
-
}
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
// ── The opt-in search column ─────────────────────────────────────
|
|
836
|
-
// Last, so it reads as what it is: derived from the columns above
|
|
837
|
-
// it. Postgres recomputes it on every write of a source column and
|
|
838
|
-
// rejects any attempt to write it directly, which is the property
|
|
839
|
-
// that makes it impossible for the index to drift from the row.
|
|
840
|
-
const searchSpec = options.includeSearch === false ? undefined : buildSearchColumnSpec(collection);
|
|
841
|
-
if (searchSpec) {
|
|
842
|
-
columns.push(` ${searchColumnDefinition(searchSpec)}`);
|
|
843
|
-
const fuzzyDef = fuzzyColumnDefinition(searchSpec);
|
|
844
|
-
if (fuzzyDef) columns.push(` ${fuzzyDef}`);
|
|
845
|
-
indexStatements.push(...searchIndexStatements(searchSpec));
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
// ANN indexes for vector columns. Emitted with the other indexes
|
|
849
|
-
// rather than inline, because `CREATE INDEX` is a statement and a
|
|
850
|
-
// column definition is not — and because a column too wide for
|
|
851
|
-
// pgvector to index still needs its column.
|
|
852
|
-
//
|
|
853
|
-
// Absent alongside their column when vector is carved out: an index
|
|
854
|
-
// over a column this file no longer declares would not resolve, and
|
|
855
|
-
// `USING hnsw` needs the extension the dev database cannot have.
|
|
856
|
-
if (options.includeVector !== false) {
|
|
857
|
-
const vectorPlan: VectorIndexPlan = buildVectorIndexPlan(collection, resolveColumnName);
|
|
858
|
-
indexStatements.push(...vectorIndexStatements(vectorPlan));
|
|
859
|
-
for (const skip of vectorPlan.skipped) {
|
|
860
|
-
indexStatements.push(`-- No ANN index on "${skip.schema}"."${skip.table}"."${skip.column}": ${skip.reason}`);
|
|
861
|
-
}
|
|
862
|
-
}
|
|
863
|
-
|
|
864
|
-
// The collection's own `indexes:` block. Last of the three index
|
|
865
|
-
// producers, and the only one the developer wrote deliberately
|
|
866
|
-
// rather than getting as a side effect of another feature.
|
|
867
|
-
indexStatements.push(...collectionIndexStatements(
|
|
868
|
-
buildCollectionIndexSpecs(collection, resolveColumnName)
|
|
869
|
-
));
|
|
870
|
-
|
|
871
|
-
// The implicit primary key, for a collection that declares none.
|
|
872
|
-
const hasPk = columns.some(c => c.includes("PRIMARY KEY"));
|
|
873
|
-
if (!hasPk) {
|
|
874
|
-
columns.unshift(' "id" TEXT PRIMARY KEY');
|
|
875
|
-
}
|
|
876
|
-
|
|
877
|
-
ddl += columns.join(",\n");
|
|
878
|
-
ddl += `\n);\n\n`;
|
|
879
|
-
|
|
880
|
-
if (options.includePolicies) {
|
|
881
|
-
// Enable RLS and add Policies. No FORCE: authenticated requests
|
|
882
|
-
// run as the non-owner `rebase_user` role, which plain ENABLE
|
|
883
|
-
// already binds. The owner (server context) must bypass — it is
|
|
884
|
-
// the trusted plane (auth flows, dataAsAdmin).
|
|
885
|
-
ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
|
|
886
|
-
ddl += `\n`;
|
|
887
|
-
|
|
888
|
-
const securityRules = getEffectiveSecurityRules(collection);
|
|
889
|
-
if (securityRules.length > 0) {
|
|
890
|
-
const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);
|
|
891
|
-
securityRules.forEach((rule: SecurityRule) => {
|
|
892
|
-
policyStatements.push(generatePolicyDdl(collection, rule, resolveCollection));
|
|
893
|
-
});
|
|
894
|
-
}
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
|
-
|
|
899
|
-
// Indexes before foreign keys. Today every FK targets a primary key created
|
|
900
|
-
// inline, so the order is safe by accident; the moment a declared
|
|
901
|
-
// `unique: true` index can back an FK target, a constraint emitted first
|
|
902
|
-
// would reference an index that does not exist yet.
|
|
903
|
-
if (indexStatements.length > 0) {
|
|
904
|
-
ddl += "-- Indexes\n";
|
|
905
|
-
ddl += indexStatements.join("\n") + "\n\n";
|
|
906
|
-
}
|
|
907
|
-
|
|
908
|
-
if (fkStatements.length > 0) {
|
|
909
|
-
ddl += "-- Foreign Key Constraints\n";
|
|
910
|
-
ddl += fkStatements.join("\n") + "\n\n";
|
|
911
|
-
}
|
|
912
|
-
|
|
913
|
-
if (policyStatements.length > 0) {
|
|
914
|
-
ddl += "-- Row Level Security Policies\n";
|
|
915
|
-
ddl += policyStatements.join("");
|
|
916
|
-
ddl += "\n";
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
return ddl;
|
|
920
|
-
};
|
|
921
|
-
|
|
922
|
-
/** The RLS statements one declared collection's table needs, ready to run. */
|
|
923
|
-
/**
|
|
924
|
-
* A foreign key, as both its parts and the statement that creates it.
|
|
925
|
-
*
|
|
926
|
-
* `ALTER TABLE … ADD CONSTRAINT` has no `IF NOT EXISTS`, so a caller applying
|
|
927
|
-
* these has to skip by name — hence the name is a field and not only a substring
|
|
928
|
-
* of the SQL.
|
|
929
|
-
*/
|
|
930
|
-
export interface ForeignKeyPlan {
|
|
931
|
-
constraintName: string;
|
|
932
|
-
schema: string;
|
|
933
|
-
/** Bare table name, no schema prefix. */
|
|
934
|
-
table: string;
|
|
935
|
-
column: string;
|
|
936
|
-
targetSchema: string;
|
|
937
|
-
targetTable: string;
|
|
938
|
-
targetColumn: string;
|
|
939
|
-
sql: string;
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
/** A column a `relation` or `reference` property owns on its own table. */
|
|
943
|
-
export interface RelationalColumnPlan {
|
|
944
|
-
schema: string;
|
|
945
|
-
/** Bare table name, no schema prefix. */
|
|
946
|
-
table: string;
|
|
947
|
-
column: string;
|
|
948
|
-
/** Postgres type, exactly as the DDL generator declares it. */
|
|
949
|
-
type: string;
|
|
950
|
-
/** Absent when the target collection is not part of this bundle. */
|
|
951
|
-
foreignKey?: ForeignKeyPlan;
|
|
952
|
-
/**
|
|
953
|
-
* What this column would have been called before `generateForeignKeyName`
|
|
954
|
-
* learned to singularize — set only when the two differ and the column name
|
|
955
|
-
* is the derived default rather than one the author wrote.
|
|
956
|
-
*
|
|
957
|
-
* Carried so the boot-time ensure can notice a database provisioned under
|
|
958
|
-
* the old rule. It is never used to name anything.
|
|
959
|
-
*/
|
|
960
|
-
legacyColumn?: string;
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
/** The table behind a many-to-many `through` relation. */
|
|
964
|
-
export interface JunctionTablePlan {
|
|
965
|
-
schema: string;
|
|
966
|
-
/** Bare table name, no schema prefix. */
|
|
967
|
-
table: string;
|
|
968
|
-
columns: { name: string; type: string; legacyName?: string }[];
|
|
969
|
-
/** Both endpoint columns plus the composite primary key. */
|
|
970
|
-
createTable: string;
|
|
971
|
-
foreignKeys: ForeignKeyPlan[];
|
|
972
|
-
}
|
|
973
|
-
|
|
974
|
-
const schemaOfCollection = (collection: CollectionConfig): string =>
|
|
975
|
-
isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
976
|
-
|
|
977
|
-
const bareTableName = (name: string): string => (name.includes(".") ? name.split(".").pop()! : name);
|
|
978
|
-
|
|
979
|
-
/**
|
|
980
|
-
* Truncate a derived identifier the way Postgres does: to 63 bytes, silently.
|
|
981
|
-
*
|
|
982
|
-
* This is not cosmetic, and not really a naming choice at all — it is agreeing
|
|
983
|
-
* with the name the database ALREADY stored. `ADD CONSTRAINT` on a longer name
|
|
984
|
-
* succeeds and records the truncated form, so the untruncated name this used to
|
|
985
|
-
* derive matched nothing in the catalogue. Boot-ensure compares its planned
|
|
986
|
-
* constraints against `readExistingSchema`, which reads catalogue names, so the
|
|
987
|
-
* comparison could never hit: every boot re-issued `ADD CONSTRAINT` for the same
|
|
988
|
-
* constraint, forever, and got "already exists" every time. Non-fatal (foreign
|
|
989
|
-
* keys are the one action allowed to fail) and therefore permanent — an error in
|
|
990
|
-
* the log on every restart of a project whose table and column names happened to
|
|
991
|
-
* be long.
|
|
992
|
-
*
|
|
993
|
-
* Byte length, not string length: NAMEDATALEN is 64 bytes, and a multi-byte
|
|
994
|
-
* character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.
|
|
995
|
-
*/
|
|
996
|
-
// Moved to `@rebasepro/utils` so the search-column builder derives index names
|
|
997
|
-
// under the same 63-byte rule this file derives constraint names under. Two
|
|
998
|
-
// copies of a truncation rule is two rules the moment one of them is edited.
|
|
999
|
-
|
|
1000
|
-
const foreignKeyPlan = (
|
|
1001
|
-
args: Omit<ForeignKeyPlan, "constraintName" | "sql"> & { onDelete: string; onUpdate?: string }
|
|
1002
|
-
): ForeignKeyPlan => {
|
|
1003
|
-
const constraintName = toPostgresIdentifier(`${args.table}_${args.column}_fkey`);
|
|
1004
|
-
const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : "";
|
|
1005
|
-
return {
|
|
1006
|
-
constraintName,
|
|
1007
|
-
schema: args.schema,
|
|
1008
|
-
table: args.table,
|
|
1009
|
-
column: args.column,
|
|
1010
|
-
targetSchema: args.targetSchema,
|
|
1011
|
-
targetTable: args.targetTable,
|
|
1012
|
-
targetColumn: args.targetColumn,
|
|
1013
|
-
sql:
|
|
1014
|
-
`ALTER TABLE "${args.schema}"."${args.table}" ADD CONSTRAINT "${constraintName}" ` +
|
|
1015
|
-
`FOREIGN KEY ("${args.column}") REFERENCES "${args.targetSchema}"."${args.targetTable}" ` +
|
|
1016
|
-
`("${args.targetColumn}") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate};`
|
|
1017
|
-
};
|
|
1018
|
-
};
|
|
1019
|
-
|
|
1020
|
-
/**
|
|
1021
|
-
* The FK columns the declared collections own — one entry per `relation`
|
|
1022
|
-
* (`belongsTo` side) or `reference` property.
|
|
1023
|
-
*
|
|
1024
|
-
* Split out of {@link generatePostgresDdl} so the boot-time schema ensure can
|
|
1025
|
-
* create the same columns with the same names, types and constraints. Before
|
|
1026
|
-
* this it skipped them outright, which was survivable only because `db push`
|
|
1027
|
-
* always followed; on a managed tenant nothing follows, so a table arrived
|
|
1028
|
-
* without the column its own collection reads and wrote 400 on every insert.
|
|
1029
|
-
*
|
|
1030
|
-
* A relation whose target is not in the bundle yields no column at all (the
|
|
1031
|
-
* generator returns early on an unresolvable target); a `reference` whose target
|
|
1032
|
-
* is unknown yields the column without a constraint. Both mirror the generator
|
|
1033
|
-
* exactly — a divergence here is a schema fork between boot and `db push`.
|
|
1034
|
-
*/
|
|
1035
|
-
export const planRelationalColumns = (allCollections: CollectionConfig[]): RelationalColumnPlan[] => {
|
|
1036
|
-
const collections = relationalCollections(allCollections);
|
|
1037
|
-
const plans: RelationalColumnPlan[] = [];
|
|
1038
|
-
|
|
1039
|
-
for (const collection of collections) {
|
|
1040
|
-
const tableName = getTableName(collection);
|
|
1041
|
-
if (!tableName) continue;
|
|
1042
|
-
const schema = schemaOfCollection(collection);
|
|
1043
|
-
const table = bareTableName(tableName);
|
|
1044
|
-
|
|
1045
|
-
for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {
|
|
1046
|
-
const prop = rawProp as Property;
|
|
1047
|
-
|
|
1048
|
-
if (prop.type === "relation") {
|
|
1049
|
-
const refProp = prop as RelationProperty;
|
|
1050
|
-
const resolvedRelations = resolveCollectionRelations(collection);
|
|
1051
|
-
const relInfo = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);
|
|
1052
|
-
if (relInfo?.kind !== "belongsTo") continue;
|
|
1053
|
-
// The relation and an explicit FK property can both be declared;
|
|
1054
|
-
// the explicit one owns the column.
|
|
1055
|
-
if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) continue;
|
|
1056
|
-
|
|
1057
|
-
let targetCollection: CollectionConfig;
|
|
1058
|
-
try {
|
|
1059
|
-
targetCollection = relInfo.target();
|
|
1060
|
-
} catch {
|
|
1061
|
-
continue;
|
|
1062
|
-
}
|
|
1063
|
-
if (!targetCollection) continue;
|
|
1064
|
-
|
|
1065
|
-
const required = prop.validation?.required;
|
|
1066
|
-
// Only a *derived* column name can be affected by the change to
|
|
1067
|
-
// `generateForeignKeyName`; one the author wrote is theirs.
|
|
1068
|
-
const relationName = refProp.relation?.relationName ?? propName;
|
|
1069
|
-
const legacyKey = legacyForeignKeyName(relationName);
|
|
1070
|
-
const derived = relInfo.localKey === generateForeignKeyName(relationName);
|
|
1071
|
-
plans.push({
|
|
1072
|
-
schema,
|
|
1073
|
-
table,
|
|
1074
|
-
column: relInfo.localKey,
|
|
1075
|
-
legacyColumn: derived && legacyKey !== relInfo.localKey ? legacyKey : undefined,
|
|
1076
|
-
type: getSqlColumnType(propName, prop, collection, collections),
|
|
1077
|
-
foreignKey: foreignKeyPlan({
|
|
1078
|
-
schema,
|
|
1079
|
-
table,
|
|
1080
|
-
column: relInfo.localKey,
|
|
1081
|
-
targetSchema: schemaOfCollection(targetCollection),
|
|
1082
|
-
targetTable: bareTableName(getTableName(targetCollection)),
|
|
1083
|
-
targetColumn: getPrimaryKeyName(targetCollection),
|
|
1084
|
-
onDelete: relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL"),
|
|
1085
|
-
onUpdate: relInfo.onUpdate
|
|
1086
|
-
})
|
|
1087
|
-
});
|
|
1088
|
-
} else if (prop.type === "reference") {
|
|
1089
|
-
const refProp = prop as ReferenceProperty;
|
|
1090
|
-
const targetCollection = collections.find(
|
|
1091
|
-
c => c.slug === refProp.path || getTableName(c) === refProp.path
|
|
1092
|
-
);
|
|
1093
|
-
const column = resolveColumnName(propName, prop);
|
|
1094
|
-
const type = getSqlColumnType(propName, prop, collection, collections);
|
|
1095
|
-
const required = prop.validation?.required;
|
|
1096
|
-
|
|
1097
|
-
plans.push({
|
|
1098
|
-
schema,
|
|
1099
|
-
table,
|
|
1100
|
-
column,
|
|
1101
|
-
type,
|
|
1102
|
-
foreignKey: targetCollection
|
|
1103
|
-
? foreignKeyPlan({
|
|
1104
|
-
schema,
|
|
1105
|
-
table,
|
|
1106
|
-
column,
|
|
1107
|
-
targetSchema: schemaOfCollection(targetCollection),
|
|
1108
|
-
targetTable: bareTableName(getTableName(targetCollection)),
|
|
1109
|
-
targetColumn: getPrimaryKeyName(targetCollection),
|
|
1110
|
-
onDelete: required ? "CASCADE" : "SET NULL"
|
|
1111
|
-
})
|
|
1112
|
-
: undefined
|
|
1113
|
-
});
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
}
|
|
1117
|
-
|
|
1118
|
-
return plans;
|
|
1119
|
-
};
|
|
1120
|
-
|
|
1121
|
-
/**
|
|
1122
|
-
* The junction tables a bundle's many-to-many relations imply.
|
|
1123
|
-
*
|
|
1124
|
-
* Derived from {@link resolveJunctionSpecs}, the same source the junction RLS
|
|
1125
|
-
* comes from, so a table created here always has policies planned for it — a
|
|
1126
|
-
* junction with row-level security left off is readable and writable by every
|
|
1127
|
-
* signed-in user, which is why the two must ship together.
|
|
1128
|
-
*/
|
|
1129
|
-
export const planJunctionTables = (allCollections: CollectionConfig[]): JunctionTablePlan[] => {
|
|
1130
|
-
const collections = relationalCollections(allCollections);
|
|
1131
|
-
const plans: JunctionTablePlan[] = [];
|
|
1132
|
-
|
|
1133
|
-
for (const spec of resolveJunctionSpecs(collections).values()) {
|
|
1134
|
-
const [source, target] = spec.endpoints;
|
|
1135
|
-
// A junction column's default name is derived from the endpoint
|
|
1136
|
-
// collection's slug — which is normally plural, so this is where the
|
|
1137
|
-
// singularization change actually lands: a `categories` endpoint used
|
|
1138
|
-
// to give `categorie_id` and now gives `category_id`. Recorded, not
|
|
1139
|
-
// used, so boot-ensure can recognise a table built under the old rule.
|
|
1140
|
-
const legacyFor = (endpoint: typeof source): string | undefined => {
|
|
1141
|
-
const slug = toSnakeCase(endpoint.collection.slug ?? endpoint.collection.name ?? "");
|
|
1142
|
-
const legacy = legacyForeignKeyName(slug);
|
|
1143
|
-
const derived = endpoint.junctionColumn === generateForeignKeyName(slug);
|
|
1144
|
-
return derived && legacy !== endpoint.junctionColumn ? legacy : undefined;
|
|
1145
|
-
};
|
|
1146
|
-
const columns = [
|
|
1147
|
-
{ name: source.junctionColumn, type: junctionKeyType(source.collection), legacyName: legacyFor(source) },
|
|
1148
|
-
{ name: target.junctionColumn, type: junctionKeyType(target.collection), legacyName: legacyFor(target) }
|
|
1149
|
-
];
|
|
1150
|
-
// Every declaring side agrees on the edge's lifetime; the first one wins,
|
|
1151
|
-
// as it does in the generator's walk.
|
|
1152
|
-
const onDelete = spec.declaringSides[0]?.relation.onDelete ?? "CASCADE";
|
|
1153
|
-
|
|
1154
|
-
plans.push({
|
|
1155
|
-
schema: spec.schema,
|
|
1156
|
-
table: spec.table,
|
|
1157
|
-
columns,
|
|
1158
|
-
createTable:
|
|
1159
|
-
`CREATE TABLE IF NOT EXISTS "${spec.schema}"."${spec.table}" (` +
|
|
1160
|
-
columns.map(c => `"${c.name}" ${c.type} NOT NULL`).join(", ") +
|
|
1161
|
-
`, PRIMARY KEY (${columns.map(c => `"${c.name}"`).join(", ")}));`,
|
|
1162
|
-
foreignKeys: [source, target].map((endpoint, i) =>
|
|
1163
|
-
foreignKeyPlan({
|
|
1164
|
-
schema: spec.schema,
|
|
1165
|
-
table: spec.table,
|
|
1166
|
-
column: columns[i].name,
|
|
1167
|
-
targetSchema: schemaOfCollection(endpoint.collection),
|
|
1168
|
-
targetTable: bareTableName(getTableName(endpoint.collection)),
|
|
1169
|
-
targetColumn: getPrimaryKeyName(endpoint.collection),
|
|
1170
|
-
onDelete
|
|
1171
|
-
})
|
|
1172
|
-
)
|
|
1173
|
-
});
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
return plans;
|
|
1177
|
-
};
|
|
1178
|
-
|
|
1179
|
-
export interface CollectionPolicyPlan {
|
|
1180
|
-
/** The table's schema (e.g. `public`, `rebase`). */
|
|
1181
|
-
schema: string;
|
|
1182
|
-
/** The bare table name, no schema prefix. */
|
|
1183
|
-
table: string;
|
|
1184
|
-
/** `schema.table` — matches the keys `readExistingSchema` returns. */
|
|
1185
|
-
qualified: string;
|
|
1186
|
-
/** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — locked by default. */
|
|
1187
|
-
enableRls: string;
|
|
1188
|
-
/** `DROP POLICY IF EXISTS` / `CREATE POLICY` statements, in order. */
|
|
1189
|
-
policyStatements: string[];
|
|
1190
|
-
}
|
|
1191
|
-
|
|
1192
|
-
/**
|
|
1193
|
-
* The per-table RLS plan for the *declared* collections, as executable
|
|
1194
|
-
* statements — what the managed runtime applies at boot so a freshly
|
|
1195
|
-
* provisioned tenant database serves data instead of 401ing every read.
|
|
1196
|
-
*
|
|
1197
|
-
* Mirrors {@link generatePostgresPoliciesDdl} exactly (same
|
|
1198
|
-
* `generatePolicyStatements`, same enable-RLS, same effective rules, same
|
|
1199
|
-
* derived junction rules), so boot and `db push` produce identical policies from
|
|
1200
|
-
* identical collections.
|
|
1201
|
-
*
|
|
1202
|
-
* Junction tables are included, and have to be: boot creates them now
|
|
1203
|
-
* ({@link planJunctionTables}), and a junction with RLS left off is readable and
|
|
1204
|
-
* writable by every signed-in user. A junction whose table is still absent is
|
|
1205
|
-
* skipped by the applier, not planned away here.
|
|
1206
|
-
*/
|
|
1207
|
-
export const planCollectionPolicies = (allCollections: CollectionConfig[]): CollectionPolicyPlan[] => {
|
|
1208
|
-
// A store with no RLS gets no policies planned for it — `supportsRLS` is
|
|
1209
|
-
// false for exactly the engines `relationalCollections` filters out.
|
|
1210
|
-
const collections = relationalCollections(allCollections);
|
|
1211
|
-
const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);
|
|
1212
|
-
const plans: CollectionPolicyPlan[] = [];
|
|
1213
|
-
const seen = new Set<string>();
|
|
1214
|
-
|
|
1215
|
-
for (const collection of collections) {
|
|
1216
|
-
const tableName = getTableName(collection);
|
|
1217
|
-
if (!tableName) continue;
|
|
1218
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
1219
|
-
const baseTableName = tableName.includes(".") ? tableName.split(".").pop()! : tableName;
|
|
1220
|
-
const qualified = `${schema}.${baseTableName}`;
|
|
1221
|
-
if (seen.has(qualified)) continue;
|
|
1222
|
-
seen.add(qualified);
|
|
1223
|
-
|
|
1224
|
-
const policyStatements: string[] = [];
|
|
1225
|
-
for (const rule of getEffectiveSecurityRules(collection)) {
|
|
1226
|
-
policyStatements.push(...generatePolicyStatements(collection, rule, resolveCollection));
|
|
1227
|
-
}
|
|
1228
|
-
|
|
1229
|
-
plans.push({
|
|
1230
|
-
schema,
|
|
1231
|
-
table: baseTableName,
|
|
1232
|
-
qualified,
|
|
1233
|
-
enableRls: `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;`,
|
|
1234
|
-
policyStatements
|
|
1235
|
-
});
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
// Junctions are derived from `through` relations rather than declared, so
|
|
1239
|
-
// the walk above never sees them.
|
|
1240
|
-
for (const spec of resolveJunctionSpecs(collections).values()) {
|
|
1241
|
-
const qualified = `${spec.schema}.${spec.table}`;
|
|
1242
|
-
if (seen.has(qualified)) continue;
|
|
1243
|
-
seen.add(qualified);
|
|
1244
|
-
|
|
1245
|
-
const junctionCollection = getJunctionCollectionConfig(spec);
|
|
1246
|
-
const policyStatements: string[] = [];
|
|
1247
|
-
for (const rule of getJunctionSecurityRules(spec)) {
|
|
1248
|
-
policyStatements.push(...generatePolicyStatements(junctionCollection, rule, resolveCollection));
|
|
1249
|
-
}
|
|
1250
|
-
|
|
1251
|
-
plans.push({
|
|
1252
|
-
schema: spec.schema,
|
|
1253
|
-
table: spec.table,
|
|
1254
|
-
qualified,
|
|
1255
|
-
enableRls: `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;`,
|
|
1256
|
-
policyStatements
|
|
1257
|
-
});
|
|
1258
|
-
}
|
|
1259
|
-
|
|
1260
|
-
return plans;
|
|
1261
|
-
};
|
|
1262
|
-
|
|
1263
|
-
export const generatePostgresPoliciesDdl = (allCollections: CollectionConfig[]): string => {
|
|
1264
|
-
// Also the expectation `checkPolicyDrift` reconciles the database against,
|
|
1265
|
-
// so a non-SQL collection filtered out here is one the drift report cannot
|
|
1266
|
-
// invent a missing policy for.
|
|
1267
|
-
const collections = relationalCollections(allCollections);
|
|
1268
|
-
let ddl = "-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\n\n";
|
|
1269
|
-
|
|
1270
|
-
const allTablesToGenerate = new Map<string, {
|
|
1271
|
-
collection: CollectionConfig
|
|
1272
|
-
}>();
|
|
1273
|
-
|
|
1274
|
-
for (const collection of collections) {
|
|
1275
|
-
const tableName = getTableName(collection);
|
|
1276
|
-
if (tableName) {
|
|
1277
|
-
allTablesToGenerate.set(tableName, { collection });
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
|
|
1281
|
-
for (const [tableName, { collection }] of allTablesToGenerate.entries()) {
|
|
1282
|
-
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
1283
|
-
const baseTableName = tableName.includes(".") ? tableName.split(".").pop()! : tableName;
|
|
1284
|
-
|
|
1285
|
-
// No FORCE: user requests run as the non-owner `rebase_user` role
|
|
1286
|
-
// (plain ENABLE binds them); the owner is the trusted server context.
|
|
1287
|
-
ddl += `ALTER TABLE "${schema}"."${baseTableName}" ENABLE ROW LEVEL SECURITY;\n`;
|
|
1288
|
-
ddl += `\n`;
|
|
1289
|
-
|
|
1290
|
-
const securityRules = getEffectiveSecurityRules(collection);
|
|
1291
|
-
if (securityRules.length > 0) {
|
|
1292
|
-
const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);
|
|
1293
|
-
const injectedNames = new Set(getInjectedSecurityRules(collection).map((rule) => rule.name));
|
|
1294
|
-
|
|
1295
|
-
securityRules.forEach((rule: SecurityRule) => {
|
|
1296
|
-
// Say which policies the author did not write. They are permissive,
|
|
1297
|
-
// so they OR with the declared rules and widen the final ACL beyond
|
|
1298
|
-
// what `securityRules` reads like — and re-appear after any manual
|
|
1299
|
-
// DROP, because a push asserts the declared state.
|
|
1300
|
-
if (rule.name && injectedNames.has(rule.name)) {
|
|
1301
|
-
ddl += `-- Injected by Rebase (not from this collection's securityRules).\n`;
|
|
1302
|
-
ddl += `-- Set \`disableDefaultPolicies: true\` on "${collection.slug}" to drop these and own its RLS outright.\n`;
|
|
1303
|
-
}
|
|
1304
|
-
ddl += generatePolicyDdl(collection, rule, resolveCollection);
|
|
1305
|
-
});
|
|
1306
|
-
ddl += "\n";
|
|
1307
|
-
}
|
|
1308
|
-
}
|
|
1309
|
-
|
|
1310
|
-
// Junction tables are generated from `through` relations, not declared as
|
|
1311
|
-
// collections, so the walk above never sees them. They get the same
|
|
1312
|
-
// treatment as any generated table: locked by default, with derived
|
|
1313
|
-
// policies — reads follow the endpoints, writes follow the declaring
|
|
1314
|
-
// side's update rules.
|
|
1315
|
-
const junctionSpecs = resolveJunctionSpecs(collections);
|
|
1316
|
-
for (const spec of junctionSpecs.values()) {
|
|
1317
|
-
ddl += `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;\n`;
|
|
1318
|
-
ddl += `\n`;
|
|
1319
|
-
|
|
1320
|
-
const junctionRules = getJunctionSecurityRules(spec);
|
|
1321
|
-
if (junctionRules.length === 0) continue;
|
|
1322
|
-
|
|
1323
|
-
const junctionCollection = getJunctionCollectionConfig(spec);
|
|
1324
|
-
const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);
|
|
1325
|
-
const declaringSlugs = spec.declaringSides.map(s => s.collection.slug).join('", "');
|
|
1326
|
-
|
|
1327
|
-
ddl += `-- Derived by Rebase for the junction "${spec.table}" (no collection declares it).\n`;
|
|
1328
|
-
ddl += `-- Reads require both endpoint rows to be visible; writes follow the update\n`;
|
|
1329
|
-
ddl += `-- rules of "${declaringSlugs}". Set \`disableDefaultPolicies: true\` on the\n`;
|
|
1330
|
-
ddl += `-- declaring collection(s) to drop these and police the junction yourself.\n`;
|
|
1331
|
-
junctionRules.forEach((rule: SecurityRule) => {
|
|
1332
|
-
ddl += generatePolicyDdl(junctionCollection, rule, resolveCollection);
|
|
1333
|
-
});
|
|
1334
|
-
ddl += "\n";
|
|
1335
|
-
}
|
|
1336
|
-
|
|
1337
|
-
return ddl;
|
|
1338
|
-
};
|
|
1339
|
-
|