@rebasepro/server-postgres 0.12.1-canary.g181d0fe → 0.12.1-canary.g35be8cb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ensure-collection-policies-CT-zIUWA.js → ensure-collection-policies-Vl3Cv1Q9.js} +2 -2
- package/dist/{ensure-collection-policies-CT-zIUWA.js.map → ensure-collection-policies-Vl3Cv1Q9.js.map} +1 -1
- package/dist/{ensure-collection-tables-Vu-GRELM.js → ensure-collection-tables-DsDsNl6o.js} +234 -25
- package/dist/ensure-collection-tables-DsDsNl6o.js.map +1 -0
- package/dist/index.es.js +35 -14
- package/dist/index.es.js.map +1 -1
- package/dist/schema/ensure-collection-tables.d.ts +24 -2
- package/dist/schema/generate-postgres-ddl-logic.d.ts +82 -9
- package/package.json +6 -6
- package/src/PostgresBootstrapper.ts +7 -1
- package/src/schema/ensure-collection-tables.test.ts +105 -9
- package/src/schema/ensure-collection-tables.ts +142 -25
- package/src/schema/generate-postgres-ddl-logic.ts +244 -12
- package/src/schema/introspect-runtime.test.ts +56 -8
- package/src/schema/introspect-runtime.ts +31 -9
- package/dist/ensure-collection-tables-Vu-GRELM.js.map +0 -1
|
@@ -46,9 +46,17 @@ export interface ExistingSchema {
|
|
|
46
46
|
tables: Map<string, Set<string>>;
|
|
47
47
|
/** `schema.typename` of every enum type that already exists. */
|
|
48
48
|
enums: Set<string>;
|
|
49
|
+
/**
|
|
50
|
+
* `schema.table.constraint` of every constraint that already exists.
|
|
51
|
+
*
|
|
52
|
+
* Optional so a caller that only cares about tables can still build one by
|
|
53
|
+
* hand; absent is read as "none known", which at worst re-attempts a
|
|
54
|
+
* constraint that then fails harmlessly as a duplicate.
|
|
55
|
+
*/
|
|
56
|
+
constraints?: Set<string>;
|
|
49
57
|
}
|
|
50
58
|
export interface EnsureAction {
|
|
51
|
-
kind: "create-enum" | "create-table" | "add-column";
|
|
59
|
+
kind: "create-enum" | "create-table" | "add-column" | "add-constraint";
|
|
52
60
|
/** Qualified target, for logging: `public.posts` or `public.posts.title`. */
|
|
53
61
|
target: string;
|
|
54
62
|
sql: string;
|
|
@@ -58,6 +66,20 @@ export interface EnsurePlan {
|
|
|
58
66
|
/** Every statement, in dependency order. Empty when the schema is current. */
|
|
59
67
|
statements: string[];
|
|
60
68
|
}
|
|
69
|
+
export interface EnsureOutcome extends EnsurePlan {
|
|
70
|
+
/**
|
|
71
|
+
* Constraints that could not be added — always non-fatal.
|
|
72
|
+
*
|
|
73
|
+
* A foreign key can only fail on data that already violates it, and the
|
|
74
|
+
* column it would police exists either way, so the collection still serves.
|
|
75
|
+
* Refusing to boot over one would turn a pre-existing data problem into an
|
|
76
|
+
* outage. Reported loudly instead.
|
|
77
|
+
*/
|
|
78
|
+
failures: {
|
|
79
|
+
target: string;
|
|
80
|
+
error: string;
|
|
81
|
+
}[];
|
|
82
|
+
}
|
|
61
83
|
/**
|
|
62
84
|
* Decide what to add. Pure — the caller supplies what exists and runs the result.
|
|
63
85
|
*
|
|
@@ -76,4 +98,4 @@ export declare function readExistingSchema(client: Queryable, schemas: string[])
|
|
|
76
98
|
* cannot be added, say) should not roll back the tables that were created fine.
|
|
77
99
|
* The error is surfaced with the statement that caused it.
|
|
78
100
|
*/
|
|
79
|
-
export declare function ensureCollectionTables(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void): Promise<
|
|
101
|
+
export declare function ensureCollectionTables(client: Queryable, collections: CollectionConfig[], log?: (message: string) => void): Promise<EnsureOutcome>;
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { CollectionConfig, Property, SecurityRule } from "@rebasepro/types";
|
|
2
2
|
export declare const resolveColumnName: (propName: string, prop?: Property | null) => string;
|
|
3
|
+
export declare const getPrimaryKeyProp: (collection: CollectionConfig) => {
|
|
4
|
+
name: string;
|
|
5
|
+
type: "string" | "number";
|
|
6
|
+
isUuid: boolean;
|
|
7
|
+
};
|
|
8
|
+
export declare const isNumericId: (collection: CollectionConfig) => boolean;
|
|
9
|
+
export declare const getPrimaryKeyName: (collection: CollectionConfig) => string;
|
|
3
10
|
export declare const isIdProperty: (propName: string, prop: Property, collection: CollectionConfig) => boolean;
|
|
4
11
|
type ResolveCollection = (slug: string) => CollectionConfig | undefined;
|
|
5
12
|
/**
|
|
@@ -17,6 +24,73 @@ export declare const generatePostgresDdl: (collections: CollectionConfig[], opti
|
|
|
17
24
|
includePolicies?: boolean;
|
|
18
25
|
}) => Promise<string>;
|
|
19
26
|
/** The RLS statements one declared collection's table needs, ready to run. */
|
|
27
|
+
/**
|
|
28
|
+
* A foreign key, as both its parts and the statement that creates it.
|
|
29
|
+
*
|
|
30
|
+
* `ALTER TABLE … ADD CONSTRAINT` has no `IF NOT EXISTS`, so a caller applying
|
|
31
|
+
* these has to skip by name — hence the name is a field and not only a substring
|
|
32
|
+
* of the SQL.
|
|
33
|
+
*/
|
|
34
|
+
export interface ForeignKeyPlan {
|
|
35
|
+
constraintName: string;
|
|
36
|
+
schema: string;
|
|
37
|
+
/** Bare table name, no schema prefix. */
|
|
38
|
+
table: string;
|
|
39
|
+
column: string;
|
|
40
|
+
targetSchema: string;
|
|
41
|
+
targetTable: string;
|
|
42
|
+
targetColumn: string;
|
|
43
|
+
sql: string;
|
|
44
|
+
}
|
|
45
|
+
/** A column a `relation` or `reference` property owns on its own table. */
|
|
46
|
+
export interface RelationalColumnPlan {
|
|
47
|
+
schema: string;
|
|
48
|
+
/** Bare table name, no schema prefix. */
|
|
49
|
+
table: string;
|
|
50
|
+
column: string;
|
|
51
|
+
/** Postgres type, exactly as the DDL generator declares it. */
|
|
52
|
+
type: string;
|
|
53
|
+
/** Absent when the target collection is not part of this bundle. */
|
|
54
|
+
foreignKey?: ForeignKeyPlan;
|
|
55
|
+
}
|
|
56
|
+
/** The table behind a many-to-many `through` relation. */
|
|
57
|
+
export interface JunctionTablePlan {
|
|
58
|
+
schema: string;
|
|
59
|
+
/** Bare table name, no schema prefix. */
|
|
60
|
+
table: string;
|
|
61
|
+
columns: {
|
|
62
|
+
name: string;
|
|
63
|
+
type: string;
|
|
64
|
+
}[];
|
|
65
|
+
/** Both endpoint columns plus the composite primary key. */
|
|
66
|
+
createTable: string;
|
|
67
|
+
foreignKeys: ForeignKeyPlan[];
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The FK columns the declared collections own — one entry per `relation`
|
|
71
|
+
* (`belongsTo` side) or `reference` property.
|
|
72
|
+
*
|
|
73
|
+
* Split out of {@link generatePostgresDdl} so the boot-time schema ensure can
|
|
74
|
+
* create the same columns with the same names, types and constraints. Before
|
|
75
|
+
* this it skipped them outright, which was survivable only because `db push`
|
|
76
|
+
* always followed; on a managed tenant nothing follows, so a table arrived
|
|
77
|
+
* without the column its own collection reads and wrote 400 on every insert.
|
|
78
|
+
*
|
|
79
|
+
* A relation whose target is not in the bundle yields no column at all (the
|
|
80
|
+
* generator returns early on an unresolvable target); a `reference` whose target
|
|
81
|
+
* is unknown yields the column without a constraint. Both mirror the generator
|
|
82
|
+
* exactly — a divergence here is a schema fork between boot and `db push`.
|
|
83
|
+
*/
|
|
84
|
+
export declare const planRelationalColumns: (collections: CollectionConfig[]) => RelationalColumnPlan[];
|
|
85
|
+
/**
|
|
86
|
+
* The junction tables a bundle's many-to-many relations imply.
|
|
87
|
+
*
|
|
88
|
+
* Derived from {@link resolveJunctionSpecs}, the same source the junction RLS
|
|
89
|
+
* comes from, so a table created here always has policies planned for it — a
|
|
90
|
+
* junction with row-level security left off is readable and writable by every
|
|
91
|
+
* signed-in user, which is why the two must ship together.
|
|
92
|
+
*/
|
|
93
|
+
export declare const planJunctionTables: (collections: CollectionConfig[]) => JunctionTablePlan[];
|
|
20
94
|
export interface CollectionPolicyPlan {
|
|
21
95
|
/** The table's schema (e.g. `public`, `rebase`). */
|
|
22
96
|
schema: string;
|
|
@@ -34,16 +108,15 @@ export interface CollectionPolicyPlan {
|
|
|
34
108
|
* statements — what the managed runtime applies at boot so a freshly
|
|
35
109
|
* provisioned tenant database serves data instead of 401ing every read.
|
|
36
110
|
*
|
|
37
|
-
* Mirrors
|
|
38
|
-
*
|
|
39
|
-
* boot and `db push` produce identical policies from
|
|
111
|
+
* Mirrors {@link generatePostgresPoliciesDdl} exactly (same
|
|
112
|
+
* `generatePolicyStatements`, same enable-RLS, same effective rules, same
|
|
113
|
+
* derived junction rules), so boot and `db push` produce identical policies from
|
|
114
|
+
* identical collections.
|
|
40
115
|
*
|
|
41
|
-
* Junction tables are
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
* `db migrate` concern, which is where those tables get created in the first
|
|
46
|
-
* place. `db push` still applies junction policies via the string generator.
|
|
116
|
+
* Junction tables are included, and have to be: boot creates them now
|
|
117
|
+
* ({@link planJunctionTables}), and a junction with RLS left off is readable and
|
|
118
|
+
* writable by every signed-in user. A junction whose table is still absent is
|
|
119
|
+
* skipped by the applier, not planned away here.
|
|
47
120
|
*/
|
|
48
121
|
export declare const planCollectionPolicies: (collections: CollectionConfig[]) => CollectionPolicyPlan[];
|
|
49
122
|
export declare const generatePostgresPoliciesDdl: (collections: CollectionConfig[]) => string;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/server-postgres",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.12.1-canary.
|
|
4
|
+
"version": "0.12.1-canary.g35be8cb",
|
|
5
5
|
"description": "PostgreSQL data source backend implementation for Rebase with Drizzle ORM",
|
|
6
6
|
"funding": {
|
|
7
7
|
"url": "https://github.com/sponsors/rebaseco"
|
|
@@ -47,11 +47,11 @@
|
|
|
47
47
|
"execa": "^9.6.1",
|
|
48
48
|
"pg": "^8.22.0",
|
|
49
49
|
"ws": "^8.21.1",
|
|
50
|
-
"@rebasepro/codegen": "0.12.1-canary.
|
|
51
|
-
"@rebasepro/
|
|
52
|
-
"@rebasepro/
|
|
53
|
-
"@rebasepro/
|
|
54
|
-
"@rebasepro/
|
|
50
|
+
"@rebasepro/codegen": "0.12.1-canary.g35be8cb",
|
|
51
|
+
"@rebasepro/server": "0.12.1-canary.g35be8cb",
|
|
52
|
+
"@rebasepro/types": "0.12.1-canary.g35be8cb",
|
|
53
|
+
"@rebasepro/utils": "0.12.1-canary.g35be8cb",
|
|
54
|
+
"@rebasepro/common": "0.12.1-canary.g35be8cb"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@hono/node-server": "^2.0.12",
|
|
@@ -757,7 +757,13 @@ schemaHealthCheck: () => probeAuthSchema(db, resolveAuthSchema(authCollection))
|
|
|
757
757
|
collections as Parameters<typeof ensureCollectionTables>[1],
|
|
758
758
|
log
|
|
759
759
|
);
|
|
760
|
-
|
|
760
|
+
for (const failure of plan.failures) {
|
|
761
|
+
logger.warn(
|
|
762
|
+
`🔗 [schema] Could not add foreign key "${failure.target}" — the column exists and the ` +
|
|
763
|
+
`collection still serves, but rows are not policed by this constraint: ${failure.error}`
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
return { applied: plan.actions.length - plan.failures.length };
|
|
761
767
|
},
|
|
762
768
|
|
|
763
769
|
/**
|
|
@@ -87,16 +87,112 @@ describe("planning an additive schema ensure", () => {
|
|
|
87
87
|
expect(sql).not.toMatch(/NOT NULL/i);
|
|
88
88
|
});
|
|
89
89
|
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
90
|
+
// ── Relations ────────────────────────────────────────────────────────────
|
|
91
|
+
//
|
|
92
|
+
// These columns were once skipped outright, on the reasoning that a bare
|
|
93
|
+
// column without its foreign key would disagree with what `db push` later
|
|
94
|
+
// generated. On a managed tenant nothing pushes afterwards, so the table
|
|
95
|
+
// arrived without the column its own collection reads: every insert 400ed
|
|
96
|
+
// with `column "author_id" does not exist`. The answer is to emit the key
|
|
97
|
+
// too, from the same planner `db push` uses.
|
|
98
|
+
|
|
99
|
+
const authors = {
|
|
100
|
+
name: "Authors",
|
|
101
|
+
slug: "authors",
|
|
102
|
+
properties: {
|
|
103
|
+
id: { name: "ID", type: "string", isId: "uuid" },
|
|
104
|
+
name: { name: "Name", type: "string" }
|
|
105
|
+
}
|
|
106
|
+
} as unknown as CollectionConfig;
|
|
107
|
+
|
|
108
|
+
const postsWithAuthor = {
|
|
109
|
+
...posts,
|
|
110
|
+
properties: {
|
|
111
|
+
...(posts as unknown as { properties: Record<string, unknown> }).properties,
|
|
112
|
+
author: { name: "Author", type: "reference", path: "authors" }
|
|
113
|
+
}
|
|
114
|
+
} as unknown as CollectionConfig;
|
|
115
|
+
|
|
116
|
+
const tags = {
|
|
117
|
+
name: "Tags",
|
|
118
|
+
slug: "tags",
|
|
119
|
+
properties: {
|
|
120
|
+
id: { name: "ID", type: "number", isId: "increment" },
|
|
121
|
+
name: { name: "Name", type: "string" }
|
|
122
|
+
}
|
|
123
|
+
} as unknown as CollectionConfig;
|
|
124
|
+
|
|
125
|
+
const postsWithTags = {
|
|
126
|
+
...posts,
|
|
127
|
+
properties: {
|
|
128
|
+
...(posts as unknown as { properties: Record<string, unknown> }).properties,
|
|
129
|
+
tags: {
|
|
130
|
+
name: "Tags",
|
|
131
|
+
type: "relation",
|
|
132
|
+
relation: { kind: "manyToMany", target: () => tags, relationName: "tags" }
|
|
96
133
|
}
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
|
|
134
|
+
}
|
|
135
|
+
} as unknown as CollectionConfig;
|
|
136
|
+
|
|
137
|
+
it("adds a reference column, and the foreign key that makes it one", () => {
|
|
138
|
+
const plan = planCollectionSchemaEnsure([postsWithAuthor, authors], withTable("public.posts", ["id"]));
|
|
139
|
+
|
|
140
|
+
expect(plan.actions.some(a => a.kind === "add-column" && a.target === "public.posts.author")).toBe(true);
|
|
141
|
+
const fk = plan.actions.find(a => a.kind === "add-constraint");
|
|
142
|
+
expect(fk?.target).toBe("public.posts.posts_author_fkey");
|
|
143
|
+
expect(fk?.sql).toMatch(/REFERENCES "public"\."authors" \("id"\)/);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("orders every constraint after the columns and tables it depends on", () => {
|
|
147
|
+
const plan = planCollectionSchemaEnsure([postsWithAuthor, authors], empty());
|
|
148
|
+
const kinds = plan.actions.map(a => a.kind);
|
|
149
|
+
expect(kinds.lastIndexOf("add-column")).toBeLessThan(kinds.indexOf("add-constraint"));
|
|
150
|
+
expect(kinds.lastIndexOf("create-table")).toBeLessThan(kinds.indexOf("add-constraint"));
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("skips a foreign key the database already has, since ADD CONSTRAINT has no IF NOT EXISTS", () => {
|
|
154
|
+
const existing: ExistingSchema = {
|
|
155
|
+
tables: new Map([
|
|
156
|
+
["public.posts", new Set(["id", "author"])],
|
|
157
|
+
["public.authors", new Set(["id", "name"])]
|
|
158
|
+
]),
|
|
159
|
+
enums: new Set(["public.posts_status"]),
|
|
160
|
+
constraints: new Set(["public.posts.posts_author_fkey"])
|
|
161
|
+
};
|
|
162
|
+
const plan = planCollectionSchemaEnsure([postsWithAuthor, authors], existing);
|
|
163
|
+
expect(plan.actions.some(a => a.kind === "add-constraint")).toBe(false);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it("creates the junction table behind a many-to-many, keyed on both endpoints", () => {
|
|
167
|
+
const plan = planCollectionSchemaEnsure([postsWithTags, tags], empty());
|
|
168
|
+
const junction = plan.actions.find(a => a.kind === "create-table" && a.target === "public.posts_tags");
|
|
169
|
+
|
|
170
|
+
expect(junction).toBeDefined();
|
|
171
|
+
// The endpoint key types have to match the primary keys they reference:
|
|
172
|
+
// posts is a uuid, tags an auto-increment integer.
|
|
173
|
+
expect(junction!.sql).toMatch(/"post_id" UUID NOT NULL/);
|
|
174
|
+
expect(junction!.sql).toMatch(/"tag_id" INTEGER NOT NULL/);
|
|
175
|
+
expect(junction!.sql).toMatch(/PRIMARY KEY \("post_id", "tag_id"\)/);
|
|
176
|
+
|
|
177
|
+
const fks = plan.actions.filter(a => a.kind === "add-constraint").map(a => a.target);
|
|
178
|
+
expect(fks).toContain("public.posts_tags.posts_tags_post_id_fkey");
|
|
179
|
+
expect(fks).toContain("public.posts_tags.posts_tags_tag_id_fkey");
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it("leaves an existing junction table alone", () => {
|
|
183
|
+
const existing: ExistingSchema = {
|
|
184
|
+
tables: new Map([
|
|
185
|
+
["public.posts", new Set(["id", "title", "views", "status"])],
|
|
186
|
+
["public.tags", new Set(["id", "name"])],
|
|
187
|
+
["public.posts_tags", new Set(["post_id", "tag_id"])]
|
|
188
|
+
]),
|
|
189
|
+
enums: new Set(["public.posts_status"]),
|
|
190
|
+
constraints: new Set([
|
|
191
|
+
"public.posts_tags.posts_tags_post_id_fkey",
|
|
192
|
+
"public.posts_tags.posts_tags_tag_id_fkey"
|
|
193
|
+
])
|
|
194
|
+
};
|
|
195
|
+
expect(planCollectionSchemaEnsure([postsWithTags, tags], existing).actions).toEqual([]);
|
|
100
196
|
});
|
|
101
197
|
});
|
|
102
198
|
|
|
@@ -30,7 +30,9 @@ import { getTableName } from "@rebasepro/common";
|
|
|
30
30
|
import {
|
|
31
31
|
getSqlColumnType,
|
|
32
32
|
resolveColumnName,
|
|
33
|
-
isIdProperty
|
|
33
|
+
isIdProperty,
|
|
34
|
+
planRelationalColumns,
|
|
35
|
+
planJunctionTables
|
|
34
36
|
} from "./generate-postgres-ddl-logic";
|
|
35
37
|
|
|
36
38
|
/**
|
|
@@ -62,10 +64,18 @@ export interface ExistingSchema {
|
|
|
62
64
|
tables: Map<string, Set<string>>;
|
|
63
65
|
/** `schema.typename` of every enum type that already exists. */
|
|
64
66
|
enums: Set<string>;
|
|
67
|
+
/**
|
|
68
|
+
* `schema.table.constraint` of every constraint that already exists.
|
|
69
|
+
*
|
|
70
|
+
* Optional so a caller that only cares about tables can still build one by
|
|
71
|
+
* hand; absent is read as "none known", which at worst re-attempts a
|
|
72
|
+
* constraint that then fails harmlessly as a duplicate.
|
|
73
|
+
*/
|
|
74
|
+
constraints?: Set<string>;
|
|
65
75
|
}
|
|
66
76
|
|
|
67
77
|
export interface EnsureAction {
|
|
68
|
-
kind: "create-enum" | "create-table" | "add-column";
|
|
78
|
+
kind: "create-enum" | "create-table" | "add-column" | "add-constraint";
|
|
69
79
|
/** Qualified target, for logging: `public.posts` or `public.posts.title`. */
|
|
70
80
|
target: string;
|
|
71
81
|
sql: string;
|
|
@@ -77,6 +87,18 @@ export interface EnsurePlan {
|
|
|
77
87
|
statements: string[];
|
|
78
88
|
}
|
|
79
89
|
|
|
90
|
+
export interface EnsureOutcome extends EnsurePlan {
|
|
91
|
+
/**
|
|
92
|
+
* Constraints that could not be added — always non-fatal.
|
|
93
|
+
*
|
|
94
|
+
* A foreign key can only fail on data that already violates it, and the
|
|
95
|
+
* column it would police exists either way, so the collection still serves.
|
|
96
|
+
* Refusing to boot over one would turn a pre-existing data problem into an
|
|
97
|
+
* outage. Reported loudly instead.
|
|
98
|
+
*/
|
|
99
|
+
failures: { target: string; error: string }[];
|
|
100
|
+
}
|
|
101
|
+
|
|
80
102
|
function schemaOf(collection: CollectionConfig): string {
|
|
81
103
|
return isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
82
104
|
}
|
|
@@ -183,34 +205,98 @@ export function planCollectionSchemaEnsure(
|
|
|
183
205
|
});
|
|
184
206
|
}
|
|
185
207
|
|
|
208
|
+
// 2b. Junction tables behind many-to-many relations. No collection declares
|
|
209
|
+
// them, so the walk above never sees them — and until they existed, an
|
|
210
|
+
// m2m write had nowhere to land and the junction's derived RLS had
|
|
211
|
+
// nothing to attach to.
|
|
212
|
+
const junctions = planJunctionTables(collections);
|
|
213
|
+
for (const junction of junctions) {
|
|
214
|
+
const key = `${junction.schema}.${junction.table}`;
|
|
215
|
+
if (existing.tables.has(key) || created.has(key)) continue;
|
|
216
|
+
created.add(key);
|
|
217
|
+
actions.push({ kind: "create-table", target: key, sql: junction.createTable });
|
|
218
|
+
}
|
|
219
|
+
|
|
186
220
|
// 3. Missing columns, on both brand-new and pre-existing tables.
|
|
221
|
+
const addColumn = (
|
|
222
|
+
key: string,
|
|
223
|
+
schema: string,
|
|
224
|
+
table: string,
|
|
225
|
+
column: string,
|
|
226
|
+
type: string
|
|
227
|
+
): void => {
|
|
228
|
+
const present = existing.tables.get(key);
|
|
229
|
+
if (present?.has(column)) return;
|
|
230
|
+
actions.push({
|
|
231
|
+
kind: "add-column",
|
|
232
|
+
target: `${key}.${column}`,
|
|
233
|
+
// Never NOT NULL: an existing table with rows cannot take a
|
|
234
|
+
// non-null column without a default, and inventing one would be
|
|
235
|
+
// guessing at the customer's data.
|
|
236
|
+
sql: `ALTER TABLE "${schema}"."${table}" ADD COLUMN IF NOT EXISTS "${column}" ${type};`
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
|
|
187
240
|
for (const collection of collections) {
|
|
188
241
|
const key = qualified(collection);
|
|
189
242
|
const schema = schemaOf(collection);
|
|
190
243
|
const table = getTableName(collection);
|
|
191
|
-
const present = existing.tables.get(key) ?? new Set<string>();
|
|
192
244
|
for (const [propName, prop] of Object.entries(collection.properties ?? {})) {
|
|
193
245
|
const p = prop as Property;
|
|
194
246
|
if (isIdProperty(propName, p, collection)) continue;
|
|
195
|
-
//
|
|
196
|
-
//
|
|
197
|
-
//
|
|
198
|
-
//
|
|
247
|
+
// Relation and reference columns are planned from the shared
|
|
248
|
+
// relational planner below, which derives the column name, type and
|
|
249
|
+
// foreign key the same way `db push` does. Deriving them here as
|
|
250
|
+
// plain columns is what once produced a column with no constraint.
|
|
199
251
|
if (p.type === "reference" || p.type === "relation") continue;
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
252
|
+
addColumn(key, schema, table, resolveColumnName(propName, p), getSqlColumnType(propName, p, collection, collections));
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// 3b. A junction that already existed, but is short a column. One created
|
|
257
|
+
// above already carries both — unlike a collection table, whose CREATE
|
|
258
|
+
// declares only the identity column — so re-listing them would log two
|
|
259
|
+
// no-op statements and inflate the count of changes applied.
|
|
260
|
+
for (const junction of junctions) {
|
|
261
|
+
const key = `${junction.schema}.${junction.table}`;
|
|
262
|
+
if (created.has(key)) continue;
|
|
263
|
+
for (const column of junction.columns) {
|
|
264
|
+
addColumn(key, junction.schema, junction.table, column.name, column.type);
|
|
211
265
|
}
|
|
212
266
|
}
|
|
213
267
|
|
|
268
|
+
// 3c. The columns relation and reference properties own.
|
|
269
|
+
for (const relational of planRelationalColumns(collections)) {
|
|
270
|
+
addColumn(
|
|
271
|
+
`${relational.schema}.${relational.table}`,
|
|
272
|
+
relational.schema,
|
|
273
|
+
relational.table,
|
|
274
|
+
relational.column,
|
|
275
|
+
relational.type
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// 4. Foreign keys, last: the tables and columns on both ends have to exist
|
|
280
|
+
// first, and a constraint is the one thing here that can fail on data
|
|
281
|
+
// rather than on schema, so nothing else depends on it.
|
|
282
|
+
const knownConstraints = existing.constraints ?? new Set<string>();
|
|
283
|
+
const plannedConstraints = new Set<string>();
|
|
284
|
+
const foreignKeys = [
|
|
285
|
+
...planRelationalColumns(collections).map(r => r.foreignKey),
|
|
286
|
+
...junctions.flatMap(j => j.foreignKeys)
|
|
287
|
+
];
|
|
288
|
+
for (const fk of foreignKeys) {
|
|
289
|
+
if (!fk) continue;
|
|
290
|
+
const name = `${fk.schema}.${fk.table}.${fk.constraintName}`;
|
|
291
|
+
if (knownConstraints.has(name) || plannedConstraints.has(name)) continue;
|
|
292
|
+
plannedConstraints.add(name);
|
|
293
|
+
actions.push({
|
|
294
|
+
kind: "add-constraint",
|
|
295
|
+
target: `${fk.schema}.${fk.table}.${fk.constraintName}`,
|
|
296
|
+
sql: fk.sql
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
214
300
|
return { actions, statements: actions.map(a => a.sql) };
|
|
215
301
|
}
|
|
216
302
|
|
|
@@ -250,7 +336,23 @@ export async function readExistingSchema(
|
|
|
250
336
|
);
|
|
251
337
|
for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);
|
|
252
338
|
|
|
253
|
-
|
|
339
|
+
// `ADD CONSTRAINT` has no IF NOT EXISTS, so an existing foreign key is
|
|
340
|
+
// skipped by name rather than guarded in SQL.
|
|
341
|
+
const constraints = new Set<string>();
|
|
342
|
+
const { rows: constraintRows } = await client.query<{
|
|
343
|
+
schema: string;
|
|
344
|
+
table: string;
|
|
345
|
+
name: string;
|
|
346
|
+
}>(
|
|
347
|
+
`SELECT n.nspname AS schema, c.relname AS table, con.conname AS name
|
|
348
|
+
FROM pg_constraint con
|
|
349
|
+
JOIN pg_class c ON con.conrelid = c.oid
|
|
350
|
+
JOIN pg_namespace n ON c.relnamespace = n.oid
|
|
351
|
+
WHERE n.nspname IN (${inList})`
|
|
352
|
+
);
|
|
353
|
+
for (const row of constraintRows) constraints.add(`${row.schema}.${row.table}.${row.name}`);
|
|
354
|
+
|
|
355
|
+
return { tables, enums, constraints };
|
|
254
356
|
}
|
|
255
357
|
|
|
256
358
|
/**
|
|
@@ -265,8 +367,14 @@ export async function ensureCollectionTables(
|
|
|
265
367
|
client: Queryable,
|
|
266
368
|
collections: CollectionConfig[],
|
|
267
369
|
log?: (message: string) => void
|
|
268
|
-
): Promise<
|
|
269
|
-
|
|
370
|
+
): Promise<EnsureOutcome> {
|
|
371
|
+
// Junctions live alongside the collections that declare them, so their
|
|
372
|
+
// schema has to be read too — otherwise an existing junction reads as
|
|
373
|
+
// missing and its constraints as unplanned.
|
|
374
|
+
const schemas = Array.from(new Set([
|
|
375
|
+
...collections.map(schemaOf),
|
|
376
|
+
...planJunctionTables(collections).map(j => j.schema)
|
|
377
|
+
]));
|
|
270
378
|
for (const schema of schemas) {
|
|
271
379
|
assertSafeIdentifier(schema, "schema name");
|
|
272
380
|
if (schema !== "public") {
|
|
@@ -276,10 +384,11 @@ export async function ensureCollectionTables(
|
|
|
276
384
|
|
|
277
385
|
const existing = await readExistingSchema(client, schemas);
|
|
278
386
|
const plan = planCollectionSchemaEnsure(collections, existing);
|
|
387
|
+
const failures: { target: string; error: string }[] = [];
|
|
279
388
|
|
|
280
389
|
if (plan.actions.length === 0) {
|
|
281
390
|
log?.("Schema is up to date; nothing to create.");
|
|
282
|
-
return plan;
|
|
391
|
+
return { ...plan, failures };
|
|
283
392
|
}
|
|
284
393
|
|
|
285
394
|
for (const action of plan.actions) {
|
|
@@ -287,11 +396,19 @@ export async function ensureCollectionTables(
|
|
|
287
396
|
await client.query(action.sql);
|
|
288
397
|
log?.(`${action.kind}: ${action.target}`);
|
|
289
398
|
} catch (err) {
|
|
399
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
400
|
+
// A foreign key is the only action that can fail on the customer's
|
|
401
|
+
// data rather than on the schema. The column it polices is already
|
|
402
|
+
// there, so the collection serves either way — record it and carry
|
|
403
|
+
// on rather than crash-looping the deployment.
|
|
404
|
+
if (action.kind === "add-constraint") {
|
|
405
|
+
failures.push({ target: action.target, error: message });
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
290
408
|
throw new Error(
|
|
291
|
-
`Failed to ${action.kind} ${action.target}: `
|
|
292
|
-
`${err instanceof Error ? err.message : String(err)}\n ${action.sql}`
|
|
409
|
+
`Failed to ${action.kind} ${action.target}: ${message}\n ${action.sql}`
|
|
293
410
|
);
|
|
294
411
|
}
|
|
295
412
|
}
|
|
296
|
-
return plan;
|
|
413
|
+
return { ...plan, failures };
|
|
297
414
|
}
|