@rebasepro/server-postgres 0.13.1-canary.g18cfeb7 → 0.13.1-canary.g1bf9303
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/PostgresBootstrapper.d.ts +26 -0
- package/dist/auth/services.d.ts +21 -0
- package/dist/{auth-users-columns-Do9mw5Y5.js → auth-users-columns-BxT6FRyu.js} +819 -68
- package/dist/auth-users-columns-BxT6FRyu.js.map +1 -0
- package/dist/{backup-service-Bww-Lg0s.js → backup-service-BH0Dzo_h.js} +2 -3
- package/dist/{backup-service-Bww-Lg0s.js.map → backup-service-BH0Dzo_h.js.map} +1 -1
- package/dist/cli-helpers.d.ts +56 -0
- package/dist/cli-output.d.ts +34 -0
- package/dist/data-transformer.d.ts +7 -2
- package/dist/data_driver-ULAyJEi9.js +193 -0
- package/dist/data_driver-ULAyJEi9.js.map +1 -0
- package/dist/ensure-collection-policies-CP5_YttS.js +124 -0
- package/dist/ensure-collection-policies-CP5_YttS.js.map +1 -0
- package/dist/{ensure-collection-tables-DSIxvLLD.js → ensure-collection-tables-DWVISfcC.js} +119 -13
- package/dist/ensure-collection-tables-DWVISfcC.js.map +1 -0
- package/dist/index.es.js +998 -600
- package/dist/index.es.js.map +1 -1
- package/dist/{rls-bootstrap-sql-Bpv3nUZo.js → rls-bootstrap-sql-69hYT8nr.js} +2 -2
- package/dist/{rls-bootstrap-sql-Bpv3nUZo.js.map → rls-bootstrap-sql-69hYT8nr.js.map} +1 -1
- package/dist/rls-enforcement-Ct9ab42o.js +425 -0
- package/dist/rls-enforcement-Ct9ab42o.js.map +1 -0
- package/dist/schema/auth-schema.d.ts +102 -0
- package/dist/schema/doctor-policy-checks.d.ts +28 -0
- package/dist/schema/doctor.d.ts +41 -25
- package/dist/schema/ensure-collection-policies.d.ts +33 -9
- package/dist/schema/ensure-collection-tables.d.ts +60 -6
- package/dist/schema/generate-drizzle-schema-logic.d.ts +9 -1
- package/dist/schema/generate-postgres-ddl-logic.d.ts +48 -0
- package/dist/schema/search-column.d.ts +248 -0
- package/dist/security/rls-enforcement.d.ts +8 -3
- package/dist/services/FetchService.d.ts +24 -0
- package/dist/services/RelationService.d.ts +30 -0
- package/dist/services/collection-helpers.d.ts +26 -0
- package/dist/services/dataService.d.ts +3 -0
- package/dist/services/realtimeService.d.ts +139 -2
- package/dist/{src-C_wvdMnl.js → src-DCdn3Val.js} +35 -3
- package/dist/src-DCdn3Val.js.map +1 -0
- package/dist/utils/drizzle-conditions.d.ts +124 -2
- package/dist/{websocket-D0TBU3ia.js → websocket-C8ZqVBiV.js} +75 -18
- package/dist/websocket-C8ZqVBiV.js.map +1 -0
- package/package.json +6 -6
- package/src/PostgresBackendDriver.ts +7 -3
- package/src/PostgresBootstrapper.ts +95 -9
- package/src/auth/ensure-tables.ts +27 -5
- package/src/auth/services.ts +82 -5
- package/src/backup/backup-cli.ts +59 -57
- package/src/cli-errors.ts +6 -6
- package/src/cli-helpers.ts +110 -4
- package/src/cli-output.ts +43 -0
- package/src/cli.ts +210 -145
- package/src/collections/buildRegistry.ts +3 -1
- package/src/data-transformer.ts +107 -14
- package/src/history/ensure-history-table.ts +2 -2
- package/src/schema/auth-schema.ts +17 -1
- package/src/schema/doctor-cli.ts +14 -65
- package/src/schema/doctor-policy-checks.ts +105 -0
- package/src/schema/doctor.ts +149 -72
- package/src/schema/ensure-collection-policies.ts +99 -6
- package/src/schema/ensure-collection-tables.ts +286 -13
- package/src/schema/generate-drizzle-schema-logic.ts +126 -42
- package/src/schema/generate-drizzle-schema.ts +11 -10
- package/src/schema/generate-postgres-ddl-logic.ts +204 -10
- package/src/schema/generate-postgres-ddl.ts +38 -14
- package/src/schema/introspect-db-logic.ts +65 -33
- package/src/schema/introspect-db.ts +24 -24
- package/src/schema/search-column.ts +643 -0
- package/src/security/rls-enforcement.ts +9 -4
- package/src/services/FetchService.ts +229 -15
- package/src/services/PersistService.ts +24 -1
- package/src/services/RelationService.ts +119 -69
- package/src/services/cdc/trigger-cdc.ts +5 -1
- package/src/services/channel-history.ts +9 -3
- package/src/services/channel-presence.ts +10 -3
- package/src/services/collection-helpers.ts +54 -1
- package/src/services/dataService.ts +3 -0
- package/src/services/pg-notify-listener.ts +1 -1
- package/src/services/realtimeService.ts +347 -86
- package/src/utils/drizzle-conditions.ts +365 -23
- package/src/utils/pg-error-utils.ts +8 -3
- package/src/websocket.ts +113 -16
- package/dist/auth-users-columns-Do9mw5Y5.js.map +0 -1
- package/dist/ensure-collection-policies-DMUdRQdM.js +0 -57
- package/dist/ensure-collection-policies-DMUdRQdM.js.map +0 -1
- package/dist/ensure-collection-tables-DSIxvLLD.js.map +0 -1
- package/dist/policy-CPkCqVTz.js +0 -105
- package/dist/policy-CPkCqVTz.js.map +0 -1
- package/dist/src-C_wvdMnl.js.map +0 -1
- package/dist/websocket-D0TBU3ia.js.map +0 -1
|
@@ -1,7 +1,20 @@
|
|
|
1
1
|
import { CollectionConfig, NumberProperty, Property, ResolvedRelation, RelationProperty, SecurityOperation, SecurityRule, StringProperty, isPostgresCollectionConfig, DateProperty, ArrayProperty, MapProperty, ReferenceProperty, VectorProperty, BinaryProperty, isManyToMany, type ResolvedManyToMany, type ResolvedBelongsTo } from "@rebasepro/types";
|
|
2
2
|
import { getEnumVarName, getTableName, resolveCollectionRelations, findRelation, securityRuleToConditions, policyToPostgres, getEffectiveSecurityRules, getInjectedSecurityRules, resolveJunctionSpecs, getJunctionSecurityRules, getJunctionCollectionConfig, resolveStringColumnLength, relationalCollections } from "@rebasepro/common";
|
|
3
|
-
import { toSnakeCase, getPolicyNamesForRule, generateForeignKeyName, legacyForeignKeyName } from "@rebasepro/utils";
|
|
3
|
+
import { toSnakeCase, getPolicyNamesForRule, generateForeignKeyName, legacyForeignKeyName, toPostgresIdentifier } from "@rebasepro/utils";
|
|
4
4
|
import { AUTH_USERS_COLUMNS, authUsersColumnDefinition, authUsersColumnSql, isAuthCollection } from "./auth-users-columns";
|
|
5
|
+
import {
|
|
6
|
+
buildSearchColumnSpec,
|
|
7
|
+
searchColumnDefinition,
|
|
8
|
+
fuzzyColumnDefinition,
|
|
9
|
+
searchIndexStatements,
|
|
10
|
+
searchHelperFunctions,
|
|
11
|
+
searchExtensionStatements,
|
|
12
|
+
searchColumnNames,
|
|
13
|
+
searchColumnStamps,
|
|
14
|
+
searchStampGuards,
|
|
15
|
+
searchIndexNames,
|
|
16
|
+
type SearchColumnSpec
|
|
17
|
+
} from "./search-column";
|
|
5
18
|
import { REBASE_SCHEMA } from "@rebasepro/types";
|
|
6
19
|
|
|
7
20
|
// --- Helper Functions ---
|
|
@@ -182,6 +195,11 @@ export const getSqlColumnType = (propName: string, prop: Property, collection: C
|
|
|
182
195
|
const mapProp = prop as MapProperty;
|
|
183
196
|
return mapProp.columnType === "json" ? "JSON" : "JSONB";
|
|
184
197
|
}
|
|
198
|
+
// `{ latitude, longitude }` — a document, like `map`. It used to fall to
|
|
199
|
+
// the `TEXT` default below while the Drizzle generator emitted no column
|
|
200
|
+
// at all, which is the divergence that made the type unpersistable.
|
|
201
|
+
case "geopoint":
|
|
202
|
+
return "JSONB";
|
|
185
203
|
case "array": {
|
|
186
204
|
const arrayProp = prop as ArrayProperty;
|
|
187
205
|
let colType = arrayProp.columnType;
|
|
@@ -233,13 +251,146 @@ export const getSqlColumnType = (propName: string, prop: Property, collection: C
|
|
|
233
251
|
return pkProp.type === "number" ? "INTEGER" : (pkProp.isUuid ? "UUID" : "TEXT");
|
|
234
252
|
}
|
|
235
253
|
default:
|
|
236
|
-
|
|
254
|
+
// A silent `TEXT` here is how the two generators drifted apart: the
|
|
255
|
+
// database got a column for `geopoint` and the Drizzle table did
|
|
256
|
+
// not, so the type looked supported and persisted nothing. Every
|
|
257
|
+
// member of `DataType` is handled above; anything else is a
|
|
258
|
+
// generator that has not been taught the type yet, and it should
|
|
259
|
+
// say so rather than invent a column.
|
|
260
|
+
throw new Error(
|
|
261
|
+
`No Postgres column type for property '${propName}' of type ` +
|
|
262
|
+
`'${(prop as Property).type}' in collection '${collection.slug}'. ` +
|
|
263
|
+
"Add a case to `getSqlColumnType` (and to `getDrizzleColumn`, which must agree)."
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Everything a `search` block needs, as a file Rebase applies itself.
|
|
270
|
+
*
|
|
271
|
+
* Search is the one part of the schema Atlas does not own. Two independent
|
|
272
|
+
* reasons, and either alone would be enough:
|
|
273
|
+
*
|
|
274
|
+
* 1. Its free tier refuses to *parse* a desired-state file that so much as
|
|
275
|
+
* contains a function — "functions and procedures are available to
|
|
276
|
+
* logged-in users only". A generated `tsvector` column cannot avoid one:
|
|
277
|
+
* `unaccent` is STABLE and jsonb flattening needs a set-returning function,
|
|
278
|
+
* so both have to be wrapped in an IMMUTABLE helper to be legal in a
|
|
279
|
+
* generated column at all.
|
|
280
|
+
* 2. Even with the file accepted, Atlas *wipes* the dev database it diffs
|
|
281
|
+
* against, so a helper seeded there beforehand is gone by the time the plan
|
|
282
|
+
* is analysed. There is no hook to reinstate it.
|
|
283
|
+
*
|
|
284
|
+
* So the column, its index and its helpers are excluded from Atlas's view
|
|
285
|
+
* (`searchExcludePatterns`) and applied from here — the same arrangement the
|
|
286
|
+
* RLS policies already use, and for the same underlying reason.
|
|
287
|
+
*
|
|
288
|
+
* Ordered as it must run: extensions, then helpers, then the column whose
|
|
289
|
+
* expression calls them, then the index over that column. Every statement is
|
|
290
|
+
* `IF NOT EXISTS` / `OR REPLACE`, because this is replayed on every push and
|
|
291
|
+
* appended to migrations that run against databases at any stage of their
|
|
292
|
+
* life. Empty when nothing opted in — the caller writes no file then.
|
|
293
|
+
*
|
|
294
|
+
* The leading half — extensions and helpers, without the table-shaped
|
|
295
|
+
* statements — is available on its own as {@link searchPrerequisiteStatements},
|
|
296
|
+
* for the dev database Atlas analyses plans against. That database has none of
|
|
297
|
+
* the project's tables, so it wants the functions and nothing else.
|
|
298
|
+
*/
|
|
299
|
+
export const searchPrerequisiteStatements = (allCollections: CollectionConfig[]): string[] => {
|
|
300
|
+
const specs = relationalCollections(allCollections)
|
|
301
|
+
.map(c => buildSearchColumnSpec(c))
|
|
302
|
+
.filter((s): s is SearchColumnSpec => s !== undefined);
|
|
303
|
+
if (specs.length === 0) return [];
|
|
304
|
+
return [
|
|
305
|
+
...new Set(specs.flatMap(searchExtensionStatements)),
|
|
306
|
+
...new Set(specs.flatMap(searchHelperFunctions))
|
|
307
|
+
];
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
export const generatePostgresSearchDdl = (allCollections: CollectionConfig[]): string => {
|
|
311
|
+
const collections = relationalCollections(allCollections);
|
|
312
|
+
const specs = collections
|
|
313
|
+
.map(c => buildSearchColumnSpec(c))
|
|
314
|
+
.filter((s): s is SearchColumnSpec => s !== undefined);
|
|
315
|
+
if (specs.length === 0) return "";
|
|
316
|
+
|
|
317
|
+
const extensions = Array.from(new Set(specs.flatMap(searchExtensionStatements)));
|
|
318
|
+
const helpers = Array.from(new Set(specs.flatMap(searchHelperFunctions)));
|
|
319
|
+
|
|
320
|
+
let ddl = "-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\n";
|
|
321
|
+
ddl += "--\n";
|
|
322
|
+
ddl += "-- Full-text search for the collections declaring a `search` block.\n";
|
|
323
|
+
ddl += "-- Applied by Rebase, not by Atlas — see generatePostgresSearchDdl.\n\n";
|
|
324
|
+
|
|
325
|
+
extensions.forEach(s => { ddl += `${s}\n`; });
|
|
326
|
+
if (extensions.length > 0) ddl += "\n";
|
|
327
|
+
helpers.forEach(s => { ddl += `${s}\n\n`; });
|
|
328
|
+
|
|
329
|
+
for (const collection of collections) {
|
|
330
|
+
const spec = buildSearchColumnSpec(collection);
|
|
331
|
+
if (!spec) continue;
|
|
332
|
+
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
333
|
+
const table = `"${schema}"."${getTableName(collection)}"`;
|
|
334
|
+
|
|
335
|
+
// ADD COLUMN IF NOT EXISTS rather than the inline definition the
|
|
336
|
+
// CREATE TABLE would use: by the time this runs the table exists,
|
|
337
|
+
// whether Atlas just created it or it has been live for a year.
|
|
338
|
+
// Refuse before altering anything if the column in the database was
|
|
339
|
+
// generated from a different `search` block: `ADD COLUMN IF NOT EXISTS`
|
|
340
|
+
// is a no-op against an existing column, so without this the file would
|
|
341
|
+
// report success and leave the old expression in place — and then stamp
|
|
342
|
+
// it as current.
|
|
343
|
+
searchStampGuards(spec).forEach(s => { ddl += `${s}\n`; });
|
|
344
|
+
ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${searchColumnDefinition(spec)};\n`;
|
|
345
|
+
const fuzzyDef = fuzzyColumnDefinition(spec);
|
|
346
|
+
if (fuzzyDef) ddl += `ALTER TABLE ${table} ADD COLUMN IF NOT EXISTS ${fuzzyDef};\n`;
|
|
347
|
+
// The fingerprint of the expression each column was built from — the
|
|
348
|
+
// only record of *which* block a generated column came from, and what
|
|
349
|
+
// the guard above and the boot-time ensure both compare against.
|
|
350
|
+
searchColumnStamps(spec).forEach(s => { ddl += `${s.sql}\n`; });
|
|
351
|
+
searchIndexStatements(spec).forEach(s => { ddl += `${s}\n`; });
|
|
352
|
+
ddl += "\n";
|
|
237
353
|
}
|
|
354
|
+
|
|
355
|
+
return ddl;
|
|
356
|
+
};
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Glob patterns telling Atlas to leave the search column and its index alone.
|
|
360
|
+
*
|
|
361
|
+
* Without these, a desired state that omits search reads to Atlas as an
|
|
362
|
+
* instruction to drop the column — taking the index and the whole search
|
|
363
|
+
* feature with it on the next push.
|
|
364
|
+
*
|
|
365
|
+
* Fully qualified, `schema.table.object`, matching the include list. The
|
|
366
|
+
* two-part form is what Atlas wants when the connection URL scopes it to one
|
|
367
|
+
* schema and is *silently ignored* otherwise: it reads `posts.search_vector`
|
|
368
|
+
* as a table named `search_vector` in a schema named `posts`, matches nothing,
|
|
369
|
+
* and reports no error for the pattern that never fired.
|
|
370
|
+
*/
|
|
371
|
+
export const searchExcludePatterns = (allCollections: CollectionConfig[]): string[] => {
|
|
372
|
+
const patterns: string[] = [];
|
|
373
|
+
for (const collection of relationalCollections(allCollections)) {
|
|
374
|
+
const spec = buildSearchColumnSpec(collection);
|
|
375
|
+
if (!spec) continue;
|
|
376
|
+
const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
377
|
+
const table = getTableName(collection);
|
|
378
|
+
for (const name of searchColumnNames(collection)) {
|
|
379
|
+
patterns.push(`${schema}.${table}.${name}`);
|
|
380
|
+
}
|
|
381
|
+
for (const index of searchIndexNames(spec)) {
|
|
382
|
+
patterns.push(`${schema}.${table}.${index}`);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
return patterns;
|
|
238
386
|
};
|
|
239
387
|
|
|
240
388
|
export const generatePostgresDdl = async (
|
|
241
389
|
allCollections: CollectionConfig[],
|
|
242
|
-
options: { includePolicies?: boolean } = {
|
|
390
|
+
options: { includePolicies?: boolean; includeSearch?: boolean } = {
|
|
391
|
+
includePolicies: true,
|
|
392
|
+
includeSearch: true
|
|
393
|
+
}
|
|
243
394
|
): Promise<string> => {
|
|
244
395
|
// Only the collections this engine stores. See `relationalCollections`.
|
|
245
396
|
const collections = relationalCollections(allCollections);
|
|
@@ -263,6 +414,32 @@ export const generatePostgresDdl = async (
|
|
|
263
414
|
});
|
|
264
415
|
if (uniqueSchemas.length > 0) ddl += "\n";
|
|
265
416
|
|
|
417
|
+
// 1b. Search support, for collections that opted in.
|
|
418
|
+
//
|
|
419
|
+
// Extensions and helper functions come before every CREATE TABLE because a
|
|
420
|
+
// generated column's expression is resolved at creation time: a table whose
|
|
421
|
+
// search column calls `rebase_search_text` cannot be created before that
|
|
422
|
+
// function exists. Both are `IF NOT EXISTS` / `OR REPLACE`, so a file
|
|
423
|
+
// replayed against a live database is a no-op here.
|
|
424
|
+
const searchSpecs = collections
|
|
425
|
+
.map(c => buildSearchColumnSpec(c))
|
|
426
|
+
.filter((s): s is SearchColumnSpec => s !== undefined);
|
|
427
|
+
|
|
428
|
+
if (searchSpecs.length > 0) {
|
|
429
|
+
if (options.includeSearch === false) {
|
|
430
|
+
// Everything search-related lives in `search.sql` — see
|
|
431
|
+
// `generatePostgresSearchDdl` for why Atlas is not shown any of it.
|
|
432
|
+
ddl += "-- Full-text search support lives in `search.sql`, applied separately.\n\n";
|
|
433
|
+
} else {
|
|
434
|
+
const extensions = Array.from(new Set(searchSpecs.flatMap(searchExtensionStatements)));
|
|
435
|
+
const helpers = Array.from(new Set(searchSpecs.flatMap(searchHelperFunctions)));
|
|
436
|
+
ddl += "-- Full-text search support (collections declaring a `search` block)\n";
|
|
437
|
+
extensions.forEach(s => { ddl += `${s}\n`; });
|
|
438
|
+
if (extensions.length > 0) ddl += "\n";
|
|
439
|
+
helpers.forEach(s => { ddl += `${s}\n\n`; });
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
266
443
|
// 2. Generate Enums
|
|
267
444
|
//
|
|
268
445
|
// The enum type name is derived from table + column, so two collections
|
|
@@ -330,6 +507,9 @@ export const generatePostgresDdl = async (
|
|
|
330
507
|
|
|
331
508
|
// 3. Generate tables
|
|
332
509
|
const fkStatements: string[] = [];
|
|
510
|
+
// Indexes follow the tables for the same reason the FK constraints do: the
|
|
511
|
+
// table has to exist first.
|
|
512
|
+
const indexStatements: string[] = [];
|
|
333
513
|
// Policies are emitted after every CREATE TABLE, like the FK constraints:
|
|
334
514
|
// a policy may reference other tables (a junction's derived policies always
|
|
335
515
|
// reference both endpoints; `policy.existsIn` references a join table), and
|
|
@@ -526,6 +706,19 @@ export const generatePostgresDdl = async (
|
|
|
526
706
|
}
|
|
527
707
|
}
|
|
528
708
|
|
|
709
|
+
// ── The opt-in search column ─────────────────────────────────────
|
|
710
|
+
// Last, so it reads as what it is: derived from the columns above
|
|
711
|
+
// it. Postgres recomputes it on every write of a source column and
|
|
712
|
+
// rejects any attempt to write it directly, which is the property
|
|
713
|
+
// that makes it impossible for the index to drift from the row.
|
|
714
|
+
const searchSpec = options.includeSearch === false ? undefined : buildSearchColumnSpec(collection);
|
|
715
|
+
if (searchSpec) {
|
|
716
|
+
columns.push(` ${searchColumnDefinition(searchSpec)}`);
|
|
717
|
+
const fuzzyDef = fuzzyColumnDefinition(searchSpec);
|
|
718
|
+
if (fuzzyDef) columns.push(` ${fuzzyDef}`);
|
|
719
|
+
indexStatements.push(...searchIndexStatements(searchSpec));
|
|
720
|
+
}
|
|
721
|
+
|
|
529
722
|
// Backwards compatibility: add default id primary key if missing
|
|
530
723
|
const hasPk = columns.some(c => c.includes("PRIMARY KEY"));
|
|
531
724
|
if (!hasPk) {
|
|
@@ -559,6 +752,11 @@ export const generatePostgresDdl = async (
|
|
|
559
752
|
ddl += fkStatements.join("\n") + "\n\n";
|
|
560
753
|
}
|
|
561
754
|
|
|
755
|
+
if (indexStatements.length > 0) {
|
|
756
|
+
ddl += "-- Indexes\n";
|
|
757
|
+
ddl += indexStatements.join("\n") + "\n\n";
|
|
758
|
+
}
|
|
759
|
+
|
|
562
760
|
if (policyStatements.length > 0) {
|
|
563
761
|
ddl += "-- Row Level Security Policies\n";
|
|
564
762
|
ddl += policyStatements.join("");
|
|
@@ -642,13 +840,9 @@ const bareTableName = (name: string): string => (name.includes(".") ? name.split
|
|
|
642
840
|
* Byte length, not string length: NAMEDATALEN is 64 bytes, and a multi-byte
|
|
643
841
|
* character straddling the boundary would be cut mid-sequence by `slice(0, 63)`.
|
|
644
842
|
*/
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
// `toString` on a slice that ends mid-character yields U+FFFD; dropping it
|
|
649
|
-
// lands on the last whole character that fits, which is what Postgres does.
|
|
650
|
-
return bytes.subarray(0, 63).toString("utf8").replace(/�+$/, "");
|
|
651
|
-
};
|
|
843
|
+
// Moved to `@rebasepro/utils` so the search-column builder derives index names
|
|
844
|
+
// under the same 63-byte rule this file derives constraint names under. Two
|
|
845
|
+
// copies of a truncation rule is two rules the moment one of them is edited.
|
|
652
846
|
|
|
653
847
|
const foreignKeyPlan = (
|
|
654
848
|
args: Omit<ForeignKeyPlan, "constraintName" | "sql"> & { onDelete: string; onUpdate?: string }
|
|
@@ -3,15 +3,20 @@ import * as fs from "fs";
|
|
|
3
3
|
import path from "path";
|
|
4
4
|
import { pathToFileURL } from "url";
|
|
5
5
|
import chokidar from "chokidar";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
generatePostgresDdl,
|
|
8
|
+
generatePostgresPoliciesDdl,
|
|
9
|
+
generatePostgresSearchDdl
|
|
10
|
+
} from "./generate-postgres-ddl-logic";
|
|
7
11
|
import { CollectionConfig } from "@rebasepro/types";
|
|
8
|
-
import {
|
|
12
|
+
import { loadCollectionsFromDirectory } from "@rebasepro/server";
|
|
13
|
+
import { out, outError } from "../cli-output";
|
|
9
14
|
|
|
10
15
|
|
|
11
16
|
const runGeneration = async (collectionsFilePath?: string, outputPath?: string) => {
|
|
12
17
|
try {
|
|
13
18
|
if (!collectionsFilePath) {
|
|
14
|
-
|
|
19
|
+
outError("Error: No collections file path provided. Skipping schema generation.");
|
|
15
20
|
return;
|
|
16
21
|
}
|
|
17
22
|
|
|
@@ -29,27 +34,46 @@ const runGeneration = async (collectionsFilePath?: string, outputPath?: string)
|
|
|
29
34
|
// Sort collections by slug alphabetically to ensure deterministic DDL generation
|
|
30
35
|
collections.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
31
36
|
|
|
32
|
-
|
|
37
|
+
// `schema.sql` is Atlas's desired state, and it carries neither the RLS
|
|
38
|
+
// policies nor the search apparatus: Atlas manages neither, and in the
|
|
39
|
+
// search case cannot. Both are written beside it and applied by the CLI
|
|
40
|
+
// in their own right.
|
|
41
|
+
const ddlContent = await generatePostgresDdl(collections, {
|
|
42
|
+
includePolicies: false,
|
|
43
|
+
includeSearch: false
|
|
44
|
+
});
|
|
33
45
|
const policiesContent = generatePostgresPoliciesDdl(collections);
|
|
46
|
+
const searchContent = generatePostgresSearchDdl(collections);
|
|
34
47
|
|
|
35
48
|
if (outputPath) {
|
|
36
49
|
const outputDir = path.dirname(outputPath);
|
|
37
50
|
await fsPromises.mkdir(outputDir, { recursive: true });
|
|
38
51
|
await fsPromises.writeFile(outputPath, ddlContent);
|
|
39
|
-
|
|
52
|
+
out(`✅ PostgreSQL DDL generated successfully at ${outputPath}`);
|
|
40
53
|
|
|
41
54
|
const policiesPath = path.join(outputDir, "policies.sql");
|
|
42
55
|
await fsPromises.writeFile(policiesPath, policiesContent);
|
|
43
|
-
|
|
56
|
+
out(`✅ PostgreSQL Policies DDL generated successfully at ${policiesPath}`);
|
|
57
|
+
|
|
58
|
+
// Removed when the last `search` block goes: the CLI applies this
|
|
59
|
+
// file whenever it exists, and a stale one would keep re-creating
|
|
60
|
+
// functions for collections that no longer want them.
|
|
61
|
+
const searchPath = path.join(outputDir, "search.sql");
|
|
62
|
+
if (searchContent) {
|
|
63
|
+
await fsPromises.writeFile(searchPath, searchContent);
|
|
64
|
+
out(`✅ PostgreSQL search DDL generated successfully at ${searchPath}`);
|
|
65
|
+
} else if (fs.existsSync(searchPath)) {
|
|
66
|
+
await fsPromises.rm(searchPath);
|
|
67
|
+
}
|
|
44
68
|
} else {
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
69
|
+
out("✅ PostgreSQL DDL generated successfully.");
|
|
70
|
+
out(String(ddlContent));
|
|
71
|
+
out("\n✅ PostgreSQL Policies DDL generated successfully.");
|
|
72
|
+
out(String(policiesContent));
|
|
49
73
|
}
|
|
50
74
|
|
|
51
75
|
} catch (error) {
|
|
52
|
-
|
|
76
|
+
outError(`Error generating DDL schema: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`);
|
|
53
77
|
}
|
|
54
78
|
};
|
|
55
79
|
|
|
@@ -63,7 +87,7 @@ const main = () => {
|
|
|
63
87
|
const watch = process.argv.includes("--watch");
|
|
64
88
|
|
|
65
89
|
if (!collectionsFilePath) {
|
|
66
|
-
|
|
90
|
+
out("Usage: ts-node generate-postgres-ddl.ts <path-to-collections-file> [--output <path-to-output-file>] [--watch]");
|
|
67
91
|
return;
|
|
68
92
|
}
|
|
69
93
|
|
|
@@ -71,14 +95,14 @@ const main = () => {
|
|
|
71
95
|
const resolvedOutputPath = outputPath ? path.resolve(process.cwd(), outputPath) : undefined;
|
|
72
96
|
|
|
73
97
|
if (watch) {
|
|
74
|
-
|
|
98
|
+
out(`Watching for changes in ${resolvedPath}...`);
|
|
75
99
|
const watcher = chokidar.watch(resolvedPath, {
|
|
76
100
|
persistent: true,
|
|
77
101
|
ignoreInitial: false
|
|
78
102
|
});
|
|
79
103
|
|
|
80
104
|
watcher.on("all", (event, filePath) => {
|
|
81
|
-
|
|
105
|
+
out(`[${event}] ${filePath}. Regenerating DDL schema...`);
|
|
82
106
|
runGeneration(resolvedPath, resolvedOutputPath);
|
|
83
107
|
});
|
|
84
108
|
} else {
|
|
@@ -218,7 +218,14 @@ export function singularize(word: string): string {
|
|
|
218
218
|
* e.g. "company_token" -> "companyTokenCollection"
|
|
219
219
|
*/
|
|
220
220
|
export function toCollectionVarName(tableName: string): string {
|
|
221
|
-
|
|
221
|
+
const camel = tableName.replace(/_([a-z])/g, (_g, letter: string) => letter.toUpperCase()) + "Collection";
|
|
222
|
+
// Only reshapes names that are not identifiers already, so every table that
|
|
223
|
+
// generated a working file keeps the exact variable name it had. A table
|
|
224
|
+
// called `2024 archive` used to emit `const 2024 archiveCollection`, which
|
|
225
|
+
// is three syntax errors rather than a declaration.
|
|
226
|
+
if (JS_IDENTIFIER.test(camel)) return camel;
|
|
227
|
+
const sanitized = camel.replace(/[^A-Za-z0-9_$]/g, "_");
|
|
228
|
+
return /^[0-9]/.test(sanitized) ? `_${sanitized}` : sanitized;
|
|
222
229
|
}
|
|
223
230
|
|
|
224
231
|
export function getIconForTable(tableName: string): string {
|
|
@@ -616,6 +623,31 @@ function quote(value: string): string {
|
|
|
616
623
|
return JSON.stringify(value);
|
|
617
624
|
}
|
|
618
625
|
|
|
626
|
+
const JS_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* An object key for the generated file: verbatim when the name is a JavaScript
|
|
630
|
+
* identifier, quoted otherwise.
|
|
631
|
+
*
|
|
632
|
+
* Postgres constrains an identifier only by quoting, so `order`, `full name`
|
|
633
|
+
* and `2fa_enabled` are all ordinary column names — and all three produced a
|
|
634
|
+
* file that did not parse when written as a bare key.
|
|
635
|
+
*/
|
|
636
|
+
function propKey(name: string): string {
|
|
637
|
+
return JS_IDENTIFIER.test(name) ? name : quote(name);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Text safe to put after `//`.
|
|
642
|
+
*
|
|
643
|
+
* A table comment or a classification reason is free text out of the database.
|
|
644
|
+
* A newline in one ended the comment and let the rest of the value continue as
|
|
645
|
+
* code.
|
|
646
|
+
*/
|
|
647
|
+
function commentText(value: string): string {
|
|
648
|
+
return value.replace(/\s*[\r\n]+\s*/g, " ");
|
|
649
|
+
}
|
|
650
|
+
|
|
619
651
|
/**
|
|
620
652
|
* The first candidate key not already used, or a numbered fallback.
|
|
621
653
|
*
|
|
@@ -688,7 +720,7 @@ export function generateCollectionFile(
|
|
|
688
720
|
*/
|
|
689
721
|
const importCollection = (otherTable: string): string => {
|
|
690
722
|
const varName = toCollectionVarName(otherTable);
|
|
691
|
-
if (otherTable !== tableName) imports.add(`import ${varName} from
|
|
723
|
+
if (otherTable !== tableName) imports.add(`import ${varName} from ${quote(`./${otherTable}`)};`);
|
|
692
724
|
return varName;
|
|
693
725
|
};
|
|
694
726
|
|
|
@@ -737,7 +769,7 @@ export function generateCollectionFile(
|
|
|
737
769
|
// Enum values — generate real enum from the PG enum
|
|
738
770
|
if (isEnumColumn && colEnumValues) {
|
|
739
771
|
const enumEntries = colEnumValues
|
|
740
|
-
.map((v) => `{ id:
|
|
772
|
+
.map((v) => `{ id: ${quote(v)}, label: ${quote(humanize(v))} }`)
|
|
741
773
|
.join(", ");
|
|
742
774
|
extra += `\n enum: [${enumEntries}],`;
|
|
743
775
|
} else if (columnChecks?.enumValues && !inferenceExtra.includes("enum:") && propType === "string") {
|
|
@@ -776,9 +808,9 @@ export function generateCollectionFile(
|
|
|
776
808
|
else if (innerType === "boolean") colType = "boolean[]";
|
|
777
809
|
}
|
|
778
810
|
if (colType) {
|
|
779
|
-
extra += `\n columnType:
|
|
811
|
+
extra += `\n columnType: ${quote(colType)},`;
|
|
780
812
|
}
|
|
781
|
-
extra += `\n of: { name:
|
|
813
|
+
extra += `\n of: { name: ${quote(`${humanize(col.column_name)} Item`)}, type: ${quote(innerType)} },`;
|
|
782
814
|
} else if (finalPropType === "map" && !inferenceExtra.includes("keyValue: true") && !inferenceExtra.includes("properties: {")) {
|
|
783
815
|
extra += "\n keyValue: true,";
|
|
784
816
|
}
|
|
@@ -789,7 +821,7 @@ export function generateCollectionFile(
|
|
|
789
821
|
const isMedia = colNameLower.includes("image") || colNameLower.includes("avatar") || colNameLower.includes("photo") || colNameLower.includes("logo") || colNameLower.includes("cover");
|
|
790
822
|
|
|
791
823
|
if (isMedia) {
|
|
792
|
-
extra += `\n storage: {\n storagePath:
|
|
824
|
+
extra += `\n storage: {\n storagePath: ${quote(`${tableName}/${col.column_name}`)}\n },`;
|
|
793
825
|
} else if (isUrl) {
|
|
794
826
|
extra += "\n url: true,";
|
|
795
827
|
} else if (colNameLower === "description" || colNameLower === "summary" || colNameLower === "excerpt") {
|
|
@@ -872,7 +904,7 @@ export function generateCollectionFile(
|
|
|
872
904
|
// Identify IDs (unless already inferred as UUID/CUID by inferenceEngine)
|
|
873
905
|
if (meta.pks.includes(col.column_name)) {
|
|
874
906
|
if (isCompositePk) {
|
|
875
|
-
extra += `\n // Part of composite primary key (${meta.pks.join(", ")})`;
|
|
907
|
+
extra += `\n // Part of composite primary key (${commentText(meta.pks.join(", "))})`;
|
|
876
908
|
} else if (finalPropType === "number" && !inferenceExtra.includes("isId:")) {
|
|
877
909
|
extra += "\n isId: \"increment\",";
|
|
878
910
|
} else if (col.data_type.toLowerCase() === "uuid" && !inferenceExtra.includes("isId:")) {
|
|
@@ -913,10 +945,10 @@ export function generateCollectionFile(
|
|
|
913
945
|
});
|
|
914
946
|
|
|
915
947
|
propertyBlocks.set(col.column_name, `
|
|
916
|
-
${col.column_name}: {
|
|
917
|
-
name:
|
|
918
|
-
columnName:
|
|
919
|
-
type:
|
|
948
|
+
${propKey(col.column_name)}: {
|
|
949
|
+
name: ${quote(humanName)},
|
|
950
|
+
columnName: ${quote(col.column_name)},
|
|
951
|
+
type: ${quote(finalPropType)},${extra}
|
|
920
952
|
},`);
|
|
921
953
|
}
|
|
922
954
|
|
|
@@ -962,14 +994,14 @@ export function generateCollectionFile(
|
|
|
962
994
|
const relHumanName = humanize(relName);
|
|
963
995
|
|
|
964
996
|
propertyBlocks.set(relName, `
|
|
965
|
-
${relName}: {
|
|
966
|
-
name:
|
|
997
|
+
${propKey(relName)}: {
|
|
998
|
+
name: ${quote(relHumanName)},
|
|
967
999
|
type: "relation",
|
|
968
|
-
// mapped from foreign key: ${fk.column_name} -> ${targetTableName}(${fk.foreign_column_name})
|
|
1000
|
+
// mapped from foreign key: ${commentText(fk.column_name)} -> ${commentText(targetTableName)}(${commentText(fk.foreign_column_name)})
|
|
969
1001
|
relation: {
|
|
970
1002
|
kind: "belongsTo",
|
|
971
1003
|
target: () => ${targetCollectionCamel},
|
|
972
|
-
localKey:
|
|
1004
|
+
localKey: ${quote(fk.column_name)}
|
|
973
1005
|
}
|
|
974
1006
|
},`);
|
|
975
1007
|
}
|
|
@@ -986,10 +1018,10 @@ export function generateCollectionFile(
|
|
|
986
1018
|
relationsOutput += `
|
|
987
1019
|
{
|
|
988
1020
|
kind: "hasMany",
|
|
989
|
-
relationName:
|
|
1021
|
+
relationName: ${quote(sourceTableName)},
|
|
990
1022
|
target: () => ${targetCollectionCamel},
|
|
991
|
-
// the ${sourceTableName}.${fk.column_name} FK points back here
|
|
992
|
-
foreignKeyOnTarget:
|
|
1023
|
+
// the ${commentText(sourceTableName)}.${commentText(fk.column_name)} FK points back here
|
|
1024
|
+
foreignKeyOnTarget: ${quote(fk.column_name)}
|
|
993
1025
|
},`;
|
|
994
1026
|
}
|
|
995
1027
|
|
|
@@ -1018,12 +1050,12 @@ export function generateCollectionFile(
|
|
|
1018
1050
|
relationsOutput += `
|
|
1019
1051
|
{
|
|
1020
1052
|
kind: "manyToMany",
|
|
1021
|
-
relationName:
|
|
1022
|
-
target: () => ${tableName}
|
|
1053
|
+
relationName: ${quote(relPropName)},
|
|
1054
|
+
target: () => ${toCollectionVarName(tableName)},
|
|
1023
1055
|
through: {
|
|
1024
|
-
table:
|
|
1025
|
-
sourceColumn:
|
|
1026
|
-
targetColumn:
|
|
1056
|
+
table: ${quote(jt)},
|
|
1057
|
+
sourceColumn: ${quote(thisFk.column_name)},
|
|
1058
|
+
targetColumn: ${quote(otherFk.column_name)}
|
|
1027
1059
|
}
|
|
1028
1060
|
},`;
|
|
1029
1061
|
continue;
|
|
@@ -1045,13 +1077,13 @@ export function generateCollectionFile(
|
|
|
1045
1077
|
const thisFk = joinFks.find((fk) => fk.foreign_table_name === tableName);
|
|
1046
1078
|
|
|
1047
1079
|
const throughCode = thisFk
|
|
1048
|
-
? `\n through: {\n table:
|
|
1080
|
+
? `\n through: {\n table: ${quote(jt)},\n sourceColumn: ${quote(thisFk.column_name)},\n targetColumn: ${quote(otherFk.column_name)}\n }`
|
|
1049
1081
|
: "";
|
|
1050
1082
|
|
|
1051
1083
|
relationsOutput += `
|
|
1052
1084
|
{
|
|
1053
1085
|
kind: "manyToMany",
|
|
1054
|
-
relationName:
|
|
1086
|
+
relationName: ${quote(targetTableName)},
|
|
1055
1087
|
target: () => ${targetCollectionCamel},${throughCode}
|
|
1056
1088
|
},`;
|
|
1057
1089
|
}
|
|
@@ -1071,7 +1103,7 @@ export function generateCollectionFile(
|
|
|
1071
1103
|
// config, where they have not belonged since the admin block was split out:
|
|
1072
1104
|
// `PostgresCollectionConfig` does not declare them, so every generated file
|
|
1073
1105
|
// was a type error, and the panel — which reads the block — never saw them.
|
|
1074
|
-
const adminEntries: string[] = [`icon:
|
|
1106
|
+
const adminEntries: string[] = [`icon: ${quote(icon)}`];
|
|
1075
1107
|
|
|
1076
1108
|
if (classification) {
|
|
1077
1109
|
const derivedFacts = context.metadata
|
|
@@ -1116,17 +1148,17 @@ export function generateCollectionFile(
|
|
|
1116
1148
|
// decision the reader may disagree with. Naming the evidence tells them
|
|
1117
1149
|
// which line to delete when they do.
|
|
1118
1150
|
const classificationNote = classification && classification.role !== "entity"
|
|
1119
|
-
? `\n// Introspected as a ${classification.role}: ${classification.reason}.\n`
|
|
1151
|
+
? `\n// Introspected as a ${commentText(classification.role)}: ${commentText(classification.reason)}.\n`
|
|
1120
1152
|
: "";
|
|
1121
1153
|
|
|
1122
1154
|
const collectionVarName = toCollectionVarName(tableName);
|
|
1123
1155
|
const fileContent = `${Array.from(imports).join("\n")}
|
|
1124
1156
|
${classificationNote}
|
|
1125
1157
|
const ${collectionVarName}: PostgresCollectionConfig = {
|
|
1126
|
-
name:
|
|
1127
|
-
singularName:
|
|
1128
|
-
slug:
|
|
1129
|
-
table:
|
|
1158
|
+
name: ${quote(collectionName)},
|
|
1159
|
+
singularName: ${quote(singular)},
|
|
1160
|
+
slug: ${quote(tableName)},
|
|
1161
|
+
table: ${quote(tableName)},${descriptionBlock}
|
|
1130
1162
|
properties: {${propsOutput}
|
|
1131
1163
|
},${relationsBlock}${adminBlock}
|
|
1132
1164
|
};
|
|
@@ -1146,7 +1178,7 @@ export function generateIndexContent(fileNames: string[]): string {
|
|
|
1146
1178
|
let arrayElements = "";
|
|
1147
1179
|
for (const f of sorted) {
|
|
1148
1180
|
const varName = toCollectionVarName(f);
|
|
1149
|
-
imports += `import ${varName} from
|
|
1181
|
+
imports += `import ${varName} from ${quote(`./${f}`)};\n`;
|
|
1150
1182
|
arrayElements += ` ${varName},\n`;
|
|
1151
1183
|
}
|
|
1152
1184
|
return `${imports}\nexport const collections = [\n${arrayElements}];\n`;
|
|
@@ -1168,7 +1200,7 @@ export function mergeIndexContent(existingContent: string, newFileNames: string[
|
|
|
1168
1200
|
for (const f of sorted) {
|
|
1169
1201
|
if (!existingImports.has(f)) {
|
|
1170
1202
|
const varName = toCollectionVarName(f);
|
|
1171
|
-
newImports += `import ${varName} from
|
|
1203
|
+
newImports += `import ${varName} from ${quote(`./${f}`)};\n`;
|
|
1172
1204
|
newElements += ` ${varName},\n`;
|
|
1173
1205
|
}
|
|
1174
1206
|
}
|