@rebasepro/server-postgres 0.23.0 → 0.24.0
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/{BranchService-DGPL6G_C.js → BranchService-BRt78gfa.js} +35 -18
- package/dist/BranchService-BRt78gfa.js.map +1 -0
- package/dist/PostgresBackendDriver.d.ts +84 -12
- package/dist/auth/services.d.ts +72 -14
- package/dist/{auth-users-columns-D2LBFrMH.js → auth-users-columns-C72EMoDJ.js} +17 -1
- package/dist/{auth-users-columns-D2LBFrMH.js.map → auth-users-columns-C72EMoDJ.js.map} +1 -1
- package/dist/{backup-cli-24v4OlSp.js → backup-cli-DW5p9_zv.js} +2 -2
- package/dist/{backup-cli-24v4OlSp.js.map → backup-cli-DW5p9_zv.js.map} +1 -1
- package/dist/{backup-service-HQ9GC4tN.js → backup-service-EwcDVG-8.js} +7 -9
- package/dist/{backup-service-HQ9GC4tN.js.map → backup-service-EwcDVG-8.js.map} +1 -1
- package/dist/{cli-errors-B8qHg02P.js → cli-errors-DsA-K9uP.js} +96 -1
- package/dist/{cli-errors-B8qHg02P.js.map → cli-errors-DsA-K9uP.js.map} +1 -1
- package/dist/cli-errors.d.ts +42 -0
- package/dist/cli-helpers.d.ts +12 -12
- package/dist/cli.js +91 -37
- package/dist/cli.js.map +1 -1
- package/dist/{column-plan-helpers-DF-8dTVa.js → column-plan-helpers-1-LQD0yI.js} +34 -24
- package/dist/column-plan-helpers-1-LQD0yI.js.map +1 -0
- package/dist/data-transformer.d.ts +0 -8
- package/dist/{doctor-Cb2thZ8s.js → doctor-C-sYWbmt.js} +224 -43
- package/dist/doctor-C-sYWbmt.js.map +1 -0
- package/dist/{ensure-collection-policies-RHUcEp4v.js → ensure-collection-policies-B1ureSIV.js} +73 -18
- package/dist/ensure-collection-policies-B1ureSIV.js.map +1 -0
- package/dist/{ensure-collection-tables-BEEjn5cn.js → ensure-collection-tables-kkkHk8oo.js} +76 -20
- package/dist/ensure-collection-tables-kkkHk8oo.js.map +1 -0
- package/dist/{ensure-tables-Dhn9KM3B.js → ensure-tables-BmI_tRxc.js} +10 -3
- package/dist/ensure-tables-BmI_tRxc.js.map +1 -0
- package/dist/{generate-drizzle-schema-yzY_BLhr.js → generate-drizzle-schema-93M0lUxK.js} +2 -2
- package/dist/{generate-drizzle-schema-yzY_BLhr.js.map → generate-drizzle-schema-93M0lUxK.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-BfzK7UQd.js → generate-drizzle-schema-logic-sSFDp6LR.js} +26 -8
- package/dist/generate-drizzle-schema-logic-sSFDp6LR.js.map +1 -0
- package/dist/generate-postgres-ddl-logic-BJsLaVNX.js +152 -0
- package/dist/generate-postgres-ddl-logic-BJsLaVNX.js.map +1 -0
- package/dist/generated-sql.d.ts +28 -0
- package/dist/index.es.js +3415 -917
- package/dist/index.es.js.map +1 -1
- package/dist/{introspect-db-logic-WMuAfxvw.js → introspect-db-logic-kCETE8TY.js} +523 -349
- package/dist/introspect-db-logic-kCETE8TY.js.map +1 -0
- package/dist/introspect-db-queries-C_Q5VgQw.js +317 -0
- package/dist/introspect-db-queries-C_Q5VgQw.js.map +1 -0
- package/dist/{plan-schema-C0fxM8dY.js → plan-schema-DU9exq6C.js} +139 -504
- package/dist/plan-schema-DU9exq6C.js.map +1 -0
- package/dist/{policy-drift-DljYdrpW.js → policy-drift-B-J2hhm0.js} +3 -3
- package/dist/policy-drift-B-J2hhm0.js.map +1 -0
- package/dist/{generate-postgres-ddl-logic-Bt2d2mRH.js → render-ddl-Ds2t_d9V.js} +11 -149
- package/dist/render-ddl-Ds2t_d9V.js.map +1 -0
- package/dist/{rls-bootstrap-sql-B8EclDyM.js → rls-bootstrap-sql-_KNnjanK.js} +263 -39
- package/dist/rls-bootstrap-sql-_KNnjanK.js.map +1 -0
- package/dist/{rls-enforcement-C6Xk0lA6.js → rls-enforcement-CfXOJJaW.js} +10 -2
- package/dist/rls-enforcement-CfXOJJaW.js.map +1 -0
- package/dist/schema/auth-schema.d.ts +170 -0
- package/dist/schema/classify-change.d.ts +29 -1
- package/dist/schema/column-plan-helpers.d.ts +33 -21
- package/dist/schema/destructive-sql.d.ts +20 -1
- package/dist/schema/doctor-cli.js +4 -4
- package/dist/schema/doctor.d.ts +34 -1
- package/dist/schema/ensure-collection-policies.d.ts +22 -0
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +5 -5
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/generate-schema-commit.d.ts +12 -0
- package/dist/schema/introspect-db-logic.d.ts +31 -0
- package/dist/schema/introspect-db-queries.d.ts +1 -1
- package/dist/schema/introspect-db-search.d.ts +22 -0
- package/dist/schema/introspect-db-storage.d.ts +83 -0
- package/dist/schema/introspect-db.js +15 -3
- package/dist/schema/introspect-db.js.map +1 -1
- package/dist/schema/plan/diff-plan.d.ts +1 -1
- package/dist/schema/plan/plan-schema.d.ts +16 -8
- package/dist/schema/plan/render-ddl.d.ts +6 -0
- package/dist/schema/plan/types.d.ts +37 -11
- package/dist/search-column-BM-GV6vH.js +442 -0
- package/dist/search-column-BM-GV6vH.js.map +1 -0
- package/dist/security/policy-drift.d.ts +1 -1
- package/dist/security/rls-enforcement.d.ts +7 -0
- package/dist/services/BranchService.d.ts +22 -1
- package/dist/services/FetchService.d.ts +5 -4
- package/dist/services/RelationService.d.ts +18 -0
- package/dist/services/cdc/CdcListener.d.ts +9 -4
- package/dist/services/cdc/identity-columns.d.ts +19 -0
- package/dist/services/cdc/trigger-cdc.d.ts +45 -7
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +12 -7
- package/dist/services/channel-history.d.ts +17 -1
- package/dist/services/collection-helpers.d.ts +11 -1
- package/dist/services/pg-notify-listener.d.ts +88 -6
- package/dist/services/realtimeService.d.ts +159 -45
- package/dist/services/socket-liveness.d.ts +45 -0
- package/dist/services/soft-delete.d.ts +12 -0
- package/dist/services/sql-script.d.ts +71 -0
- package/dist/services/write-depth.d.ts +16 -0
- package/dist/services/write-transaction-scope.d.ts +6 -3
- package/dist/utils/drizzle-conditions.d.ts +42 -2
- package/dist/utils/sql-redaction.d.ts +21 -0
- package/dist/websocket.d.ts +50 -18
- package/package.json +7 -7
- package/dist/BranchService-DGPL6G_C.js.map +0 -1
- package/dist/column-plan-helpers-DF-8dTVa.js.map +0 -1
- package/dist/doctor-Cb2thZ8s.js.map +0 -1
- package/dist/ensure-collection-policies-RHUcEp4v.js.map +0 -1
- package/dist/ensure-collection-tables-BEEjn5cn.js.map +0 -1
- package/dist/ensure-tables-Dhn9KM3B.js.map +0 -1
- package/dist/generate-drizzle-schema-logic-BfzK7UQd.js.map +0 -1
- package/dist/generate-postgres-ddl-logic-Bt2d2mRH.js.map +0 -1
- package/dist/introspect-db-logic-WMuAfxvw.js.map +0 -1
- package/dist/plan-schema-C0fxM8dY.js.map +0 -1
- package/dist/policy-drift-DljYdrpW.js.map +0 -1
- package/dist/rls-bootstrap-sql-B8EclDyM.js.map +0 -1
- package/dist/rls-enforcement-C6Xk0lA6.js.map +0 -1
|
@@ -1,317 +1,8 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* A Postgres identifier, quoted so that whatever is inside it stays inside it.
|
|
7
|
-
*
|
|
8
|
-
* Introspection reads table and schema names out of `pg_class` and puts them
|
|
9
|
-
* straight back into SQL, and wrapping a name in double quotes is not the same
|
|
10
|
-
* as escaping it: a table named `x" ; DROP TABLE users; --` closes the quote
|
|
11
|
-
* and then the statement. Postgres's own escape for a quote inside a quoted
|
|
12
|
-
* identifier is to double it, which is what this does.
|
|
13
|
-
*
|
|
14
|
-
* "The catalogue is trusted" is true of your own database, and is exactly the
|
|
15
|
-
* assumption this tool cannot make. Introspection exists to be pointed at
|
|
16
|
-
* databases somebody else built, and it runs with the privileges of whoever
|
|
17
|
-
* ran it — which is usually a superuser, because that is who has a connection
|
|
18
|
-
* string to a database they are adopting.
|
|
19
|
-
*/
|
|
20
|
-
function quoteIdentifier(name) {
|
|
21
|
-
return `"${name.replace(/"/g, "\"\"")}"`;
|
|
22
|
-
}
|
|
23
|
-
/** `"schema"."table"`, both halves quoted. */
|
|
24
|
-
function quoteRelation(schema, table) {
|
|
25
|
-
return `${quoteIdentifier(schema)}.${quoteIdentifier(table)}`;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* Can this table's name be the name of the file describing it?
|
|
29
|
-
*
|
|
30
|
-
* Introspection writes `<collectionsDir>/<tableName>.ts`, and the table name
|
|
31
|
-
* came from a database this tool did not create. Postgres will hold a table
|
|
32
|
-
* called `../../../etc/cron.d/x`, and `path.join` resolves it — so without this
|
|
33
|
-
* the generator writes a file wherever the name points, as whoever ran the
|
|
34
|
-
* command.
|
|
35
|
-
*
|
|
36
|
-
* Deliberately narrow, and deliberately not a blocklist of `..` and `/`: the
|
|
37
|
-
* question is "is this a plain file name?", and every answer that is not
|
|
38
|
-
* obviously yes is a table better written by hand. NUL and the Windows
|
|
39
|
-
* separator are in scope because a collections directory is checked out on
|
|
40
|
-
* whatever machine the developer has.
|
|
41
|
-
*/
|
|
42
|
-
function isUsableFileName(name) {
|
|
43
|
-
if (name.length === 0 || name.length > 200) return false;
|
|
44
|
-
if (name === "." || name === "..") return false;
|
|
45
|
-
if (/[/\\:\u0000-\u001f]/.test(name)) return false;
|
|
46
|
-
return !name.startsWith(".") && !name.endsWith(".");
|
|
47
|
-
}
|
|
48
|
-
/**
|
|
49
|
-
* Base tables, excluding partitions.
|
|
50
|
-
*
|
|
51
|
-
* `relispartition` is the reason this reads `pg_class` rather than
|
|
52
|
-
* `information_schema.tables`, which reports every partition as a base table of
|
|
53
|
-
* its own. Pagila partitions `payment` by month; introspected through
|
|
54
|
-
* information_schema it yields `payment` plus 26 near-identical
|
|
55
|
-
* `payment_p2022_*` collections, each with its own nav entry.
|
|
56
|
-
*
|
|
57
|
-
* `relkind = 'p'` (the partitioned parent) is included and `'r'` partitions are
|
|
58
|
-
* dropped, which is the right way round: the parent is the queryable table.
|
|
59
|
-
*/
|
|
60
|
-
var TABLES_QUERY = `
|
|
61
|
-
SELECT c.relname AS table_name,
|
|
62
|
-
c.relkind = 'p' AS is_partitioned
|
|
63
|
-
FROM pg_class c
|
|
64
|
-
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
65
|
-
WHERE n.nspname = $1
|
|
66
|
-
AND c.relkind IN ('r', 'p')
|
|
67
|
-
AND NOT c.relispartition
|
|
68
|
-
AND c.relname NOT LIKE 'drizzle_%'
|
|
69
|
-
AND c.relname NOT LIKE 'rebase_%'
|
|
70
|
-
ORDER BY c.relname
|
|
71
|
-
`;
|
|
72
|
-
/**
|
|
73
|
-
* Columns, with the catalog facts that say a column is not the user's to edit.
|
|
74
|
-
*
|
|
75
|
-
* `is_generated`/`is_identity` are read for that reason: a generated column
|
|
76
|
-
* rejects any write, so a form that offers it is offering a field that always
|
|
77
|
-
* errors. `character_maximum_length` is the declared `varchar(n)` bound —
|
|
78
|
-
* already enforced by the database, and free to surface as validation.
|
|
79
|
-
*/
|
|
80
|
-
var COLUMNS_QUERY = `
|
|
81
|
-
SELECT
|
|
82
|
-
c.table_name,
|
|
83
|
-
c.column_name,
|
|
84
|
-
c.data_type,
|
|
85
|
-
c.udt_name,
|
|
86
|
-
c.is_nullable,
|
|
87
|
-
c.column_default,
|
|
88
|
-
c.ordinal_position,
|
|
89
|
-
c.is_generated,
|
|
90
|
-
c.is_identity,
|
|
91
|
-
c.identity_generation,
|
|
92
|
-
c.character_maximum_length,
|
|
93
|
-
c.numeric_precision,
|
|
94
|
-
c.numeric_scale,
|
|
95
|
-
(SELECT a.atttypmod FROM pg_attribute a
|
|
96
|
-
JOIN pg_class pc ON a.attrelid = pc.oid
|
|
97
|
-
WHERE pc.relname = c.table_name
|
|
98
|
-
AND a.attname = c.column_name
|
|
99
|
-
AND pc.relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = c.table_schema)) as atttypmod
|
|
100
|
-
FROM information_schema.columns c
|
|
101
|
-
WHERE c.table_schema = $1
|
|
102
|
-
ORDER BY c.table_name, c.ordinal_position
|
|
103
|
-
`;
|
|
104
|
-
var ENUMS_QUERY = `
|
|
105
|
-
SELECT t.typname AS enum_name,
|
|
106
|
-
e.enumlabel AS enum_value,
|
|
107
|
-
e.enumsortorder AS sort_order
|
|
108
|
-
FROM pg_type t
|
|
109
|
-
JOIN pg_enum e ON t.oid = e.enumtypid
|
|
110
|
-
JOIN pg_namespace n ON t.typnamespace = n.oid
|
|
111
|
-
WHERE n.nspname = $1
|
|
112
|
-
ORDER BY t.typname, e.enumsortorder
|
|
113
|
-
`;
|
|
114
|
-
/**
|
|
115
|
-
* Primary key columns, in key order.
|
|
116
|
-
*
|
|
117
|
-
* `ORDER BY k.ord` matters for composite keys: the position of a column inside
|
|
118
|
-
* the key is what tells a two-column PK made of two foreign keys apart from an
|
|
119
|
-
* ordinary composite key, and `= ANY(i.indkey)` (the shape this replaced)
|
|
120
|
-
* returns catalog order instead.
|
|
121
|
-
*/
|
|
122
|
-
var PRIMARY_KEYS_QUERY = `
|
|
123
|
-
SELECT t.relname AS table_name,
|
|
124
|
-
a.attname AS column_name
|
|
125
|
-
FROM pg_index i
|
|
126
|
-
JOIN pg_class t ON t.oid = i.indrelid
|
|
127
|
-
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
128
|
-
CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
129
|
-
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
|
|
130
|
-
WHERE i.indisprimary AND n.nspname = $1
|
|
131
|
-
ORDER BY t.relname, k.ord
|
|
132
|
-
`;
|
|
133
|
-
/**
|
|
134
|
-
* Foreign keys, one row per referencing column, with the delete rule.
|
|
135
|
-
*
|
|
136
|
-
* Read from `pg_constraint` rather than through
|
|
137
|
-
* `information_schema.constraint_column_usage`, which does not preserve the
|
|
138
|
-
* pairing on a composite foreign key: it reports the cross product of the
|
|
139
|
-
* constraint's columns, so a two-column FK comes back as four rows, two of them
|
|
140
|
-
* pairing the wrong columns. `unnest(...) WITH ORDINALITY` on both sides joined
|
|
141
|
-
* on the ordinal keeps each referencing column with the column it references.
|
|
142
|
-
*
|
|
143
|
-
* `confdeltype` is carried because `ON DELETE CASCADE` is the schema author
|
|
144
|
-
* saying, in the database, that the child cannot outlive the parent — the one
|
|
145
|
-
* unambiguous declaration of ownership a schema contains.
|
|
146
|
-
*
|
|
147
|
-
* Constraints declared on a *partition* are attributed to the partition root,
|
|
148
|
-
* because that is the table this run generates a collection for. Pagila declares
|
|
149
|
-
* `payment`'s three foreign keys on each monthly partition and none on the
|
|
150
|
-
* parent, so reading `pg_constraint` at face value gives the `payment`
|
|
151
|
-
* collection no relations at all. `pick = 1` then keeps one row per logical key,
|
|
152
|
-
* preferring the root's own constraint when it has one, so a schema that
|
|
153
|
-
* declares the key on the parent *and* inherits it onto 26 partitions does not
|
|
154
|
-
* yield 27 copies of the same relation.
|
|
155
|
-
*/
|
|
156
|
-
var FOREIGN_KEYS_QUERY = `
|
|
157
|
-
WITH fk AS (
|
|
158
|
-
SELECT con.oid,
|
|
159
|
-
con.conname,
|
|
160
|
-
con.conrelid,
|
|
161
|
-
con.confrelid,
|
|
162
|
-
con.conkey,
|
|
163
|
-
con.confkey,
|
|
164
|
-
con.confdeltype,
|
|
165
|
-
COALESCE(pg_partition_root(con.conrelid), con.conrelid) AS root_oid,
|
|
166
|
-
row_number() OVER (
|
|
167
|
-
PARTITION BY COALESCE(pg_partition_root(con.conrelid), con.conrelid),
|
|
168
|
-
con.confrelid, con.conkey, con.confkey
|
|
169
|
-
ORDER BY (con.conrelid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)) DESC,
|
|
170
|
-
con.oid
|
|
171
|
-
) AS pick
|
|
172
|
-
FROM pg_constraint con
|
|
173
|
-
JOIN pg_namespace n ON n.oid = con.connamespace
|
|
174
|
-
WHERE con.contype = 'f' AND n.nspname = $1
|
|
175
|
-
)
|
|
176
|
-
SELECT root.relname AS table_name,
|
|
177
|
-
sa.attname AS column_name,
|
|
178
|
-
tgt.relname AS foreign_table_name,
|
|
179
|
-
ta.attname AS foreign_column_name,
|
|
180
|
-
fk.conname AS constraint_name,
|
|
181
|
-
s.ord::int AS ordinal,
|
|
182
|
-
CASE fk.confdeltype
|
|
183
|
-
WHEN 'a' THEN 'NO ACTION'
|
|
184
|
-
WHEN 'r' THEN 'RESTRICT'
|
|
185
|
-
WHEN 'c' THEN 'CASCADE'
|
|
186
|
-
WHEN 'n' THEN 'SET NULL'
|
|
187
|
-
WHEN 'd' THEN 'SET DEFAULT'
|
|
188
|
-
END AS delete_rule
|
|
189
|
-
FROM fk
|
|
190
|
-
JOIN pg_class root ON root.oid = fk.root_oid
|
|
191
|
-
JOIN pg_class tgt ON tgt.oid = fk.confrelid
|
|
192
|
-
CROSS JOIN LATERAL unnest(fk.conkey) WITH ORDINALITY AS s(attnum, ord)
|
|
193
|
-
JOIN pg_attribute sa ON sa.attrelid = fk.conrelid AND sa.attnum = s.attnum
|
|
194
|
-
CROSS JOIN LATERAL unnest(fk.confkey) WITH ORDINALITY AS f(attnum, ord)
|
|
195
|
-
JOIN pg_attribute ta ON ta.attrelid = fk.confrelid AND ta.attnum = f.attnum
|
|
196
|
-
WHERE fk.pick = 1 AND s.ord = f.ord
|
|
197
|
-
ORDER BY root.relname, fk.conname, s.ord
|
|
198
|
-
`;
|
|
199
|
-
/**
|
|
200
|
-
* Unique constraints and unique indexes, as ordered column lists.
|
|
201
|
-
*
|
|
202
|
-
* Indexes rather than constraints alone, because `CREATE UNIQUE INDEX` and
|
|
203
|
-
* `ADD CONSTRAINT ... UNIQUE` produce the same guarantee and schemas use both.
|
|
204
|
-
* Partial indexes (`indpred IS NOT NULL`) are excluded: they promise uniqueness
|
|
205
|
-
* only over the rows matching their predicate, which is not the promise a
|
|
206
|
-
* `validation: { unique: true }` field makes.
|
|
207
|
-
*/
|
|
208
|
-
var UNIQUE_CONSTRAINTS_QUERY = `
|
|
209
|
-
SELECT t.relname AS table_name,
|
|
210
|
-
ic.relname AS constraint_name,
|
|
211
|
-
-- ::text, because the driver has no parser for an array of \`name\`
|
|
212
|
-
-- and hands back the raw \`{a,b}\` literal as a string. Every consumer
|
|
213
|
-
-- here indexes and compares it as an array, and a string of that
|
|
214
|
-
-- shape fails those silently rather than loudly.
|
|
215
|
-
array_agg(a.attname::text ORDER BY k.ord) AS column_names
|
|
216
|
-
FROM pg_index i
|
|
217
|
-
JOIN pg_class t ON t.oid = i.indrelid
|
|
218
|
-
JOIN pg_class ic ON ic.oid = i.indexrelid
|
|
219
|
-
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
220
|
-
CROSS JOIN LATERAL unnest(i.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
221
|
-
JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = k.attnum
|
|
222
|
-
WHERE i.indisunique
|
|
223
|
-
AND NOT i.indisprimary
|
|
224
|
-
AND i.indpred IS NULL
|
|
225
|
-
AND n.nspname = $1
|
|
226
|
-
AND NOT t.relispartition
|
|
227
|
-
GROUP BY t.relname, ic.relname
|
|
228
|
-
ORDER BY t.relname, ic.relname
|
|
229
|
-
`;
|
|
230
|
-
/**
|
|
231
|
-
* CHECK constraints, as the source text Postgres reproduces them from.
|
|
232
|
-
*
|
|
233
|
-
* `pg_get_constraintdef` output is normalized by the server — the parser in
|
|
234
|
-
* {@link ./introspect-db-constraints.ts} reads that normalized form, not
|
|
235
|
-
* whatever the author typed.
|
|
236
|
-
*/
|
|
237
|
-
var CHECK_CONSTRAINTS_QUERY = `
|
|
238
|
-
SELECT DISTINCT
|
|
239
|
-
root.relname AS table_name,
|
|
240
|
-
con.conname AS constraint_name,
|
|
241
|
-
pg_get_constraintdef(con.oid) AS definition
|
|
242
|
-
FROM pg_constraint con
|
|
243
|
-
JOIN pg_namespace n ON n.oid = con.connamespace
|
|
244
|
-
JOIN pg_class root ON root.oid = COALESCE(pg_partition_root(con.conrelid), con.conrelid)
|
|
245
|
-
WHERE con.contype = 'c'
|
|
246
|
-
AND n.nspname = $1
|
|
247
|
-
ORDER BY root.relname, con.conname
|
|
248
|
-
`;
|
|
249
|
-
/**
|
|
250
|
-
* `COMMENT ON TABLE` / `COMMENT ON COLUMN`, which is documentation the author
|
|
251
|
-
* already wrote and which nothing downstream has ever read.
|
|
252
|
-
*/
|
|
253
|
-
var COMMENTS_QUERY = `
|
|
254
|
-
SELECT t.relname AS table_name,
|
|
255
|
-
a.attname AS column_name,
|
|
256
|
-
d.description AS comment
|
|
257
|
-
FROM pg_description d
|
|
258
|
-
JOIN pg_class t ON t.oid = d.objoid
|
|
259
|
-
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
260
|
-
LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = d.objsubid
|
|
261
|
-
WHERE n.nspname = $1
|
|
262
|
-
AND t.relkind IN ('r', 'p')
|
|
263
|
-
AND (d.objsubid = 0 OR a.attname IS NOT NULL)
|
|
264
|
-
ORDER BY t.relname, d.objsubid
|
|
265
|
-
`;
|
|
266
|
-
/**
|
|
267
|
-
* Counts a table's rows, stopping once the answer can only be "more than
|
|
268
|
-
* `limit`".
|
|
269
|
-
*
|
|
270
|
-
* Introspection asks this to tell a small reference table from a table that
|
|
271
|
-
* merely looks like one (see `classifyTables`). `reltuples` would answer for
|
|
272
|
-
* free but lies on a table that has never been analyzed — which is every table
|
|
273
|
-
* in a database restored from a dump, i.e. exactly the case introspection meets
|
|
274
|
-
* — and reports -1 there rather than an error, so the lie is silent.
|
|
275
|
-
*
|
|
276
|
-
* The subquery's LIMIT caps the work at `limit + 1` rows however large the
|
|
277
|
-
* table is, so this stays cheap on a table with a billion rows.
|
|
278
|
-
*/
|
|
279
|
-
async function countRowsUpTo(client, schema, table, limit) {
|
|
280
|
-
const { rows } = await client.query(`SELECT count(*)::text AS count FROM (SELECT 1 FROM ${quoteRelation(schema, table)} LIMIT ${limit + 1}) probe`);
|
|
281
|
-
return Number(rows[0]?.count ?? 0);
|
|
282
|
-
}
|
|
283
|
-
/**
|
|
284
|
-
* Reads everything the generator needs, in one pass.
|
|
285
|
-
*
|
|
286
|
-
* `rowCounts` is deliberately absent here: it costs a query per table and only
|
|
287
|
-
* a handful of tables can possibly need it. The caller fills it in for the
|
|
288
|
-
* candidates `lookupCandidates()` names.
|
|
289
|
-
*/
|
|
290
|
-
async function readSchemaMetadata(client, schema) {
|
|
291
|
-
const tables = await client.query(TABLES_QUERY, [schema]);
|
|
292
|
-
const columns = await client.query(COLUMNS_QUERY, [schema]);
|
|
293
|
-
const enumValues = await client.query(ENUMS_QUERY, [schema]);
|
|
294
|
-
const pks = await client.query(PRIMARY_KEYS_QUERY, [schema]);
|
|
295
|
-
const fks = await client.query(FOREIGN_KEYS_QUERY, [schema]);
|
|
296
|
-
const uniques = await client.query(UNIQUE_CONSTRAINTS_QUERY, [schema]);
|
|
297
|
-
const checks = await client.query(CHECK_CONSTRAINTS_QUERY, [schema]);
|
|
298
|
-
const comments = await client.query(COMMENTS_QUERY, [schema]);
|
|
299
|
-
const known = new Set(tables.rows.map((t) => t.table_name));
|
|
300
|
-
const scoped = (rows) => rows.filter((r) => known.has(r.table_name));
|
|
301
|
-
return {
|
|
302
|
-
schema,
|
|
303
|
-
tables: tables.rows,
|
|
304
|
-
columns: scoped(columns.rows),
|
|
305
|
-
enumValues: enumValues.rows,
|
|
306
|
-
pks: scoped(pks.rows),
|
|
307
|
-
fks: scoped(fks.rows).filter((fk) => known.has(fk.foreign_table_name)),
|
|
308
|
-
uniques: scoped(uniques.rows),
|
|
309
|
-
checks: scoped(checks.rows),
|
|
310
|
-
comments: scoped(comments.rows),
|
|
311
|
-
rowCounts: {}
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
//#endregion
|
|
3
|
+
import { a as buildSearchColumnSpec, u as searchColumnStamps } from "./search-column-BM-GV6vH.js";
|
|
4
|
+
import { DEFAULT_SEARCH_COLUMN, DEFAULT_SEARCH_LANGUAGE } from "@rebasepro/types";
|
|
5
|
+
import { firstFreeKey, toPostgresIdentifier, toWireKey } from "@rebasepro/utils";
|
|
315
6
|
//#region src/schema/introspect-db-naming.ts
|
|
316
7
|
/**
|
|
317
8
|
* Naming helpers shared by the introspection modules. These live apart from
|
|
@@ -495,6 +186,359 @@ function mapPgType(dataType) {
|
|
|
495
186
|
if (dt === "uuid") return "string";
|
|
496
187
|
return "string";
|
|
497
188
|
}
|
|
189
|
+
//#endregion
|
|
190
|
+
//#region src/schema/introspect-db-storage.ts
|
|
191
|
+
var literal = (value) => JSON.stringify(value);
|
|
192
|
+
/** `character varying` → `varchar`, the spellings the planner's `columnType` uses. */
|
|
193
|
+
var NUMBER_COLUMN_TYPE = {
|
|
194
|
+
"integer": "integer",
|
|
195
|
+
"bigint": "bigint",
|
|
196
|
+
"real": "real",
|
|
197
|
+
"double precision": "double precision"
|
|
198
|
+
};
|
|
199
|
+
/** A sequence default — `nextval('orders_id_seq'::regclass)`. */
|
|
200
|
+
var SEQUENCE_DEFAULT = /^nextval\('([^']+)'::regclass\)$/;
|
|
201
|
+
/**
|
|
202
|
+
* Whether a `nextval` default names the sequence `SERIAL` would have made for
|
|
203
|
+
* this column — the only one the planner can declare, because it declares the
|
|
204
|
+
* column as `SERIAL` and lets Postgres name the sequence.
|
|
205
|
+
*/
|
|
206
|
+
var isConventionalSequence = (col, sequence) => {
|
|
207
|
+
return sequence.replace(/^.*\./, "").replace(/^"|"$/g, "") === serialSequenceName(col.table_name, col.column_name);
|
|
208
|
+
};
|
|
209
|
+
/**
|
|
210
|
+
* The name Postgres gives a `SERIAL` column's sequence — `ChooseRelationName`
|
|
211
|
+
* with the `seq` label: `<table>_<column>_seq`, and when that is over 63 bytes
|
|
212
|
+
* the longer of the two names is shortened, one character at a time, until it
|
|
213
|
+
* fits.
|
|
214
|
+
*/
|
|
215
|
+
function serialSequenceName(table, column) {
|
|
216
|
+
const available = 58;
|
|
217
|
+
let tableChars = table.length;
|
|
218
|
+
let columnChars = column.length;
|
|
219
|
+
while (tableChars + columnChars > available) if (tableChars > columnChars) tableChars--;
|
|
220
|
+
else columnChars--;
|
|
221
|
+
return `${table.slice(0, tableChars)}_${column.slice(0, columnChars)}_seq`;
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* The `isId` (and `columnType`) a single-column primary key needs.
|
|
225
|
+
*
|
|
226
|
+
* `isId: "increment"` is an identity column, and only an INTEGER one. A serial
|
|
227
|
+
* key — an integer with a `nextval` default — is `SERIAL`/`BIGSERIAL`, declared
|
|
228
|
+
* through `columnType` beside `isId: "manual"`. A uuid key is `"uuid"` only when
|
|
229
|
+
* the database generates it; a key with no default is `"manual"`, which keeps
|
|
230
|
+
* the planner from inventing one.
|
|
231
|
+
*/
|
|
232
|
+
function primaryKeyStorage(col, propType) {
|
|
233
|
+
const dataType = col.data_type.toLowerCase();
|
|
234
|
+
const fallback = col.column_default?.trim();
|
|
235
|
+
if (propType === "number") {
|
|
236
|
+
if (col.is_identity === "YES") {
|
|
237
|
+
if (dataType === "integer") return { keys: [`isId: ${literal("increment")}`] };
|
|
238
|
+
return {
|
|
239
|
+
keys: [`isId: ${literal("increment")}`],
|
|
240
|
+
note: `"${col.column_name}" is a ${dataType} identity key; \`isId: "increment"\` is always INTEGER, so a push would plan a narrowing type change (and ask before applying it).`
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
const sequence = fallback ? SEQUENCE_DEFAULT.exec(fallback) : null;
|
|
244
|
+
if (sequence) {
|
|
245
|
+
const serial = dataType === "bigint" ? "bigserial" : dataType === "integer" ? "serial" : void 0;
|
|
246
|
+
if (serial && isConventionalSequence(col, sequence[1])) return { keys: [`isId: ${literal("manual")}`, `columnType: ${literal(serial)}`] };
|
|
247
|
+
return {
|
|
248
|
+
keys: [`isId: ${literal("manual")}`, ...numberColumnType(dataType)],
|
|
249
|
+
note: `"${col.column_name}" takes its value from the sequence ${sequence[1]}, which no property can declare; a push would plan dropping that default.`
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
if (fallback) return { keys: [`isId: ${literal(`sql\`${fallback}\``)}`, ...numberColumnType(dataType)] };
|
|
253
|
+
return { keys: [`isId: ${literal("manual")}`, ...numberColumnType(dataType)] };
|
|
254
|
+
}
|
|
255
|
+
if (dataType === "uuid") {
|
|
256
|
+
if (fallback === "gen_random_uuid()") return { keys: [`isId: ${literal("uuid")}`] };
|
|
257
|
+
if (fallback) return { keys: [`isId: ${literal(`sql\`${fallback}\``)}`, `columnType: ${literal("uuid")}`] };
|
|
258
|
+
return { keys: [`isId: ${literal("manual")}`, `columnType: ${literal("uuid")}`] };
|
|
259
|
+
}
|
|
260
|
+
const strategy = fallback ? `sql\`${fallback}\`` : "manual";
|
|
261
|
+
const stored = stringStorage(col);
|
|
262
|
+
return {
|
|
263
|
+
keys: [`isId: ${literal(strategy)}`, ...stored.keys],
|
|
264
|
+
note: stored.note
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
/** `columnType` for a number column the planner would otherwise make NUMERIC. */
|
|
268
|
+
function numberColumnType(dataType) {
|
|
269
|
+
const mapped = NUMBER_COLUMN_TYPE[dataType];
|
|
270
|
+
return mapped ? [`columnType: ${literal(mapped)}`] : [];
|
|
271
|
+
}
|
|
272
|
+
/** The keys a `string` column needs; the bound itself is emitted as `validation.max`. */
|
|
273
|
+
function stringStorage(col) {
|
|
274
|
+
switch (col.data_type.toLowerCase()) {
|
|
275
|
+
case "text": return { keys: [] };
|
|
276
|
+
case "character varying":
|
|
277
|
+
if (typeof col.character_maximum_length === "number" && col.character_maximum_length > 0) return { keys: [`columnType: ${literal("varchar")}`] };
|
|
278
|
+
return {
|
|
279
|
+
keys: [`columnType: ${literal("varchar")}`],
|
|
280
|
+
note: `"${col.column_name}" is a varchar with no length; the planner always writes one (255 unless \`validation.max\` says otherwise), so a push would plan a narrowing type change.`
|
|
281
|
+
};
|
|
282
|
+
case "character": return { keys: [`columnType: ${literal("char")}`] };
|
|
283
|
+
case "uuid": return { keys: [`columnType: ${literal("uuid")}`] };
|
|
284
|
+
default: return {
|
|
285
|
+
keys: [],
|
|
286
|
+
note: `"${col.column_name}" is ${col.data_type === "USER-DEFINED" ? col.udt_name : col.data_type}, which no property type stores; it is read as text, and a push would plan converting the column to text.`
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The keys a non-key column needs, for the property type introspection chose.
|
|
292
|
+
*
|
|
293
|
+
* `enumTypeName` is the type the planner would name for this column
|
|
294
|
+
* (`<table>_<column>`, cut to 63 bytes); an enum column whose type is called
|
|
295
|
+
* anything else cannot be declared, and the note says how to rename it.
|
|
296
|
+
*/
|
|
297
|
+
function columnStorage(col, propType, context) {
|
|
298
|
+
const dataType = col.data_type.toLowerCase();
|
|
299
|
+
if (context.isEnumColumn) {
|
|
300
|
+
if (col.udt_name === context.enumTypeName) return { keys: [] };
|
|
301
|
+
return {
|
|
302
|
+
keys: [],
|
|
303
|
+
note: context.enumTypeShared ? `"${col.column_name}" uses the enum type "${col.udt_name}", which other columns share; Rebase gives each column its own type (<table>_<column>), so a push would plan "${context.enumTypeName}" and a conversion Postgres cannot cast.` : `"${col.column_name}" uses the enum type "${col.udt_name}", and Rebase names a column's enum type <table>_<column>. Rename it before pushing: ALTER TYPE "${col.udt_name}" RENAME TO "${context.enumTypeName}";`
|
|
304
|
+
};
|
|
305
|
+
}
|
|
306
|
+
switch (propType) {
|
|
307
|
+
case "number": {
|
|
308
|
+
if (dataType === "numeric") {
|
|
309
|
+
const keys = [];
|
|
310
|
+
if (typeof col.numeric_precision === "number") keys.push(`precision: ${col.numeric_precision}`);
|
|
311
|
+
if (typeof col.numeric_precision === "number" && typeof col.numeric_scale === "number") keys.push(`scale: ${col.numeric_scale}`);
|
|
312
|
+
return { keys };
|
|
313
|
+
}
|
|
314
|
+
if (dataType === "smallint") return {
|
|
315
|
+
keys: [`columnType: ${literal("integer")}`],
|
|
316
|
+
note: `"${col.column_name}" is smallint, which no \`columnType\` names; it is declared integer, so a push widens it (every value survives).`
|
|
317
|
+
};
|
|
318
|
+
const mapped = numberColumnType(dataType);
|
|
319
|
+
if (mapped.length > 0) return { keys: mapped };
|
|
320
|
+
return {
|
|
321
|
+
keys: [],
|
|
322
|
+
note: `"${col.column_name}" is ${col.data_type}, which no \`columnType\` names; it is declared numeric, and a push would plan converting it.`
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
case "string": return stringStorage(col);
|
|
326
|
+
case "date": switch (dataType) {
|
|
327
|
+
case "timestamp with time zone": return { keys: [] };
|
|
328
|
+
case "date": return { keys: [`columnType: ${literal("date")}`] };
|
|
329
|
+
case "time without time zone": return { keys: [`columnType: ${literal("time")}`] };
|
|
330
|
+
default: return {
|
|
331
|
+
keys: [],
|
|
332
|
+
note: `"${col.column_name}" is ${col.data_type}; a date property stores timestamptz, date or time, so a push would plan converting it to timestamptz (and ask before applying it).`
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
case "map": return dataType === "json" ? { keys: [`columnType: ${literal("json")}`] } : { keys: [] };
|
|
336
|
+
default: return { keys: [] };
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* The `columnType` an array column needs, or a note when its element type is
|
|
341
|
+
* not one the planner stores natively.
|
|
342
|
+
*
|
|
343
|
+
* Only `text[]`, `integer[]`, `boolean[]` and `numeric[]` are. Reading
|
|
344
|
+
* `bigint[]` as `integer[]` — what this used to do — planned a narrowing.
|
|
345
|
+
*/
|
|
346
|
+
function arrayStorage(col) {
|
|
347
|
+
switch (col.udt_name) {
|
|
348
|
+
case "_text": return {
|
|
349
|
+
columnType: "text[]",
|
|
350
|
+
innerType: "string"
|
|
351
|
+
};
|
|
352
|
+
case "_int4": return {
|
|
353
|
+
columnType: "integer[]",
|
|
354
|
+
innerType: "number"
|
|
355
|
+
};
|
|
356
|
+
case "_bool": return {
|
|
357
|
+
columnType: "boolean[]",
|
|
358
|
+
innerType: "boolean"
|
|
359
|
+
};
|
|
360
|
+
case "_numeric": return {
|
|
361
|
+
columnType: "numeric[]",
|
|
362
|
+
innerType: "number"
|
|
363
|
+
};
|
|
364
|
+
default: {
|
|
365
|
+
const element = col.udt_name.replace(/^_/, "");
|
|
366
|
+
return {
|
|
367
|
+
innerType: "string",
|
|
368
|
+
note: `"${col.column_name}" is an array of ${element}; arrays are stored as text[], integer[], boolean[] or numeric[] (anything else as jsonb), so a push would plan converting it.`
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* A column default as a `defaultValue`, when it is a literal a property can carry.
|
|
375
|
+
*
|
|
376
|
+
* `undefined` when there is no default to carry, or when the default is one the
|
|
377
|
+
* generator expresses another way (`now()` is `autoValue`, a key's default is
|
|
378
|
+
* its `isId`). `{ note }` when there is a default and no property can say it —
|
|
379
|
+
* a push would plan dropping it.
|
|
380
|
+
*/
|
|
381
|
+
function literalDefaultOf(col, propType) {
|
|
382
|
+
const raw = col.column_default?.trim();
|
|
383
|
+
if (!raw) return void 0;
|
|
384
|
+
if (/^(now\(\)|CURRENT_TIMESTAMP)$/i.test(raw)) return void 0;
|
|
385
|
+
const quoted = /^'((?:[^']|'')*)'(?:::[\w\s."[\]]+)?$/.exec(raw);
|
|
386
|
+
const unquoted = quoted ? quoted[1].replace(/''/g, "'") : void 0;
|
|
387
|
+
switch (propType) {
|
|
388
|
+
case "string":
|
|
389
|
+
if (unquoted !== void 0) return { source: literal(unquoted) };
|
|
390
|
+
break;
|
|
391
|
+
case "number": {
|
|
392
|
+
const text = unquoted ?? raw.replace(/^\((.*)\)$/, "$1").replace(/::[\w\s]+$/, "");
|
|
393
|
+
if (/^-?\d+(\.\d+)?$/.test(text) && Number.isFinite(Number(text))) return { source: String(Number(text)) };
|
|
394
|
+
break;
|
|
395
|
+
}
|
|
396
|
+
case "boolean":
|
|
397
|
+
if (/^true$/i.test(raw)) return { source: "true" };
|
|
398
|
+
if (/^false$/i.test(raw)) return { source: "false" };
|
|
399
|
+
break;
|
|
400
|
+
case "map":
|
|
401
|
+
if (unquoted !== void 0) try {
|
|
402
|
+
const parsed = JSON.parse(unquoted);
|
|
403
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return { source: JSON.stringify(parsed) };
|
|
404
|
+
} catch {}
|
|
405
|
+
break;
|
|
406
|
+
default: break;
|
|
407
|
+
}
|
|
408
|
+
return { note: `"${col.column_name}" defaults to ${raw}, which no \`defaultValue\` can express; a push would plan dropping that default.` };
|
|
409
|
+
}
|
|
410
|
+
/** `ON DELETE` as the relation's `onDelete`, when it is not the default the planner would choose. */
|
|
411
|
+
function onDeleteOf(fk, required) {
|
|
412
|
+
const rule = fk.delete_rule?.toUpperCase();
|
|
413
|
+
if (!rule) return void 0;
|
|
414
|
+
if (rule === (required ? "RESTRICT" : "SET NULL")) return void 0;
|
|
415
|
+
return rule.toLowerCase();
|
|
416
|
+
}
|
|
417
|
+
//#endregion
|
|
418
|
+
//#region src/schema/introspect-db-search.ts
|
|
419
|
+
/**
|
|
420
|
+
* A collection's `search` block, read back out of the column it built.
|
|
421
|
+
*
|
|
422
|
+
* A Rebase search column is `tsvector GENERATED ALWAYS AS (…) STORED`, stamped
|
|
423
|
+
* with a fingerprint of the expression in its `COMMENT`. Introspection used to
|
|
424
|
+
* emit it as an ordinary read-only string property, which the planner makes a
|
|
425
|
+
* `text` column — so the first push after adopting a Rebase database planned
|
|
426
|
+
* `ALTER COLUMN "search_vector" TYPE text … DROP EXPRESSION`, and search was
|
|
427
|
+
* gone for whoever approved it.
|
|
428
|
+
*
|
|
429
|
+
* Reading the block back is a guess checked by the stamp: the deparsed
|
|
430
|
+
* expression names each field's column, weight and language, which is enough
|
|
431
|
+
* to write a candidate block; the candidate is then compiled by the very code
|
|
432
|
+
* that built the column, and kept only if its fingerprint is the one the column
|
|
433
|
+
* carries. A block that does not reproduce the stamp is not emitted at all —
|
|
434
|
+
* the note says so — because a wrong one would rebuild the column differently.
|
|
435
|
+
*
|
|
436
|
+
* `mode` and `fuzzyThreshold` act at query time and are stored nowhere, so they
|
|
437
|
+
* come back as their defaults.
|
|
438
|
+
*/
|
|
439
|
+
/** One `setweight(to_tsvector('<lang>'::regconfig, <text>), '<W>'::"char")`, deparsed. */
|
|
440
|
+
var SEGMENT = /setweight\(to_tsvector\('((?:[^']|'')+)'::regconfig, ([\s\S]+?)\), '([A-D])'::"char"\)/g;
|
|
441
|
+
/** A property with the column's shape, for the candidate block to resolve against. */
|
|
442
|
+
function propertyFor(col) {
|
|
443
|
+
if (col.data_type === "text" || col.data_type === "character varying" || col.data_type === "character") return {
|
|
444
|
+
name: col.column_name,
|
|
445
|
+
type: "string",
|
|
446
|
+
columnName: col.column_name
|
|
447
|
+
};
|
|
448
|
+
if (col.udt_name === "_text") return {
|
|
449
|
+
name: col.column_name,
|
|
450
|
+
type: "array",
|
|
451
|
+
columnName: col.column_name,
|
|
452
|
+
of: {
|
|
453
|
+
name: col.column_name,
|
|
454
|
+
type: "string"
|
|
455
|
+
}
|
|
456
|
+
};
|
|
457
|
+
if (col.data_type === "jsonb") return {
|
|
458
|
+
name: col.column_name,
|
|
459
|
+
type: "map",
|
|
460
|
+
columnName: col.column_name,
|
|
461
|
+
keyValue: true
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* The search block a table's stamped generated columns were built from, or a
|
|
466
|
+
* note saying why it could not be read back.
|
|
467
|
+
*/
|
|
468
|
+
function reconstructSearchBlock(input) {
|
|
469
|
+
const stamped = input.columns.filter((col) => col.is_generated === "ALWAYS" && (input.comments.get(col.column_name) ?? "").startsWith("rebase:search:v1:"));
|
|
470
|
+
const main = stamped.find((col) => col.udt_name === "tsvector");
|
|
471
|
+
if (!main) return { columns: /* @__PURE__ */ new Set() };
|
|
472
|
+
const fuzzy = stamped.find((col) => col.column_name === `${main.column_name}_text`);
|
|
473
|
+
const columns = new Set(stamped.map((col) => col.column_name));
|
|
474
|
+
const unreadable = (why) => ({
|
|
475
|
+
columns,
|
|
476
|
+
note: `"${main.column_name}" is a Rebase search column whose \`search\` block could not be read back (${why}). Declare the block again before pushing — without it a push plans dropping the column.`
|
|
477
|
+
});
|
|
478
|
+
const expression = main.generation_expression ?? "";
|
|
479
|
+
const byColumn = new Map(input.columns.map((col) => [col.column_name, col]));
|
|
480
|
+
const fields = [];
|
|
481
|
+
let language;
|
|
482
|
+
let unaccent = false;
|
|
483
|
+
for (const [, lang, inner, weight] of expression.matchAll(SEGMENT)) {
|
|
484
|
+
language ??= lang.replace(/''/g, "'");
|
|
485
|
+
if (lang.replace(/''/g, "'") !== language) return unreadable("its fields use different languages");
|
|
486
|
+
if (inner.includes("rebase_search_unaccent")) unaccent = true;
|
|
487
|
+
const column = [...inner.matchAll(/"?([A-Za-z_][A-Za-z0-9_$]*)"?/g)].map((m) => m[1]).find((name) => byColumn.has(name) && !columns.has(name));
|
|
488
|
+
if (!column) return unreadable("a field reads no column of this table");
|
|
489
|
+
const key = input.keyByColumn.get(column);
|
|
490
|
+
if (!key) return unreadable(`the column "${column}" is not a property`);
|
|
491
|
+
const jsonPath = [...inner.matchAll(/(?:->|#>)\s*'([^']+)'/g)].flatMap((m) => m[1].replace(/^\{|\}$/g, "").split(","));
|
|
492
|
+
fields.push({
|
|
493
|
+
path: [key, ...jsonPath].join("."),
|
|
494
|
+
weight
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
if (fields.length === 0 || !language) return unreadable("its expression is not one Rebase writes");
|
|
498
|
+
const search = {
|
|
499
|
+
...main.column_name !== DEFAULT_SEARCH_COLUMN ? { column: main.column_name } : {},
|
|
500
|
+
...language !== DEFAULT_SEARCH_LANGUAGE ? { language } : {},
|
|
501
|
+
...unaccent ? { unaccent: true } : {},
|
|
502
|
+
...fuzzy ? { fuzzy: true } : {},
|
|
503
|
+
fields: fields.map((f) => ({
|
|
504
|
+
path: f.path,
|
|
505
|
+
weight: f.weight
|
|
506
|
+
}))
|
|
507
|
+
};
|
|
508
|
+
const properties = {};
|
|
509
|
+
for (const [column, key] of input.keyByColumn) {
|
|
510
|
+
const col = byColumn.get(column);
|
|
511
|
+
const prop = col ? propertyFor(col) : void 0;
|
|
512
|
+
if (prop) properties[key] = prop;
|
|
513
|
+
}
|
|
514
|
+
const candidate = {
|
|
515
|
+
slug: input.table,
|
|
516
|
+
name: input.table,
|
|
517
|
+
table: input.table,
|
|
518
|
+
...input.schema !== "public" ? { schema: input.schema } : {},
|
|
519
|
+
properties,
|
|
520
|
+
search
|
|
521
|
+
};
|
|
522
|
+
let fingerprints;
|
|
523
|
+
try {
|
|
524
|
+
const spec = buildSearchColumnSpec(candidate);
|
|
525
|
+
if (!spec) return unreadable("no block compiles from it");
|
|
526
|
+
fingerprints = new Map(searchColumnStamps(spec).map((stamp) => [stamp.column, stamp.fingerprint]));
|
|
527
|
+
} catch (err) {
|
|
528
|
+
return unreadable(err instanceof Error ? err.message : String(err));
|
|
529
|
+
}
|
|
530
|
+
for (const col of stamped) if (fingerprints.get(col.column_name) !== input.comments.get(col.column_name)) return unreadable("the block read from its expression does not reproduce the column's stamp");
|
|
531
|
+
return {
|
|
532
|
+
columns,
|
|
533
|
+
block: `\n search: {\n ${[
|
|
534
|
+
...search.column ? [`column: ${JSON.stringify(search.column)}`] : [],
|
|
535
|
+
...search.language ? [`language: ${JSON.stringify(search.language)}`] : [],
|
|
536
|
+
...search.unaccent ? ["unaccent: true"] : [],
|
|
537
|
+
...search.fuzzy ? ["fuzzy: true"] : [],
|
|
538
|
+
`fields: [\n${fields.map((f) => ` { path: ${JSON.stringify(f.path)}, weight: ${JSON.stringify(f.weight)} }`).join(",\n")}\n ]`
|
|
539
|
+
].join(",\n ")}\n },`
|
|
540
|
+
};
|
|
541
|
+
}
|
|
498
542
|
/**
|
|
499
543
|
* A timestamp the database maintains: a temporal column defaulting to the
|
|
500
544
|
* transaction clock.
|
|
@@ -908,6 +952,34 @@ function deriveListProperties(propertiesOrder, hidden = /* @__PURE__ */ new Set(
|
|
|
908
952
|
* no process.exit. It is imported by introspect-db.ts (the CLI entry-point)
|
|
909
953
|
* and consumed directly by tests.
|
|
910
954
|
*/
|
|
955
|
+
/**
|
|
956
|
+
* Why a table keyed on several columns is not generated as a collection, or
|
|
957
|
+
* `undefined` when it is.
|
|
958
|
+
*
|
|
959
|
+
* Several `isId` properties are one composite key, and the planner builds that
|
|
960
|
+
* table under the same `PRIMARY KEY (a, b)` — so such a table round-trips when
|
|
961
|
+
* two things hold:
|
|
962
|
+
*
|
|
963
|
+
* - **Every key column can carry `isId`,** which exists on string and number
|
|
964
|
+
* properties only. Read from the column's SQL type, not a data sample: a
|
|
965
|
+
* `line_no` holding only 1s is not a boolean. A key with a column of another
|
|
966
|
+
* type — pagila's `payment` is keyed on a timestamp too — can be marked on
|
|
967
|
+
* some of its columns only, and those would be read as the whole key.
|
|
968
|
+
* - **Nothing points at it.** A foreign key into it, or a junction, is a link
|
|
969
|
+
* into a composite key, which the planner refuses: the relation has one
|
|
970
|
+
* column to point with.
|
|
971
|
+
*/
|
|
972
|
+
function compositeKeySkipReason(meta, allFks) {
|
|
973
|
+
if (meta.pks.length < 2) return void 0;
|
|
974
|
+
const unmarkable = meta.pks.filter((pk) => {
|
|
975
|
+
const column = meta.columns.find((c) => c.column_name === pk);
|
|
976
|
+
const type = column ? mapPgType(column.data_type) : void 0;
|
|
977
|
+
return type !== "string" && type !== "number";
|
|
978
|
+
});
|
|
979
|
+
if (unmarkable.length > 0) return `its key column${unmarkable.length > 1 ? "s" : ""} ${unmarkable.map((c) => `"${c}"`).join(", ")} cannot carry \`isId\`, which a string or number property takes`;
|
|
980
|
+
const referencing = [...new Set(allFks.filter((fk) => fk.foreign_table_name === meta.name && fk.table_name !== meta.name).map((fk) => fk.table_name))];
|
|
981
|
+
if (referencing.length > 0) return `${referencing.map((t) => `"${t}"`).join(", ")} point${referencing.length > 1 ? "" : "s"} at it, and a link cannot point at a composite key`;
|
|
982
|
+
}
|
|
911
983
|
var IRREGULAR_SINGULARS = {
|
|
912
984
|
people: "person",
|
|
913
985
|
children: "child",
|
|
@@ -1265,6 +1337,8 @@ function withAdminOptions(extra, entries, emitAdmin = true) {
|
|
|
1265
1337
|
if (extra.includes("admin: {")) return extra.replace("admin: {", `admin: {\n${block},`);
|
|
1266
1338
|
return `${extra}\n admin: {\n${block}\n },`;
|
|
1267
1339
|
}
|
|
1340
|
+
/** A SQL string literal. */
|
|
1341
|
+
var quoteSqlString = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
1268
1342
|
/** A TypeScript string literal, escaped. */
|
|
1269
1343
|
function quote(value) {
|
|
1270
1344
|
return JSON.stringify(value);
|
|
@@ -1369,6 +1443,9 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1369
1443
|
};
|
|
1370
1444
|
let propsOutput = "";
|
|
1371
1445
|
let relationsOutput = "";
|
|
1446
|
+
/** What the planner will not reproduce exactly, column by column. */
|
|
1447
|
+
const fileNotes = [];
|
|
1448
|
+
const skippedTables = context.skippedTables ?? /* @__PURE__ */ new Set();
|
|
1372
1449
|
const orderEntries = [];
|
|
1373
1450
|
const propertyBlocks = /* @__PURE__ */ new Map();
|
|
1374
1451
|
/**
|
|
@@ -1386,25 +1463,45 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1386
1463
|
const hiddenFromCollection = /* @__PURE__ */ new Set();
|
|
1387
1464
|
let columnIndex = 0;
|
|
1388
1465
|
const isCompositePk = meta.pks.length > 1;
|
|
1466
|
+
/**
|
|
1467
|
+
* The property type a column is generated as, with what the data sample
|
|
1468
|
+
* adds to it. A column of a composite key keeps its SQL type's reading:
|
|
1469
|
+
* it carries `isId`, which only a string or number property takes, and a
|
|
1470
|
+
* key column holding only 1s and 0s is still a key, not a boolean.
|
|
1471
|
+
*/
|
|
1472
|
+
const propertyTypeOf = (col) => {
|
|
1473
|
+
const isEnumColumn = col.data_type === "USER-DEFINED" && enumMap.get(col.udt_name) !== void 0;
|
|
1474
|
+
const propType = isEnumColumn ? "string" : col.udt_name === "vector" ? "vector" : mapPgType(col.data_type);
|
|
1475
|
+
if (isEnumColumn || !sampleData || sampleData.length === 0 || isCompositePk && meta.pks.includes(col.column_name)) return {
|
|
1476
|
+
propType,
|
|
1477
|
+
finalPropType: propType,
|
|
1478
|
+
inferenceExtra: ""
|
|
1479
|
+
};
|
|
1480
|
+
const values = sampleData.map((r) => r[col.column_name]);
|
|
1481
|
+
const inferred = inferPropertyFromData(col.column_name, col.data_type, propType, values, meta.pks.includes(col.column_name), emitAdmin);
|
|
1482
|
+
return {
|
|
1483
|
+
propType,
|
|
1484
|
+
finalPropType: inferred.propType || propType,
|
|
1485
|
+
inferenceExtra: inferred.extra || ""
|
|
1486
|
+
};
|
|
1487
|
+
};
|
|
1488
|
+
const compositeKeyMarkable = isCompositePk && meta.pks.every((pk) => {
|
|
1489
|
+
const keyColumn = meta.columns.find((c) => c.column_name === pk);
|
|
1490
|
+
if (!keyColumn) return false;
|
|
1491
|
+
const { finalPropType } = propertyTypeOf(keyColumn);
|
|
1492
|
+
return finalPropType === "string" || finalPropType === "number";
|
|
1493
|
+
});
|
|
1389
1494
|
for (const col of meta.columns) {
|
|
1495
|
+
if (col.is_generated === "ALWAYS" && (columnComments.get(col.column_name) ?? "").startsWith("rebase:search:v1:")) continue;
|
|
1390
1496
|
if (meta.fks.some((fk) => fk.column_name === col.column_name) && !meta.pks.includes(col.column_name)) continue;
|
|
1391
1497
|
const currentIndex = columnIndex++;
|
|
1392
1498
|
const propertyKey = firstFreeKey([toWireKey(col.column_name), col.column_name], propertyBlocks);
|
|
1393
1499
|
keyByColumn.set(col.column_name, propertyKey);
|
|
1394
1500
|
const colEnumValues = enumMap.get(col.udt_name);
|
|
1395
1501
|
const isEnumColumn = col.data_type === "USER-DEFINED" && colEnumValues !== void 0;
|
|
1396
|
-
const isVectorColumn = col.udt_name === "vector";
|
|
1397
|
-
const propType = isEnumColumn ? "string" : isVectorColumn ? "vector" : mapPgType(col.data_type);
|
|
1398
1502
|
let extra = "";
|
|
1399
1503
|
const colNameLower = col.column_name.toLowerCase();
|
|
1400
|
-
|
|
1401
|
-
let inferenceExtra = "";
|
|
1402
|
-
if (!isEnumColumn && sampleData && sampleData.length > 0) {
|
|
1403
|
-
const values = sampleData.map((r) => r[col.column_name]);
|
|
1404
|
-
const inferred = inferPropertyFromData(col.column_name, col.data_type, propType, values, meta.pks.includes(col.column_name), emitAdmin);
|
|
1405
|
-
if (inferred.propType) finalPropType = inferred.propType;
|
|
1406
|
-
if (inferred.extra) inferenceExtra = inferred.extra;
|
|
1407
|
-
}
|
|
1504
|
+
const { propType, finalPropType, inferenceExtra } = propertyTypeOf(col);
|
|
1408
1505
|
const columnChecks = tableChecks?.get(col.column_name);
|
|
1409
1506
|
if (isEnumColumn && colEnumValues) {
|
|
1410
1507
|
const enumEntries = colEnumValues.map((v) => `{ id: ${quote(v)}, label: ${quote(humanize(v))} }`).join(", ");
|
|
@@ -1412,6 +1509,13 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1412
1509
|
} else if (columnChecks?.enumValues && !inferenceExtra.includes("enum:") && propType === "string") {
|
|
1413
1510
|
const enumEntries = columnChecks.enumValues.map((v) => `{ id: ${quote(v)}, label: ${quote(humanize(v))} }`).join(", ");
|
|
1414
1511
|
extra += `\n enum: [${enumEntries}],`;
|
|
1512
|
+
const enumType = toPostgresIdentifier(`${tableName}_${col.column_name}`);
|
|
1513
|
+
const labels = columnChecks.enumValues.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ");
|
|
1514
|
+
const check = (context.metadata?.checks ?? []).find((c) => c.table_name === tableName && c.definition.includes(col.column_name));
|
|
1515
|
+
const table = `"${tableName}"`;
|
|
1516
|
+
const column = `"${col.column_name}"`;
|
|
1517
|
+
const restoreDefault = literalDefaultOf(col, "string");
|
|
1518
|
+
fileNotes.push(`"${col.column_name}" is text with CHECK (… IN …), declared here as an \`enum\`, which Rebase stores as the enum type "${enumType}". Convert the column before pushing: CREATE TYPE "${enumType}" AS ENUM (${labels}); ALTER TABLE ${table} ${check ? `DROP CONSTRAINT "${check.constraint_name}", ` : ""}ALTER COLUMN ${column} DROP DEFAULT, ALTER COLUMN ${column} TYPE "${enumType}" USING ${column}::"${enumType}"` + (restoreDefault && "source" in restoreDefault ? `, ALTER COLUMN ${column} SET DEFAULT ${quoteSqlString(JSON.parse(restoreDefault.source))}` : "") + "; — or delete the `enum` to keep the column as it is.");
|
|
1415
1519
|
}
|
|
1416
1520
|
if (finalPropType === "date") {
|
|
1417
1521
|
if (colNameLower === "created_at" || colNameLower === "createdat") {
|
|
@@ -1428,16 +1532,10 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1428
1532
|
}
|
|
1429
1533
|
}
|
|
1430
1534
|
if (finalPropType === "array" && !inferenceExtra.includes("of: {")) {
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
if (
|
|
1434
|
-
|
|
1435
|
-
if (innerType === "string") colType = "text[]";
|
|
1436
|
-
else if (innerType === "number") colType = col.udt_name === "_numeric" ? "numeric[]" : "integer[]";
|
|
1437
|
-
else if (innerType === "boolean") colType = "boolean[]";
|
|
1438
|
-
}
|
|
1439
|
-
if (colType) extra += `\n columnType: ${quote(colType)},`;
|
|
1440
|
-
extra += `\n of: { name: ${quote(`${humanize(col.column_name)} Item`)}, type: ${quote(innerType)} },`;
|
|
1535
|
+
const stored = arrayStorage(col);
|
|
1536
|
+
if (stored.columnType) extra += `\n columnType: ${quote(stored.columnType)},`;
|
|
1537
|
+
if (stored.note) fileNotes.push(stored.note);
|
|
1538
|
+
extra += `\n of: { name: ${quote(`${humanize(col.column_name)} Item`)}, type: ${quote(stored.innerType)} },`;
|
|
1441
1539
|
} else if (finalPropType === "map" && !inferenceExtra.includes("keyValue: true") && !inferenceExtra.includes("properties: {")) extra += "\n keyValue: true,";
|
|
1442
1540
|
if (finalPropType === "string" && !isEnumColumn && !inferenceExtra) {
|
|
1443
1541
|
const isUrl = colNameLower.endsWith("_url") || colNameLower.endsWith("_uri") || colNameLower.endsWith("_link");
|
|
@@ -1451,6 +1549,25 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1451
1549
|
extra += inferenceExtra;
|
|
1452
1550
|
if (!extra.endsWith(",")) extra += ",";
|
|
1453
1551
|
}
|
|
1552
|
+
if (!meta.pks.includes(col.column_name) && !isReadOnlyColumn(col)) {
|
|
1553
|
+
const enumTypeName = toPostgresIdentifier(`${tableName}_${col.column_name}`);
|
|
1554
|
+
const enumTypeShared = isEnumColumn && (context.metadata?.columns ?? meta.columns).filter((other) => other.udt_name === col.udt_name && other.data_type === "USER-DEFINED").length > 1;
|
|
1555
|
+
const stored = finalPropType === "array" ? { keys: [] } : columnStorage(col, finalPropType, {
|
|
1556
|
+
isEnumColumn,
|
|
1557
|
+
enumTypeName,
|
|
1558
|
+
enumTypeShared
|
|
1559
|
+
});
|
|
1560
|
+
for (const key of stored.keys) {
|
|
1561
|
+
const name = key.slice(0, key.indexOf(":"));
|
|
1562
|
+
if (!hasGeneratedKey(extra, name) && !hasGeneratedKey(inferenceExtra, name)) extra += `\n ${key},`;
|
|
1563
|
+
}
|
|
1564
|
+
if (stored.note) fileNotes.push(stored.note);
|
|
1565
|
+
if (!hasGeneratedKey(extra, "autoValue") && !hasGeneratedKey(extra, "defaultValue")) {
|
|
1566
|
+
const fallback = literalDefaultOf(col, finalPropType);
|
|
1567
|
+
if (fallback && "source" in fallback) extra += `\n defaultValue: ${fallback.source},`;
|
|
1568
|
+
else if (fallback) fileNotes.push(fallback.note);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1454
1571
|
const declaredValidation = [];
|
|
1455
1572
|
if (finalPropType === "string" && typeof col.character_maximum_length === "number" && col.character_maximum_length > 0 && !hasGeneratedKey(extra, "max")) declaredValidation.push(`max: ${col.character_maximum_length}`);
|
|
1456
1573
|
if (columnChecks) {
|
|
@@ -1478,16 +1595,30 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1478
1595
|
const columnComment = columnComments.get(col.column_name);
|
|
1479
1596
|
if (columnComment) extra = `\n description: ${quote(columnComment)},${extra}`;
|
|
1480
1597
|
if (meta.pks.includes(col.column_name)) {
|
|
1481
|
-
if (isCompositePk)
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1598
|
+
if (isCompositePk) {
|
|
1599
|
+
extra += `\n // Part of composite primary key (${commentText(meta.pks.join(", "))})`;
|
|
1600
|
+
if (compositeKeyMarkable && !inferenceExtra.includes("isId:")) {
|
|
1601
|
+
const stored = primaryKeyStorage(col, finalPropType);
|
|
1602
|
+
for (const key of stored.keys) {
|
|
1603
|
+
const name = key.slice(0, key.indexOf(":"));
|
|
1604
|
+
if (!hasGeneratedKey(extra, name)) extra += `\n ${key},`;
|
|
1605
|
+
}
|
|
1606
|
+
if (stored.note) fileNotes.push(stored.note);
|
|
1607
|
+
}
|
|
1608
|
+
} else if (!inferenceExtra.includes("isId:")) {
|
|
1609
|
+
const stored = primaryKeyStorage(col, finalPropType);
|
|
1610
|
+
for (const key of stored.keys) {
|
|
1611
|
+
const name = key.slice(0, key.indexOf(":"));
|
|
1612
|
+
if (!hasGeneratedKey(extra, name)) extra += `\n ${key},`;
|
|
1613
|
+
}
|
|
1614
|
+
if (stored.note) fileNotes.push(stored.note);
|
|
1615
|
+
}
|
|
1485
1616
|
}
|
|
1486
1617
|
if (finalPropType === "vector") {
|
|
1487
1618
|
const dims = col.atttypmod && col.atttypmod > 0 ? col.atttypmod : 1536;
|
|
1488
1619
|
extra += `\n dimensions: ${dims},`;
|
|
1489
1620
|
}
|
|
1490
|
-
if (col.is_nullable === "NO" && !meta.pks.includes(col.column_name) && !
|
|
1621
|
+
if (col.is_nullable === "NO" && !meta.pks.includes(col.column_name) && !isReadOnlyColumn(col)) if (extra.includes("validation: {")) extra = extra.replace("validation: {", "validation: {\n required: true,");
|
|
1491
1622
|
else extra += "\n validation: {\n required: true\n },";
|
|
1492
1623
|
const humanName = humanize(col.column_name);
|
|
1493
1624
|
orderEntries.push({
|
|
@@ -1510,6 +1641,7 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1510
1641
|
}
|
|
1511
1642
|
for (const fk of meta.fks) {
|
|
1512
1643
|
const targetTableName = fk.foreign_table_name;
|
|
1644
|
+
if (skippedTables.has(targetTableName)) continue;
|
|
1513
1645
|
if (!joinTables.has(targetTableName)) {
|
|
1514
1646
|
const stripped = toWireKey(fk.column_name.replace(/_id$/, ""));
|
|
1515
1647
|
const relName = firstFreeKey([
|
|
@@ -1530,27 +1662,47 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1530
1662
|
});
|
|
1531
1663
|
const targetCollectionCamel = importCollection(targetTableName);
|
|
1532
1664
|
const relHumanName = humanize(relName);
|
|
1665
|
+
const required = meta.columns.find((c) => c.column_name === fk.column_name)?.is_nullable === "NO";
|
|
1666
|
+
const onDelete = onDeleteOf(fk, required);
|
|
1667
|
+
const requiredLine = required ? "\n validation: { required: true }," : "";
|
|
1668
|
+
const onDeleteLine = onDelete ? `,\n onDelete: ${quote(onDelete)}` : "";
|
|
1533
1669
|
propertyBlocks.set(relName, `
|
|
1534
1670
|
${propKey(relName)}: {
|
|
1535
1671
|
name: ${quote(relHumanName)},
|
|
1536
|
-
type: "relation"
|
|
1672
|
+
type: "relation",${requiredLine}
|
|
1537
1673
|
// mapped from foreign key: ${commentText(fk.column_name)} -> ${commentText(targetTableName)}(${commentText(fk.foreign_column_name)})
|
|
1538
1674
|
relation: {
|
|
1539
1675
|
kind: "belongsTo",
|
|
1540
1676
|
target: ${relationTarget(targetCollectionCamel)},
|
|
1541
|
-
localKey: ${quote(fk.column_name)}
|
|
1677
|
+
localKey: ${quote(fk.column_name)}${onDeleteLine}
|
|
1542
1678
|
}
|
|
1543
1679
|
},`);
|
|
1544
1680
|
}
|
|
1545
1681
|
}
|
|
1546
|
-
|
|
1682
|
+
/**
|
|
1683
|
+
* A name for an entry in the `relations` array that no property and no
|
|
1684
|
+
* earlier entry has taken.
|
|
1685
|
+
*
|
|
1686
|
+
* Relations and properties share one namespace — a relation is found by
|
|
1687
|
+
* name — so a `belongsTo` property called `series` beside a many-to-many
|
|
1688
|
+
* also called `series` left one of them unreachable: the planner resolved
|
|
1689
|
+
* the property's name to the many-to-many, planned no `series_id` column,
|
|
1690
|
+
* and the first push dropped it.
|
|
1691
|
+
*/
|
|
1692
|
+
const usedRelationNames = /* @__PURE__ */ new Set();
|
|
1693
|
+
const relationNameFor = (preferred, fallback) => {
|
|
1694
|
+
const name = firstFreeKey([preferred, fallback], { has: (key) => propertyBlocks.has(key) || usedRelationNames.has(key) });
|
|
1695
|
+
usedRelationNames.add(name);
|
|
1696
|
+
return name;
|
|
1697
|
+
};
|
|
1698
|
+
const inverseFks = allFks.filter((fk) => fk.foreign_table_name === tableName && !joinTables.has(fk.table_name) && !skippedTables.has(fk.table_name));
|
|
1547
1699
|
for (const fk of inverseFks) {
|
|
1548
1700
|
const sourceTableName = fk.table_name;
|
|
1549
1701
|
const targetCollectionCamel = importCollection(sourceTableName);
|
|
1550
1702
|
relationsOutput += `
|
|
1551
1703
|
{
|
|
1552
1704
|
kind: "hasMany",
|
|
1553
|
-
relationName: ${quote(sourceTableName)},
|
|
1705
|
+
relationName: ${quote(relationNameFor(sourceTableName, `${sourceTableName}_by_${fk.column_name}`))},
|
|
1554
1706
|
target: ${relationTarget(targetCollectionCamel)},
|
|
1555
1707
|
// the ${commentText(sourceTableName)}.${commentText(fk.column_name)} FK points back here
|
|
1556
1708
|
foreignKeyOnTarget: ${quote(fk.column_name)}
|
|
@@ -1564,7 +1716,11 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1564
1716
|
const jtMeta = tablesMap.get(jt);
|
|
1565
1717
|
if (!jtMeta) continue;
|
|
1566
1718
|
const joinFks = jtMeta.fks;
|
|
1567
|
-
const
|
|
1719
|
+
const keyPosition = (fk) => {
|
|
1720
|
+
const position = jtMeta.pks.indexOf(fk.column_name);
|
|
1721
|
+
return position === -1 ? Number.MAX_SAFE_INTEGER : position;
|
|
1722
|
+
};
|
|
1723
|
+
const selfRefFks = joinFks.filter((fk) => fk.foreign_table_name === tableName).sort((a, b) => keyPosition(a) - keyPosition(b));
|
|
1568
1724
|
if (selfRefFks.length === 2) {
|
|
1569
1725
|
const thisFk = selfRefFks[0];
|
|
1570
1726
|
const otherFk = selfRefFks[1];
|
|
@@ -1572,7 +1728,7 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1572
1728
|
relationsOutput += `
|
|
1573
1729
|
{
|
|
1574
1730
|
kind: "manyToMany",
|
|
1575
|
-
relationName: ${quote(relPropName)},
|
|
1731
|
+
relationName: ${quote(relationNameFor(relPropName, `${relPropName}_${jt}`))},
|
|
1576
1732
|
target: ${relationTarget(toCollectionVarName(tableName))},
|
|
1577
1733
|
through: {
|
|
1578
1734
|
table: ${quote(jt)},
|
|
@@ -1583,7 +1739,14 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1583
1739
|
continue;
|
|
1584
1740
|
}
|
|
1585
1741
|
const otherFk = joinFks.find((fk) => fk.foreign_table_name !== tableName);
|
|
1586
|
-
|
|
1742
|
+
const leadingTable = joinFks.find((fk) => fk.column_name === jtMeta.pks[0])?.foreign_table_name;
|
|
1743
|
+
const sortsFirst = otherFk ? [tableName, otherFk.foreign_table_name].sort()[0] : tableName;
|
|
1744
|
+
const declareHere = !leadingTable || leadingTable === sortsFirst || leadingTable === tableName;
|
|
1745
|
+
if (otherFk && !declareHere) relationsOutput += `
|
|
1746
|
+
// The many-to-many with ${commentText(otherFk.foreign_table_name)} through ${commentText(jt)} is declared on
|
|
1747
|
+
// ${commentText(otherFk.foreign_table_name)} only: declaring it here too would re-key ${commentText(jt)}
|
|
1748
|
+
// from (${commentText(jtMeta.pks.join(", "))}) on the next push.`;
|
|
1749
|
+
if (otherFk && declareHere && !skippedTables.has(otherFk.foreign_table_name)) {
|
|
1587
1750
|
const targetTableName = otherFk.foreign_table_name;
|
|
1588
1751
|
const targetCollectionCamel = importCollection(targetTableName);
|
|
1589
1752
|
const thisFk = joinFks.find((fk) => fk.foreign_table_name === tableName);
|
|
@@ -1591,11 +1754,20 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1591
1754
|
relationsOutput += `
|
|
1592
1755
|
{
|
|
1593
1756
|
kind: "manyToMany",
|
|
1594
|
-
relationName: ${quote(targetTableName)},
|
|
1757
|
+
relationName: ${quote(relationNameFor(targetTableName, `${targetTableName}_via_${jt}`))},
|
|
1595
1758
|
target: ${relationTarget(targetCollectionCamel)},${throughCode}
|
|
1596
1759
|
},`;
|
|
1597
1760
|
}
|
|
1598
1761
|
}
|
|
1762
|
+
const search = reconstructSearchBlock({
|
|
1763
|
+
schema: context.metadata?.schema ?? "public",
|
|
1764
|
+
table: tableName,
|
|
1765
|
+
columns: meta.columns,
|
|
1766
|
+
comments: columnComments,
|
|
1767
|
+
keyByColumn
|
|
1768
|
+
});
|
|
1769
|
+
if (search.note) fileNotes.push(search.note);
|
|
1770
|
+
const searchBlock = search.block ?? "";
|
|
1599
1771
|
const relationsBlock = relationsOutput ? `\n relations: [${relationsOutput}\n ],` : "";
|
|
1600
1772
|
const sortedPropertiesOrder = sortPropertiesOrder(orderEntries);
|
|
1601
1773
|
for (const key of sortedPropertiesOrder) propsOutput += propertyBlocks.get(key) || "";
|
|
@@ -1622,16 +1794,18 @@ function generateCollectionFile(tableName, meta, allFks, joinTables, tablesMap,
|
|
|
1622
1794
|
const pgSchema = context.metadata?.schema;
|
|
1623
1795
|
const schemaBlock = pgSchema && pgSchema !== "public" ? `\n schema: ${quote(pgSchema)},` : "";
|
|
1624
1796
|
const classificationNote = classification && classification.role !== "entity" ? `\n// Introspected as a ${commentText(classification.role)}: ${commentText(classification.reason)}.\n` : "";
|
|
1797
|
+
for (const note of fileNotes) context.notes?.push(`${tableName}: ${note}`);
|
|
1798
|
+
const storageNote = fileNotes.length > 0 ? `\n// ⚠ Not reproduced exactly by \`rebase db push\` — read before pushing:\n${fileNotes.map((n) => `// - ${commentText(n)}`).join("\n")}\n` : "";
|
|
1625
1799
|
const collectionVarName = toCollectionVarName(tableName);
|
|
1626
1800
|
const [open, close] = builder === "annotation" ? [`const ${collectionVarName}: PostgresCollectionConfig = {`, "};"] : [`const ${collectionVarName} = defineCollection({`, "});"];
|
|
1627
1801
|
const importLines = Array.from(imports);
|
|
1628
1802
|
return `${[...importLines.filter((line) => !line.includes("from \"./")), ...importLines.filter((line) => line.includes("from \"./"))].join("\n")}
|
|
1629
|
-
${classificationNote}
|
|
1803
|
+
${classificationNote}${storageNote}
|
|
1630
1804
|
${open}
|
|
1631
1805
|
name: ${quote(collectionName)},
|
|
1632
1806
|
singularName: ${quote(singular)},
|
|
1633
1807
|
slug: ${quote(tableName)},
|
|
1634
|
-
table: ${quote(tableName)},${schemaBlock}${descriptionBlock}
|
|
1808
|
+
table: ${quote(tableName)},${schemaBlock}${descriptionBlock}${searchBlock}
|
|
1635
1809
|
properties: {${propsOutput}
|
|
1636
1810
|
},${relationsBlock}${adminBlock}
|
|
1637
1811
|
${close}
|
|
@@ -1692,6 +1866,6 @@ function safeHostFromUrl(url) {
|
|
|
1692
1866
|
return url.includes("@") ? url.split("@")[1] : "(local connection)";
|
|
1693
1867
|
}
|
|
1694
1868
|
//#endregion
|
|
1695
|
-
export {
|
|
1869
|
+
export { compositeKeySkipReason as a, getIconForTable as c, safeHostFromUrl as d, singularize as f, humanize as g, mapPgType as h, buildTablesMap as i, identifyJoinTables as l, lookupCandidates as m, COMMON_PACKAGE as n, generateCollectionFile as o, classifyTables as p, buildEnumMap as r, generateIndexContent as s, ADMIN_TYPES_PACKAGE as t, mergeIndexContent as u };
|
|
1696
1870
|
|
|
1697
|
-
//# sourceMappingURL=introspect-db-logic-
|
|
1871
|
+
//# sourceMappingURL=introspect-db-logic-kCETE8TY.js.map
|