@rebasepro/server-postgres 0.12.1-canary.g181d0fe → 0.12.1-canary.g35be8cb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ensure-collection-policies-CT-zIUWA.js → ensure-collection-policies-Vl3Cv1Q9.js} +2 -2
- package/dist/{ensure-collection-policies-CT-zIUWA.js.map → ensure-collection-policies-Vl3Cv1Q9.js.map} +1 -1
- package/dist/{ensure-collection-tables-Vu-GRELM.js → ensure-collection-tables-DsDsNl6o.js} +234 -25
- package/dist/ensure-collection-tables-DsDsNl6o.js.map +1 -0
- package/dist/index.es.js +35 -14
- package/dist/index.es.js.map +1 -1
- package/dist/schema/ensure-collection-tables.d.ts +24 -2
- package/dist/schema/generate-postgres-ddl-logic.d.ts +82 -9
- package/package.json +6 -6
- package/src/PostgresBootstrapper.ts +7 -1
- package/src/schema/ensure-collection-tables.test.ts +105 -9
- package/src/schema/ensure-collection-tables.ts +142 -25
- package/src/schema/generate-postgres-ddl-logic.ts +244 -12
- package/src/schema/introspect-runtime.test.ts +56 -8
- package/src/schema/introspect-runtime.ts +31 -9
- package/dist/ensure-collection-tables-Vu-GRELM.js.map +0 -1
|
@@ -11,7 +11,7 @@ export const resolveColumnName = (propName: string, prop?: Property | null): str
|
|
|
11
11
|
return toSnakeCase(propName);
|
|
12
12
|
};
|
|
13
13
|
|
|
14
|
-
const getPrimaryKeyProp = (collection: CollectionConfig): { name: string, type: "string" | "number", isUuid: boolean } => {
|
|
14
|
+
export const getPrimaryKeyProp = (collection: CollectionConfig): { name: string, type: "string" | "number", isUuid: boolean } => {
|
|
15
15
|
if (collection.properties) {
|
|
16
16
|
const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => "isId" in (prop as unknown as object) && Boolean((prop as unknown as Record<string, unknown>).isId));
|
|
17
17
|
if (idPropEntry) {
|
|
@@ -28,14 +28,18 @@ const getPrimaryKeyProp = (collection: CollectionConfig): { name: string, type:
|
|
|
28
28
|
return { name: "id", type: "string", isUuid: isUuid ?? false };
|
|
29
29
|
};
|
|
30
30
|
|
|
31
|
-
const isNumericId = (collection: CollectionConfig): boolean => {
|
|
31
|
+
export const isNumericId = (collection: CollectionConfig): boolean => {
|
|
32
32
|
return getPrimaryKeyProp(collection).type === "number";
|
|
33
33
|
};
|
|
34
34
|
|
|
35
|
-
const getPrimaryKeyName = (collection: CollectionConfig): string => {
|
|
35
|
+
export const getPrimaryKeyName = (collection: CollectionConfig): string => {
|
|
36
36
|
return getPrimaryKeyProp(collection).name;
|
|
37
37
|
};
|
|
38
38
|
|
|
39
|
+
/** The column type a junction holds for one endpoint's primary key. */
|
|
40
|
+
const junctionKeyType = (collection: CollectionConfig): string =>
|
|
41
|
+
isNumericId(collection) ? "INTEGER" : (getPrimaryKeyProp(collection).isUuid ? "UUID" : "TEXT");
|
|
42
|
+
|
|
39
43
|
export const isIdProperty = (propName: string, prop: Property, collection: CollectionConfig): boolean => {
|
|
40
44
|
if ("isId" in prop && Boolean(prop.isId)) return true;
|
|
41
45
|
const hasExplicitId = Object.values(collection.properties ?? {}).some(p => "isId" in (p as unknown as object) && Boolean((p as unknown as Record<string, unknown>).isId));
|
|
@@ -497,6 +501,213 @@ export const generatePostgresDdl = async (
|
|
|
497
501
|
};
|
|
498
502
|
|
|
499
503
|
/** The RLS statements one declared collection's table needs, ready to run. */
|
|
504
|
+
/**
|
|
505
|
+
* A foreign key, as both its parts and the statement that creates it.
|
|
506
|
+
*
|
|
507
|
+
* `ALTER TABLE … ADD CONSTRAINT` has no `IF NOT EXISTS`, so a caller applying
|
|
508
|
+
* these has to skip by name — hence the name is a field and not only a substring
|
|
509
|
+
* of the SQL.
|
|
510
|
+
*/
|
|
511
|
+
export interface ForeignKeyPlan {
|
|
512
|
+
constraintName: string;
|
|
513
|
+
schema: string;
|
|
514
|
+
/** Bare table name, no schema prefix. */
|
|
515
|
+
table: string;
|
|
516
|
+
column: string;
|
|
517
|
+
targetSchema: string;
|
|
518
|
+
targetTable: string;
|
|
519
|
+
targetColumn: string;
|
|
520
|
+
sql: string;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** A column a `relation` or `reference` property owns on its own table. */
|
|
524
|
+
export interface RelationalColumnPlan {
|
|
525
|
+
schema: string;
|
|
526
|
+
/** Bare table name, no schema prefix. */
|
|
527
|
+
table: string;
|
|
528
|
+
column: string;
|
|
529
|
+
/** Postgres type, exactly as the DDL generator declares it. */
|
|
530
|
+
type: string;
|
|
531
|
+
/** Absent when the target collection is not part of this bundle. */
|
|
532
|
+
foreignKey?: ForeignKeyPlan;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** The table behind a many-to-many `through` relation. */
|
|
536
|
+
export interface JunctionTablePlan {
|
|
537
|
+
schema: string;
|
|
538
|
+
/** Bare table name, no schema prefix. */
|
|
539
|
+
table: string;
|
|
540
|
+
columns: { name: string; type: string }[];
|
|
541
|
+
/** Both endpoint columns plus the composite primary key. */
|
|
542
|
+
createTable: string;
|
|
543
|
+
foreignKeys: ForeignKeyPlan[];
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const schemaOfCollection = (collection: CollectionConfig): string =>
|
|
547
|
+
isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : "public";
|
|
548
|
+
|
|
549
|
+
const bareTableName = (name: string): string => (name.includes(".") ? name.split(".").pop()! : name);
|
|
550
|
+
|
|
551
|
+
const foreignKeyPlan = (
|
|
552
|
+
args: Omit<ForeignKeyPlan, "constraintName" | "sql"> & { onDelete: string; onUpdate?: string }
|
|
553
|
+
): ForeignKeyPlan => {
|
|
554
|
+
const constraintName = `${args.table}_${args.column}_fkey`;
|
|
555
|
+
const onUpdate = args.onUpdate ? ` ON UPDATE ${args.onUpdate.toUpperCase()}` : "";
|
|
556
|
+
return {
|
|
557
|
+
constraintName,
|
|
558
|
+
schema: args.schema,
|
|
559
|
+
table: args.table,
|
|
560
|
+
column: args.column,
|
|
561
|
+
targetSchema: args.targetSchema,
|
|
562
|
+
targetTable: args.targetTable,
|
|
563
|
+
targetColumn: args.targetColumn,
|
|
564
|
+
sql:
|
|
565
|
+
`ALTER TABLE "${args.schema}"."${args.table}" ADD CONSTRAINT "${constraintName}" ` +
|
|
566
|
+
`FOREIGN KEY ("${args.column}") REFERENCES "${args.targetSchema}"."${args.targetTable}" ` +
|
|
567
|
+
`("${args.targetColumn}") ON DELETE ${args.onDelete.toUpperCase()}${onUpdate};`
|
|
568
|
+
};
|
|
569
|
+
};
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* The FK columns the declared collections own — one entry per `relation`
|
|
573
|
+
* (`belongsTo` side) or `reference` property.
|
|
574
|
+
*
|
|
575
|
+
* Split out of {@link generatePostgresDdl} so the boot-time schema ensure can
|
|
576
|
+
* create the same columns with the same names, types and constraints. Before
|
|
577
|
+
* this it skipped them outright, which was survivable only because `db push`
|
|
578
|
+
* always followed; on a managed tenant nothing follows, so a table arrived
|
|
579
|
+
* without the column its own collection reads and wrote 400 on every insert.
|
|
580
|
+
*
|
|
581
|
+
* A relation whose target is not in the bundle yields no column at all (the
|
|
582
|
+
* generator returns early on an unresolvable target); a `reference` whose target
|
|
583
|
+
* is unknown yields the column without a constraint. Both mirror the generator
|
|
584
|
+
* exactly — a divergence here is a schema fork between boot and `db push`.
|
|
585
|
+
*/
|
|
586
|
+
export const planRelationalColumns = (collections: CollectionConfig[]): RelationalColumnPlan[] => {
|
|
587
|
+
const plans: RelationalColumnPlan[] = [];
|
|
588
|
+
|
|
589
|
+
for (const collection of collections) {
|
|
590
|
+
const tableName = getTableName(collection);
|
|
591
|
+
if (!tableName) continue;
|
|
592
|
+
const schema = schemaOfCollection(collection);
|
|
593
|
+
const table = bareTableName(tableName);
|
|
594
|
+
|
|
595
|
+
for (const [propName, rawProp] of Object.entries(collection.properties ?? {})) {
|
|
596
|
+
const prop = rawProp as Property;
|
|
597
|
+
|
|
598
|
+
if (prop.type === "relation") {
|
|
599
|
+
const refProp = prop as RelationProperty;
|
|
600
|
+
const resolvedRelations = resolveCollectionRelations(collection);
|
|
601
|
+
const relInfo = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);
|
|
602
|
+
if (relInfo?.kind !== "belongsTo") continue;
|
|
603
|
+
// The relation and an explicit FK property can both be declared;
|
|
604
|
+
// the explicit one owns the column.
|
|
605
|
+
if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) continue;
|
|
606
|
+
|
|
607
|
+
let targetCollection: CollectionConfig;
|
|
608
|
+
try {
|
|
609
|
+
targetCollection = relInfo.target();
|
|
610
|
+
} catch {
|
|
611
|
+
continue;
|
|
612
|
+
}
|
|
613
|
+
if (!targetCollection) continue;
|
|
614
|
+
|
|
615
|
+
const required = prop.validation?.required;
|
|
616
|
+
plans.push({
|
|
617
|
+
schema,
|
|
618
|
+
table,
|
|
619
|
+
column: relInfo.localKey,
|
|
620
|
+
type: getSqlColumnType(propName, prop, collection, collections),
|
|
621
|
+
foreignKey: foreignKeyPlan({
|
|
622
|
+
schema,
|
|
623
|
+
table,
|
|
624
|
+
column: relInfo.localKey,
|
|
625
|
+
targetSchema: schemaOfCollection(targetCollection),
|
|
626
|
+
targetTable: bareTableName(getTableName(targetCollection)),
|
|
627
|
+
targetColumn: getPrimaryKeyName(targetCollection),
|
|
628
|
+
onDelete: relInfo.onDelete ?? (required ? "CASCADE" : "SET NULL"),
|
|
629
|
+
onUpdate: relInfo.onUpdate
|
|
630
|
+
})
|
|
631
|
+
});
|
|
632
|
+
} else if (prop.type === "reference") {
|
|
633
|
+
const refProp = prop as ReferenceProperty;
|
|
634
|
+
const targetCollection = collections.find(
|
|
635
|
+
c => c.slug === refProp.path || getTableName(c) === refProp.path
|
|
636
|
+
);
|
|
637
|
+
const column = resolveColumnName(propName, prop);
|
|
638
|
+
const type = getSqlColumnType(propName, prop, collection, collections);
|
|
639
|
+
const required = prop.validation?.required;
|
|
640
|
+
|
|
641
|
+
plans.push({
|
|
642
|
+
schema,
|
|
643
|
+
table,
|
|
644
|
+
column,
|
|
645
|
+
type,
|
|
646
|
+
foreignKey: targetCollection
|
|
647
|
+
? foreignKeyPlan({
|
|
648
|
+
schema,
|
|
649
|
+
table,
|
|
650
|
+
column,
|
|
651
|
+
targetSchema: schemaOfCollection(targetCollection),
|
|
652
|
+
targetTable: bareTableName(getTableName(targetCollection)),
|
|
653
|
+
targetColumn: getPrimaryKeyName(targetCollection),
|
|
654
|
+
onDelete: required ? "CASCADE" : "SET NULL"
|
|
655
|
+
})
|
|
656
|
+
: undefined
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
return plans;
|
|
663
|
+
};
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* The junction tables a bundle's many-to-many relations imply.
|
|
667
|
+
*
|
|
668
|
+
* Derived from {@link resolveJunctionSpecs}, the same source the junction RLS
|
|
669
|
+
* comes from, so a table created here always has policies planned for it — a
|
|
670
|
+
* junction with row-level security left off is readable and writable by every
|
|
671
|
+
* signed-in user, which is why the two must ship together.
|
|
672
|
+
*/
|
|
673
|
+
export const planJunctionTables = (collections: CollectionConfig[]): JunctionTablePlan[] => {
|
|
674
|
+
const plans: JunctionTablePlan[] = [];
|
|
675
|
+
|
|
676
|
+
for (const spec of resolveJunctionSpecs(collections).values()) {
|
|
677
|
+
const [source, target] = spec.endpoints;
|
|
678
|
+
const columns = [
|
|
679
|
+
{ name: source.junctionColumn, type: junctionKeyType(source.collection) },
|
|
680
|
+
{ name: target.junctionColumn, type: junctionKeyType(target.collection) }
|
|
681
|
+
];
|
|
682
|
+
// Every declaring side agrees on the edge's lifetime; the first one wins,
|
|
683
|
+
// as it does in the generator's walk.
|
|
684
|
+
const onDelete = spec.declaringSides[0]?.relation.onDelete ?? "CASCADE";
|
|
685
|
+
|
|
686
|
+
plans.push({
|
|
687
|
+
schema: spec.schema,
|
|
688
|
+
table: spec.table,
|
|
689
|
+
columns,
|
|
690
|
+
createTable:
|
|
691
|
+
`CREATE TABLE IF NOT EXISTS "${spec.schema}"."${spec.table}" (` +
|
|
692
|
+
columns.map(c => `"${c.name}" ${c.type} NOT NULL`).join(", ") +
|
|
693
|
+
`, PRIMARY KEY (${columns.map(c => `"${c.name}"`).join(", ")}));`,
|
|
694
|
+
foreignKeys: [source, target].map((endpoint, i) =>
|
|
695
|
+
foreignKeyPlan({
|
|
696
|
+
schema: spec.schema,
|
|
697
|
+
table: spec.table,
|
|
698
|
+
column: columns[i].name,
|
|
699
|
+
targetSchema: schemaOfCollection(endpoint.collection),
|
|
700
|
+
targetTable: bareTableName(getTableName(endpoint.collection)),
|
|
701
|
+
targetColumn: getPrimaryKeyName(endpoint.collection),
|
|
702
|
+
onDelete
|
|
703
|
+
})
|
|
704
|
+
)
|
|
705
|
+
});
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
return plans;
|
|
709
|
+
};
|
|
710
|
+
|
|
500
711
|
export interface CollectionPolicyPlan {
|
|
501
712
|
/** The table's schema (e.g. `public`, `rebase`). */
|
|
502
713
|
schema: string;
|
|
@@ -515,16 +726,15 @@ export interface CollectionPolicyPlan {
|
|
|
515
726
|
* statements — what the managed runtime applies at boot so a freshly
|
|
516
727
|
* provisioned tenant database serves data instead of 401ing every read.
|
|
517
728
|
*
|
|
518
|
-
* Mirrors
|
|
519
|
-
*
|
|
520
|
-
* boot and `db push` produce identical policies from
|
|
729
|
+
* Mirrors {@link generatePostgresPoliciesDdl} exactly (same
|
|
730
|
+
* `generatePolicyStatements`, same enable-RLS, same effective rules, same
|
|
731
|
+
* derived junction rules), so boot and `db push` produce identical policies from
|
|
732
|
+
* identical collections.
|
|
521
733
|
*
|
|
522
|
-
* Junction tables are
|
|
523
|
-
*
|
|
524
|
-
*
|
|
525
|
-
*
|
|
526
|
-
* `db migrate` concern, which is where those tables get created in the first
|
|
527
|
-
* place. `db push` still applies junction policies via the string generator.
|
|
734
|
+
* Junction tables are included, and have to be: boot creates them now
|
|
735
|
+
* ({@link planJunctionTables}), and a junction with RLS left off is readable and
|
|
736
|
+
* writable by every signed-in user. A junction whose table is still absent is
|
|
737
|
+
* skipped by the applier, not planned away here.
|
|
528
738
|
*/
|
|
529
739
|
export const planCollectionPolicies = (collections: CollectionConfig[]): CollectionPolicyPlan[] => {
|
|
530
740
|
const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);
|
|
@@ -554,6 +764,28 @@ export const planCollectionPolicies = (collections: CollectionConfig[]): Collect
|
|
|
554
764
|
});
|
|
555
765
|
}
|
|
556
766
|
|
|
767
|
+
// Junctions are derived from `through` relations rather than declared, so
|
|
768
|
+
// the walk above never sees them.
|
|
769
|
+
for (const spec of resolveJunctionSpecs(collections).values()) {
|
|
770
|
+
const qualified = `${spec.schema}.${spec.table}`;
|
|
771
|
+
if (seen.has(qualified)) continue;
|
|
772
|
+
seen.add(qualified);
|
|
773
|
+
|
|
774
|
+
const junctionCollection = getJunctionCollectionConfig(spec);
|
|
775
|
+
const policyStatements: string[] = [];
|
|
776
|
+
for (const rule of getJunctionSecurityRules(spec)) {
|
|
777
|
+
policyStatements.push(...generatePolicyStatements(junctionCollection, rule, resolveCollection));
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
plans.push({
|
|
781
|
+
schema: spec.schema,
|
|
782
|
+
table: spec.table,
|
|
783
|
+
qualified,
|
|
784
|
+
enableRls: `ALTER TABLE "${spec.schema}"."${spec.table}" ENABLE ROW LEVEL SECURITY;`,
|
|
785
|
+
policyStatements
|
|
786
|
+
});
|
|
787
|
+
}
|
|
788
|
+
|
|
557
789
|
return plans;
|
|
558
790
|
};
|
|
559
791
|
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { describe, expect, it } from "@jest/globals";
|
|
2
|
+
import { resolveCollectionRelations } from "@rebasepro/common";
|
|
3
|
+
import type { CollectionConfig } from "@rebasepro/types";
|
|
2
4
|
|
|
3
5
|
import { buildCollectionsFromSchema, introspectSchema, readRlsStatus, IntrospectedSchema, Queryable } from "./introspect-runtime";
|
|
4
6
|
import { buildTablesMap, identifyJoinTables, TableColumn, ForeignKeyRow, PrimaryKeyRow } from "./introspect-db-logic";
|
|
@@ -121,14 +123,60 @@ describe("buildCollectionsFromSchema", () => {
|
|
|
121
123
|
const props = posts.properties as any;
|
|
122
124
|
|
|
123
125
|
expect(props.author_id).toBeUndefined();
|
|
124
|
-
expect(props.author).
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
126
|
+
expect(props.author.name).toBe("Author");
|
|
127
|
+
expect(props.author.type).toBe("relation");
|
|
128
|
+
// The descriptor is nested under `relation`, carries `kind`, and its
|
|
129
|
+
// `target` is a thunk — see the resolvability test below for why none of
|
|
130
|
+
// those three are stylistic.
|
|
131
|
+
expect(props.author.relation).toMatchObject({ kind: "belongsTo", localKey: "author_id" });
|
|
132
|
+
expect(typeof props.author.relation.target).toBe("function");
|
|
133
|
+
expect(props.author.relation.target().slug).toBe("authors");
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* The shape has to be one the resolver actually reads.
|
|
138
|
+
*
|
|
139
|
+
* This path emitted `cardinality` / `direction` / a bare-string `target`
|
|
140
|
+
* flat on the property — the shape `Relation` stopped accepting, and the
|
|
141
|
+
* same drift `introspect-emits-valid-relations.test.ts` caught in the
|
|
142
|
+
* generated-file path and this one was missed by. Nothing threw:
|
|
143
|
+
* `resolveCollectionRelations` reads `property.relation`, found none, and
|
|
144
|
+
* reported a collection with no relations at all.
|
|
145
|
+
*
|
|
146
|
+
* The visible cost was writes. `assertKnownWriteFields` learns an owning
|
|
147
|
+
* relation's FK column from the *resolved* relation's `localKey`, and the FK
|
|
148
|
+
* column is deliberately absent from `properties` ("surfaces as a
|
|
149
|
+
* relation"), so with nothing resolving, `POST /api/data/orders` with
|
|
150
|
+
* `product_id` came back 400 `has no field 'product_id'` — the column was
|
|
151
|
+
* simultaneously the only way to set the relation and not a known field.
|
|
152
|
+
*
|
|
153
|
+
* Asserting the literal object is what let it drift, so this asserts
|
|
154
|
+
* through the resolver instead: a future reshape has to keep it resolvable,
|
|
155
|
+
* not merely keep the keys someone once wrote down.
|
|
156
|
+
*/
|
|
157
|
+
it("emits a relation the resolver can read, so the fk column is writable", () => {
|
|
158
|
+
const schema = schemaOf(
|
|
159
|
+
[
|
|
160
|
+
column({ table_name: "products", column_name: "id", data_type: "integer", udt_name: "int4", is_nullable: "NO" }),
|
|
161
|
+
column({ table_name: "orders", column_name: "id", data_type: "integer", udt_name: "int4", is_nullable: "NO" }),
|
|
162
|
+
column({ table_name: "orders", column_name: "product_id", data_type: "integer", udt_name: "int4" })
|
|
163
|
+
],
|
|
164
|
+
[
|
|
165
|
+
{ table_name: "products", column_name: "id" },
|
|
166
|
+
{ table_name: "orders", column_name: "id" }
|
|
167
|
+
],
|
|
168
|
+
[{ table_name: "orders", column_name: "product_id", foreign_table_name: "products", foreign_column_name: "id" }]
|
|
169
|
+
);
|
|
170
|
+
|
|
171
|
+
const orders = buildCollectionsFromSchema(schema, "public").find((c) => c.slug === "orders")!;
|
|
172
|
+
const resolved = resolveCollectionRelations(orders as unknown as CollectionConfig);
|
|
173
|
+
|
|
174
|
+
expect(Object.keys(resolved)).toEqual(["product"]);
|
|
175
|
+
expect(resolved.product.kind).toBe("belongsTo");
|
|
176
|
+
// `localKey` is the field `assertKnownWriteFields` adds to the known set,
|
|
177
|
+
// which is what makes `product_id` writable. The write itself is covered
|
|
178
|
+
// end-to-end by `scripts/smoke-baas.ts` against a real database.
|
|
179
|
+
expect((resolved.product as { localKey: string }).localKey).toBe("product_id");
|
|
132
180
|
});
|
|
133
181
|
|
|
134
182
|
it("skips join tables — they are an edge between collections, not a collection", () => {
|
|
@@ -207,13 +207,30 @@ function buildProperties(
|
|
|
207
207
|
}
|
|
208
208
|
|
|
209
209
|
/**
|
|
210
|
-
* Owning relations, derived from this table's foreign keys
|
|
211
|
-
* `generateCollectionFile`
|
|
212
|
-
*
|
|
210
|
+
* Owning relations, derived from this table's foreign keys — the same shape
|
|
211
|
+
* `generateCollectionFile` writes into a collection file: a `relation` property
|
|
212
|
+
* whose nested descriptor carries `kind`, a `target` thunk and the `localKey`.
|
|
213
|
+
*
|
|
214
|
+
* The shape is load-bearing, not cosmetic. `resolveCollectionRelations` reads
|
|
215
|
+
* relations from `property.relation` and `resolveRelation` requires `target` to
|
|
216
|
+
* be a thunk; this used to emit `target`/`cardinality`/`localKey` flat on the
|
|
217
|
+
* property with the slug as a bare string, which satisfies neither. Nothing
|
|
218
|
+
* threw — the resolver simply skipped every such property and reported that the
|
|
219
|
+
* collection had no relations. So an introspected BaaS collection had its FK
|
|
220
|
+
* columns removed from `properties` (they "surface as relations") and then no
|
|
221
|
+
* resolvable relation to surface as, which is why writing the FK column
|
|
222
|
+
* directly came back as `has no field 'product_id'`: `assertKnownWriteFields`
|
|
223
|
+
* learns that column from the resolved relation's `localKey`.
|
|
224
|
+
*
|
|
225
|
+
* The thunk closes over the collections being built in this same pass rather
|
|
226
|
+
* than importing a module, which is what a runtime introspection has instead of
|
|
227
|
+
* generated files. It is called lazily, after the map is fully populated, so a
|
|
228
|
+
* table may reference one introspected later.
|
|
213
229
|
*/
|
|
214
230
|
function buildRelations(
|
|
215
231
|
meta: TableMeta,
|
|
216
|
-
slugByTable: Map<string, string
|
|
232
|
+
slugByTable: Map<string, string>,
|
|
233
|
+
collectionBySlug: Map<string, PostgresCollectionConfig>
|
|
217
234
|
): Record<string, Record<string, unknown>> {
|
|
218
235
|
const relations: Record<string, Record<string, unknown>> = {};
|
|
219
236
|
|
|
@@ -233,10 +250,11 @@ function buildRelations(
|
|
|
233
250
|
relations[key] = {
|
|
234
251
|
name: humanize(key),
|
|
235
252
|
type: "relation",
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
253
|
+
relation: {
|
|
254
|
+
kind: "belongsTo",
|
|
255
|
+
target: () => collectionBySlug.get(targetSlug),
|
|
256
|
+
localKey: fk.column_name
|
|
257
|
+
}
|
|
240
258
|
};
|
|
241
259
|
}
|
|
242
260
|
|
|
@@ -259,6 +277,9 @@ export function buildCollectionsFromSchema(
|
|
|
259
277
|
}
|
|
260
278
|
|
|
261
279
|
const collections: PostgresCollectionConfig[] = [];
|
|
280
|
+
// Filled as we go; the relation thunks read it lazily, so a table may point
|
|
281
|
+
// at one that has not been built yet at the moment its relation is created.
|
|
282
|
+
const collectionBySlug = new Map<string, PostgresCollectionConfig>();
|
|
262
283
|
|
|
263
284
|
for (const [tableName, meta] of tablesMap) {
|
|
264
285
|
if (joinTables.has(tableName)) continue;
|
|
@@ -273,11 +294,12 @@ export function buildCollectionsFromSchema(
|
|
|
273
294
|
icon: getIconForTable(tableName),
|
|
274
295
|
properties: {
|
|
275
296
|
...buildProperties(meta, enumMap),
|
|
276
|
-
...buildRelations(meta, slugByTable)
|
|
297
|
+
...buildRelations(meta, slugByTable, collectionBySlug)
|
|
277
298
|
}
|
|
278
299
|
} as unknown as PostgresCollectionConfig;
|
|
279
300
|
|
|
280
301
|
collections.push(collection);
|
|
302
|
+
collectionBySlug.set(tableName, collection);
|
|
281
303
|
}
|
|
282
304
|
|
|
283
305
|
return collections;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ensure-collection-tables-Vu-GRELM.js","names":[],"sources":["../src/schema/generate-postgres-ddl-logic.ts","../src/schema/ensure-collection-tables.ts"],"sourcesContent":["import { CollectionConfig, NumberProperty, Property, ResolvedRelation, RelationProperty, SecurityOperation, SecurityRule, StringProperty, isPostgresCollectionConfig, DateProperty, ArrayProperty, MapProperty, ReferenceProperty, VectorProperty, BinaryProperty, isManyToMany, type ResolvedManyToMany, type ResolvedBelongsTo } from \"@rebasepro/types\";\nimport { getEnumVarName, getTableName, resolveCollectionRelations, findRelation, securityRuleToConditions, policyToPostgres, getEffectiveSecurityRules, getInjectedSecurityRules, resolveJunctionSpecs, getJunctionSecurityRules, getJunctionCollectionConfig, resolveStringColumnLength } from \"@rebasepro/common\";\nimport { toSnakeCase, getPolicyNamesForRule } from \"@rebasepro/utils\";\n\n// --- Helper Functions ---\n\nexport const resolveColumnName = (propName: string, prop?: Property | null): string => {\n if (prop && \"columnName\" in prop && typeof prop.columnName === \"string\") {\n return prop.columnName;\n }\n return toSnakeCase(propName);\n};\n\nconst getPrimaryKeyProp = (collection: CollectionConfig): { name: string, type: \"string\" | \"number\", isUuid: boolean } => {\n if (collection.properties) {\n const idPropEntry = Object.entries(collection.properties).find(([_, prop]) => \"isId\" in (prop as unknown as object) && Boolean((prop as unknown as Record<string, unknown>).isId));\n if (idPropEntry) {\n const prop = idPropEntry[1] as unknown as Property;\n const isUuid = prop.type === \"string\" && \"isId\" in prop && (prop as unknown as StringProperty).isId === \"uuid\";\n return { name: idPropEntry[0], type: prop.type === \"number\" ? \"number\" : \"string\", isUuid };\n }\n }\n const idProp = collection.properties?.[\"id\"] as unknown as Property | undefined;\n if (idProp?.type === \"number\") {\n return { name: \"id\", type: \"number\", isUuid: false };\n }\n const isUuid = idProp?.type === \"string\" && \"isId\" in idProp && (idProp as unknown as StringProperty).isId === \"uuid\";\n return { name: \"id\", type: \"string\", isUuid: isUuid ?? false };\n};\n\nconst isNumericId = (collection: CollectionConfig): boolean => {\n return getPrimaryKeyProp(collection).type === \"number\";\n};\n\nconst getPrimaryKeyName = (collection: CollectionConfig): string => {\n return getPrimaryKeyProp(collection).name;\n};\n\nexport const isIdProperty = (propName: string, prop: Property, collection: CollectionConfig): boolean => {\n if (\"isId\" in prop && Boolean(prop.isId)) return true;\n const hasExplicitId = Object.values(collection.properties ?? {}).some(p => \"isId\" in (p as unknown as object) && Boolean((p as unknown as Record<string, unknown>).isId));\n return !hasExplicitId && propName === \"id\";\n};\n\n\ntype ResolveCollection = (slug: string) => CollectionConfig | undefined;\n\n/**\n * Render statements produced by {@link generatePolicyStatements} back into the\n * exact string the DDL/policies files have always carried: each statement on\n * its own line, terminated by a newline. Keeping the string form derived from\n * the statement array means the two can never drift — the boot-time applier and\n * the generated `policies.sql` emit the same SQL, from the same source.\n */\nconst statementsToDdl = (statements: string[]): string => statements.map(s => `${s}\\n`).join(\"\");\n\nconst generatePolicyDdl = (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection): string =>\n statementsToDdl(generatePolicyStatements(collection, rule, resolveCollection));\n\n/**\n * The individual SQL statements a single security rule compiles to: a\n * `DROP POLICY IF EXISTS` / `CREATE POLICY` pair per operation, each a complete\n * statement (terminated by `;`, no trailing newline).\n *\n * This is the primitive the boot-time RLS applier runs one statement at a time\n * (the runtime's DB handle speaks the extended query protocol, which forbids\n * multiple commands in one execute), while `db push` writes the joined string.\n */\nexport const generatePolicyStatements = (collection: CollectionConfig, rule: SecurityRule, resolveCollection: ResolveCollection): string[] => {\n const tableName = getTableName(collection);\n const ops: readonly SecurityOperation[] = rule.operations && rule.operations.length > 0\n ? rule.operations\n : [rule.operation ?? \"all\"];\n\n const policyNames = getPolicyNamesForRule(rule, tableName);\n\n return ops.flatMap((op, opIdx) => {\n return generateSinglePolicyStatements(collection, rule, op, policyNames[opIdx], resolveCollection);\n });\n};\n\nconst generateSinglePolicyStatements = (collection: CollectionConfig, rule: SecurityRule, operation: SecurityOperation, policyName: string, resolveCollection: ResolveCollection): string[] => {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const tableName = getTableName(collection);\n const mode = (rule.mode ?? \"permissive\").toUpperCase();\n const operationUpper = operation.toUpperCase();\n const pgRoles = rule.pgRoles ? [...rule.pgRoles].sort() : [\"public\"];\n\n const needsUsing = operation !== \"insert\";\n const needsWithCheck = operation !== \"select\" && operation !== \"delete\";\n\n // Desugar the rule (access / ownerField / roles / structured condition / raw\n // SQL) into the shared PolicyExpression model, then compile to SQL. This is\n // the same normalization the client-side evaluator uses, so DDL and UI agree.\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);\n\n let usingClause = needsUsing && usingExpr ? policyToPostgres(usingExpr, collection, { resolveCollection }) : null;\n let withCheckClause = needsWithCheck && withCheckExpr ? policyToPostgres(withCheckExpr, collection, { resolveCollection }) : null;\n\n if (!usingClause && needsUsing) {\n usingClause = \"false\";\n }\n if (!withCheckClause && needsWithCheck) {\n withCheckClause = \"false\";\n }\n\n const drop = `DROP POLICY IF EXISTS \"${policyName}\" ON \"${schema}\".\"${tableName}\";`;\n let create = `CREATE POLICY \"${policyName}\" ON \"${schema}\".\"${tableName}\" AS ${mode} FOR ${operationUpper} TO ${pgRoles.map(r => `\"${r}\"`).join(\", \")}`;\n if (usingClause) create += ` USING (${usingClause})`;\n if (withCheckClause) create += ` WITH CHECK (${withCheckClause})`;\n create += \";\";\n return [drop, create];\n};\n\nexport const getSqlColumnType = (propName: string, prop: Property, collection: CollectionConfig, collections: CollectionConfig[]): string => {\n switch (prop.type) {\n case \"string\": {\n const stringProp = prop as StringProperty;\n if (stringProp.enum) {\n const tableName = getTableName(collection);\n const colName = resolveColumnName(propName, prop);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n return `\"${schema}\".\"${tableName}_${colName}\"`;\n }\n if (stringProp.isId === \"uuid\" || stringProp.columnType === \"uuid\") {\n return \"UUID\";\n }\n // Width comes from `validation.max` when the property states one.\n // It used to be a hardcoded 255 here and *absent* on the Drizzle\n // path, so the same property produced a bounded column down one\n // generator and an unbounded one down the other.\n if (stringProp.columnType === \"char\") {\n return `CHAR(${resolveStringColumnLength(stringProp)})`;\n }\n if (stringProp.columnType === \"varchar\") {\n return `VARCHAR(${resolveStringColumnLength(stringProp)})`;\n }\n // `text` is the default. The two generators disagreed here before:\n // this one emitted VARCHAR(255) while the drizzle path emitted a bare\n // `varchar()`, which Postgres treats as unbounded — so the same\n // property produced a capped column down one path and an uncapped one\n // down the other.\n return \"TEXT\";\n }\n case \"number\": {\n const numProp = prop as NumberProperty;\n const isId = isIdProperty(propName, prop, collection);\n if (\"isId\" in numProp && numProp.isId === \"increment\") {\n return \"INTEGER GENERATED BY DEFAULT AS IDENTITY\";\n }\n if (numProp.columnType) {\n if (numProp.columnType === \"double precision\") return \"DOUBLE PRECISION\";\n return numProp.columnType.toUpperCase();\n }\n return (numProp.validation?.integer || isId) ? \"INTEGER\" : \"NUMERIC\";\n }\n case \"boolean\":\n return \"BOOLEAN\";\n case \"date\": {\n const dateProp = prop as DateProperty;\n if (dateProp.columnType === \"date\") return \"DATE\";\n if (dateProp.columnType === \"time\") return \"TIME\";\n return \"TIMESTAMP WITH TIME ZONE\";\n }\n case \"map\": {\n const mapProp = prop as MapProperty;\n return mapProp.columnType === \"json\" ? \"JSON\" : \"JSONB\";\n }\n case \"array\": {\n const arrayProp = prop as ArrayProperty;\n let colType = arrayProp.columnType;\n if (!colType && arrayProp.of && !Array.isArray(arrayProp.of)) {\n const ofProp = arrayProp.of as Property;\n if (ofProp.type === \"string\") {\n colType = \"text[]\";\n } else if (ofProp.type === \"number\") {\n colType = ofProp.validation?.integer ? \"integer[]\" : \"numeric[]\";\n } else if (ofProp.type === \"boolean\") {\n colType = \"boolean[]\";\n }\n }\n if (colType === \"json\") return \"JSON\";\n if (colType === \"text[]\") return \"TEXT[]\";\n if (colType === \"integer[]\") return \"INTEGER[]\";\n if (colType === \"boolean[]\") return \"BOOLEAN[]\";\n if (colType === \"numeric[]\") return \"NUMERIC[]\";\n return \"JSONB\";\n }\n case \"vector\": {\n const vp = prop as VectorProperty;\n return `VECTOR(${vp.dimensions})`;\n }\n case \"binary\": {\n return \"BYTEA\";\n }\n case \"relation\": {\n const refProp = prop as RelationProperty;\n const resolvedRelations = resolveCollectionRelations(collection);\n const relation = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);\n if (relation?.kind !== \"belongsTo\") {\n throw new Error(`Relation ${propName} does not put a column on this table (only \\`belongsTo\\` does)`);\n }\n let targetCollection: CollectionConfig;\n try {\n targetCollection = relation.target();\n } catch {\n return \"TEXT\";\n }\n const pkProp = getPrimaryKeyProp(targetCollection);\n return pkProp.type === \"number\" ? \"INTEGER\" : (pkProp.isUuid ? \"UUID\" : \"TEXT\");\n }\n case \"reference\": {\n const refProp = prop as ReferenceProperty;\n const targetCollection = collections.find(c => c.slug === refProp.path || getTableName(c) === refProp.path);\n if (!targetCollection) return \"TEXT\";\n const pkProp = getPrimaryKeyProp(targetCollection);\n return pkProp.type === \"number\" ? \"INTEGER\" : (pkProp.isUuid ? \"UUID\" : \"TEXT\");\n }\n default:\n return \"TEXT\";\n }\n};\n\nexport const generatePostgresDdl = async (\n collections: CollectionConfig[],\n options: { includePolicies?: boolean } = { includePolicies: true }\n): Promise<string> => {\n let ddl = \"-- This file is auto-generated by the Rebase DDL generator. Do not edit manually.\\n\\n\";\n\n // 1. Create custom schemas\n const uniqueSchemas = Array.from(new Set([\n \"auth\",\n ...collections.map(c => isPostgresCollectionConfig(c) ? c.schema : undefined).filter(Boolean)\n ]));\n uniqueSchemas.forEach(schema => {\n if (schema) ddl += `CREATE SCHEMA IF NOT EXISTS \"${schema}\";\\n`;\n });\n if (uniqueSchemas.length > 0) ddl += \"\\n\";\n\n // 2. Generate Enums\n collections.forEach(collection => {\n const collectionTable = getTableName(collection);\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {\n if ((\"enum\" in prop) && (prop.type === \"string\" || prop.type === \"number\") && prop.enum) {\n const enumDbName = `${collectionTable}_${resolveColumnName(propName, prop)}`;\n const values = Array.isArray(prop.enum)\n ? (prop.enum as (string | number | { id: string | number })[]).map((v: string | number | { id: string | number }) =>\n String(typeof v === \"object\" && v !== null && \"id\" in v ? v.id : v)\n )\n : Object.keys(prop.enum);\n if (values.length > 0) {\n ddl += `CREATE TYPE \"${schema}\".\"${enumDbName}\" AS ENUM (${values.map(v => `'${v}'`).join(\", \")});\\n`;\n }\n }\n });\n });\n if (ddl.endsWith(\";\\n\")) ddl += \"\\n\";\n\n // Junction policy derivation needs every declaring side of each junction,\n // not just the first relation that reached it in the walk below.\n const junctionSpecs = resolveJunctionSpecs(collections);\n\n const allTablesToGenerate = new Map<string, {\n collection: CollectionConfig,\n isJunction?: boolean,\n relation?: ResolvedRelation,\n sourceCollection?: CollectionConfig\n }>();\n\n // Identify all tables\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (tableName) {\n allTablesToGenerate.set(tableName, { collection });\n }\n\n const resolvedRelations = resolveCollectionRelations(collection);\n for (const relation of Object.values(resolvedRelations)) {\n if (isManyToMany(relation)) {\n const junctionTableName = relation.through.table;\n if (!allTablesToGenerate.has(junctionTableName)) {\n allTablesToGenerate.set(junctionTableName, {\n collection: {\n table: junctionTableName,\n properties: {}\n } as CollectionConfig,\n isJunction: true,\n relation: relation,\n sourceCollection: collection\n });\n }\n }\n }\n }\n\n // 3. Generate tables\n const fkStatements: string[] = [];\n // Policies are emitted after every CREATE TABLE, like the FK constraints:\n // a policy may reference other tables (a junction's derived policies always\n // reference both endpoints; `policy.existsIn` references a join table), and\n // CREATE POLICY validates those relations at creation time.\n const policyStatements: string[] = [];\n for (const [tableName, {\n collection,\n isJunction,\n relation,\n sourceCollection\n }] of allTablesToGenerate.entries()) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const baseTableName = tableName.includes(\".\") ? tableName.split(\".\").pop()! : tableName;\n\n if (isJunction && relation && sourceCollection && isManyToMany(relation)) {\n const targetCollection = relation.target();\n const sourceTable = getTableName(sourceCollection);\n const targetTable = getTableName(targetCollection);\n const sourceSchema = isPostgresCollectionConfig(sourceCollection) && sourceCollection.schema ? sourceCollection.schema : \"public\";\n const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : \"public\";\n const { sourceColumn, targetColumn } = relation.through;\n\n // TEXT, matching the string default: a junction column has to have the\n // same type as the primary key it references.\n const sourceColType = isNumericId(sourceCollection) ? \"INTEGER\" : (getPrimaryKeyProp(sourceCollection).isUuid ? \"UUID\" : \"TEXT\");\n const targetColType = isNumericId(targetCollection) ? \"INTEGER\" : (getPrimaryKeyProp(targetCollection).isUuid ? \"UUID\" : \"TEXT\");\n const sourceId = getPrimaryKeyName(sourceCollection);\n const targetId = getPrimaryKeyName(targetCollection);\n\n const onDelete = relation.onDelete ?? \"CASCADE\";\n\n ddl += `CREATE TABLE \"${schema}\".\"${baseTableName}\" (\\n`;\n ddl += ` \"${sourceColumn}\" ${sourceColType} NOT NULL,\\n`;\n ddl += ` \"${targetColumn}\" ${targetColType} NOT NULL,\\n`;\n ddl += ` PRIMARY KEY (\"${sourceColumn}\", \"${targetColumn}\")\\n`;\n ddl += `);\\n\\n`;\n\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${baseTableName}_${sourceColumn}_fkey\" FOREIGN KEY (\"${sourceColumn}\") REFERENCES \"${sourceSchema}\".\"${sourceTable}\" (\"${sourceId}\") ON DELETE ${onDelete.toUpperCase()};`);\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${baseTableName}_${targetColumn}_fkey\" FOREIGN KEY (\"${targetColumn}\") REFERENCES \"${targetSchema}\".\"${targetTable}\" (\"${targetId}\") ON DELETE ${onDelete.toUpperCase()};`);\n\n if (options.includePolicies) {\n // Junction tables are generated tables like any other: locked by\n // default, with derived policies — reads follow the endpoints'\n // visibility, writes follow the declaring side's update rules.\n // Without this they were the one kind of generated table with no\n // RLS at all, readable and writable by every signed-in user.\n ddl += `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const spec = junctionSpecs.get(baseTableName);\n if (spec) {\n const junctionCollection = getJunctionCollectionConfig(spec);\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n getJunctionSecurityRules(spec).forEach((rule: SecurityRule) => {\n policyStatements.push(generatePolicyDdl(junctionCollection, rule, resolveCollection));\n });\n }\n }\n } else if (!isJunction) {\n ddl += `CREATE TABLE \"${schema}\".\"${baseTableName}\" (\\n`;\n const columns: string[] = [];\n\n Object.entries(collection.properties ?? {}).forEach(([propName, prop]) => {\n if (prop.type === \"relation\") {\n const refProp = prop as RelationProperty;\n const resolvedRelations = resolveCollectionRelations(collection);\n const relInfo = findRelation(resolvedRelations, refProp.relation?.relationName ?? propName);\n\n if (relInfo?.kind !== \"belongsTo\") {\n return;\n }\n\n if (collection.properties[relInfo.localKey] && propName !== relInfo.localKey) {\n return;\n }\n\n let targetCollection: CollectionConfig;\n try {\n targetCollection = relInfo.target();\n } catch {\n return;\n }\n\n const targetTable = getTableName(targetCollection);\n const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : \"public\";\n const targetId = getPrimaryKeyName(targetCollection);\n const fkColType = getSqlColumnType(propName, prop, collection, collections);\n \n const onUpdate = relInfo.onUpdate ? ` ON UPDATE ${relInfo.onUpdate.toUpperCase()}` : \"\";\n const required = prop.validation?.required;\n const onDeleteVal = relInfo.onDelete ?? (required ? \"CASCADE\" : \"SET NULL\");\n \n let colDef = ` \"${relInfo.localKey}\" ${fkColType}`;\n if (required) colDef += \" NOT NULL\";\n columns.push(colDef);\n\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${baseTableName}_${relInfo.localKey}_fkey\" FOREIGN KEY (\"${relInfo.localKey}\") REFERENCES \"${targetSchema}\".\"${targetTable}\" (\"${targetId}\") ON DELETE ${onDeleteVal.toUpperCase()}${onUpdate};`);\n } else if (prop.type === \"reference\") {\n const refProp = prop as ReferenceProperty;\n const targetCollection = collections.find(c => c.slug === refProp.path || getTableName(c) === refProp.path);\n const colName = resolveColumnName(propName, prop);\n const colType = getSqlColumnType(propName, prop, collection, collections);\n const required = prop.validation?.required;\n\n if (!targetCollection) {\n let colDef = ` \"${colName}\" ${colType}`;\n if (required) colDef += \" NOT NULL\";\n columns.push(colDef);\n } else {\n const targetTable = getTableName(targetCollection);\n const targetSchema = isPostgresCollectionConfig(targetCollection) && targetCollection.schema ? targetCollection.schema : \"public\";\n const targetId = getPrimaryKeyName(targetCollection);\n const onDelete = required ? \"CASCADE\" : \"SET NULL\";\n\n let colDef = ` \"${colName}\" ${colType}`;\n if (required) colDef += \" NOT NULL\";\n columns.push(colDef);\n\n fkStatements.push(`ALTER TABLE \"${schema}\".\"${baseTableName}\" ADD CONSTRAINT \"${baseTableName}_${colName}_fkey\" FOREIGN KEY (\"${colName}\") REFERENCES \"${targetSchema}\".\"${targetTable}\" (\"${targetId}\") ON DELETE ${onDelete.toUpperCase()};`);\n }\n } else {\n const colName = resolveColumnName(propName, prop);\n const colType = getSqlColumnType(propName, prop, collection, collections);\n let colDef = ` \"${colName}\" ${colType}`;\n\n if (isIdProperty(propName, prop, collection)) {\n colDef += \" PRIMARY KEY\";\n }\n\n if (\"isId\" in prop && prop.isId !== \"manual\" && prop.isId !== true && prop.isId !== \"increment\") {\n if (prop.isId === \"uuid\") {\n colDef += \" DEFAULT gen_random_uuid()\";\n } else if (prop.isId === \"cuid\") {\n colDef += \" DEFAULT cuid()\";\n } else if (typeof prop.isId === \"string\") {\n colDef += ` DEFAULT ${prop.isId}`;\n }\n }\n\n if (!isIdProperty(propName, prop, collection) && prop.validation?.unique) {\n colDef += \" UNIQUE\";\n }\n\n if (prop.type === \"date\") {\n const dateProp = prop as DateProperty;\n if (dateProp.autoValue === \"on_create\" || dateProp.autoValue === \"on_update\") {\n colDef += \" DEFAULT now()\";\n }\n }\n\n if (prop.validation?.required && !colDef.includes(\"PRIMARY KEY\")) {\n colDef += \" NOT NULL\";\n }\n\n columns.push(colDef);\n }\n });\n\n // Backwards compatibility: add default id primary key if missing\n const hasPk = columns.some(c => c.includes(\"PRIMARY KEY\"));\n if (!hasPk) {\n columns.unshift(' \"id\" TEXT PRIMARY KEY');\n }\n\n ddl += columns.join(\",\\n\");\n ddl += `\\n);\\n\\n`;\n\n if (options.includePolicies) {\n // Enable RLS and add Policies. No FORCE: authenticated requests\n // run as the non-owner `rebase_user` role, which plain ENABLE\n // already binds. The owner (server context) must bypass — it is\n // the trusted plane (auth flows, dataAsAdmin).\n ddl += `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const securityRules = getEffectiveSecurityRules(collection);\n if (securityRules.length > 0) {\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n securityRules.forEach((rule: SecurityRule) => {\n policyStatements.push(generatePolicyDdl(collection, rule, resolveCollection));\n });\n }\n }\n }\n }\n\n if (fkStatements.length > 0) {\n ddl += \"-- Foreign Key Constraints\\n\";\n ddl += fkStatements.join(\"\\n\") + \"\\n\\n\";\n }\n\n if (policyStatements.length > 0) {\n ddl += \"-- Row Level Security Policies\\n\";\n ddl += policyStatements.join(\"\");\n ddl += \"\\n\";\n }\n\n return ddl;\n};\n\n/** The RLS statements one declared collection's table needs, ready to run. */\nexport interface CollectionPolicyPlan {\n /** The table's schema (e.g. `public`, `rebase`). */\n schema: string;\n /** The bare table name, no schema prefix. */\n table: string;\n /** `schema.table` — matches the keys `readExistingSchema` returns. */\n qualified: string;\n /** `ALTER TABLE … ENABLE ROW LEVEL SECURITY;` — locked by default. */\n enableRls: string;\n /** `DROP POLICY IF EXISTS` / `CREATE POLICY` statements, in order. */\n policyStatements: string[];\n}\n\n/**\n * The per-table RLS plan for the *declared* collections, as executable\n * statements — what the managed runtime applies at boot so a freshly\n * provisioned tenant database serves data instead of 401ing every read.\n *\n * Mirrors the non-junction half of {@link generatePostgresPoliciesDdl} exactly\n * (same `generatePolicyStatements`, same enable-RLS, same effective rules), so\n * boot and `db push` produce identical policies from identical collections.\n *\n * Junction tables are deliberately excluded: they are derived from `through`\n * relations, not declared collections, and the boot-time *table* creator\n * (`ensureCollectionTables`) does not create them either — enabling RLS on a\n * table that boot never created would fail. Their RLS stays a `db push` /\n * `db migrate` concern, which is where those tables get created in the first\n * place. `db push` still applies junction policies via the string generator.\n */\nexport const planCollectionPolicies = (collections: CollectionConfig[]): CollectionPolicyPlan[] => {\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n const plans: CollectionPolicyPlan[] = [];\n const seen = new Set<string>();\n\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (!tableName) continue;\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const baseTableName = tableName.includes(\".\") ? tableName.split(\".\").pop()! : tableName;\n const qualified = `${schema}.${baseTableName}`;\n if (seen.has(qualified)) continue;\n seen.add(qualified);\n\n const policyStatements: string[] = [];\n for (const rule of getEffectiveSecurityRules(collection)) {\n policyStatements.push(...generatePolicyStatements(collection, rule, resolveCollection));\n }\n\n plans.push({\n schema,\n table: baseTableName,\n qualified,\n enableRls: `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;`,\n policyStatements\n });\n }\n\n return plans;\n};\n\nexport const generatePostgresPoliciesDdl = (collections: CollectionConfig[]): string => {\n let ddl = \"-- This file contains RLS policies generated by Rebase. Applied separately from migrations.\\n\\n\";\n\n const allTablesToGenerate = new Map<string, {\n collection: CollectionConfig\n }>();\n\n for (const collection of collections) {\n const tableName = getTableName(collection);\n if (tableName) {\n allTablesToGenerate.set(tableName, { collection });\n }\n }\n\n for (const [tableName, { collection }] of allTablesToGenerate.entries()) {\n const schema = isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n const baseTableName = tableName.includes(\".\") ? tableName.split(\".\").pop()! : tableName;\n\n // No FORCE: user requests run as the non-owner `rebase_user` role\n // (plain ENABLE binds them); the owner is the trusted server context.\n ddl += `ALTER TABLE \"${schema}\".\"${baseTableName}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const securityRules = getEffectiveSecurityRules(collection);\n if (securityRules.length > 0) {\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n const injectedNames = new Set(getInjectedSecurityRules(collection).map((rule) => rule.name));\n\n securityRules.forEach((rule: SecurityRule) => {\n // Say which policies the author did not write. They are permissive,\n // so they OR with the declared rules and widen the final ACL beyond\n // what `securityRules` reads like — and re-appear after any manual\n // DROP, because a push asserts the declared state.\n if (rule.name && injectedNames.has(rule.name)) {\n ddl += `-- Injected by Rebase (not from this collection's securityRules).\\n`;\n ddl += `-- Set \\`disableDefaultPolicies: true\\` on \"${collection.slug}\" to drop these and own its RLS outright.\\n`;\n }\n ddl += generatePolicyDdl(collection, rule, resolveCollection);\n });\n ddl += \"\\n\";\n }\n }\n\n // Junction tables are generated from `through` relations, not declared as\n // collections, so the walk above never sees them. They get the same\n // treatment as any generated table: locked by default, with derived\n // policies — reads follow the endpoints, writes follow the declaring\n // side's update rules.\n const junctionSpecs = resolveJunctionSpecs(collections);\n for (const spec of junctionSpecs.values()) {\n ddl += `ALTER TABLE \"${spec.schema}\".\"${spec.table}\" ENABLE ROW LEVEL SECURITY;\\n`;\n ddl += `\\n`;\n\n const junctionRules = getJunctionSecurityRules(spec);\n if (junctionRules.length === 0) continue;\n\n const junctionCollection = getJunctionCollectionConfig(spec);\n const resolveCollection: ResolveCollection = (slug) => collections.find(c => c.slug === slug || getTableName(c) === slug);\n const declaringSlugs = spec.declaringSides.map(s => s.collection.slug).join('\", \"');\n\n ddl += `-- Derived by Rebase for the junction \"${spec.table}\" (no collection declares it).\\n`;\n ddl += `-- Reads require both endpoint rows to be visible; writes follow the update\\n`;\n ddl += `-- rules of \"${declaringSlugs}\". Set \\`disableDefaultPolicies: true\\` on the\\n`;\n ddl += `-- declaring collection(s) to drop these and police the junction yourself.\\n`;\n junctionRules.forEach((rule: SecurityRule) => {\n ddl += generatePolicyDdl(junctionCollection, rule, resolveCollection);\n });\n ddl += \"\\n\";\n }\n\n return ddl;\n};\n\n","/**\n * Bringing a database up to date with a bundle's collections, additively.\n *\n * ## Why this exists\n *\n * A managed runtime boots someone else's compiled project against a database it\n * has never seen. Auth tables are ensured at boot already, but collection tables\n * were not created by anything: the platform ran the app and every `/api/data/*`\n * request answered 500 on a missing relation. `rebase db push` cannot help — it\n * is an Atlas-driven CLI command, and the runtime image ships no CLI.\n *\n * ## Why additive-only, forever\n *\n * This runs unattended, against a database with customers' data in it, with no\n * human reading a diff. So it may only ever do things that cannot lose data:\n * create a missing table, add a missing column, create a missing enum type.\n *\n * It will **never** drop a table or a column, narrow a type, or alter a\n * constraint. A removed field leaves its column behind; a renamed field looks\n * like an addition and the old column stays. That is the correct trade for an\n * automated path — the alternative is an unattended process that can silently\n * destroy a column, which is precisely the failure `db push` was hardened\n * against. Destructive changes stay a deliberate, human-reviewed migration.\n *\n * Because of that, this is safe to run on every boot, and re-running it is a\n * no-op.\n */\nimport { type CollectionConfig, type Property, isPostgresCollectionConfig } from \"@rebasepro/types\";\nimport { getTableName } from \"@rebasepro/common\";\nimport {\n getSqlColumnType,\n resolveColumnName,\n isIdProperty\n} from \"./generate-postgres-ddl-logic\";\n\n/**\n * The subset of a database handle this needs: run a statement, get rows back.\n *\n * Deliberately parameterless. Everything here is DDL or catalogue reads keyed by\n * schema name, and schema names are identifiers — they cannot be bound as\n * parameters anyway. They are validated against {@link SAFE_IDENTIFIER} before\n * they reach a statement, so a config that somehow carried a quote is refused\n * rather than concatenated.\n */\nexport interface Queryable {\n query<T = unknown>(sql: string): Promise<{ rows: T[] }>;\n}\n\n/** Postgres identifiers this module is willing to interpolate. */\nconst SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/;\n\nfunction assertSafeIdentifier(value: string, what: string): string {\n if (!SAFE_IDENTIFIER.test(value)) {\n throw new Error(`Refusing to build SQL with an unsafe ${what}: ${JSON.stringify(value)}`);\n }\n return value;\n}\n\n/** What the database currently has, as the planner needs it. */\nexport interface ExistingSchema {\n /** `schema.table` → set of column names. */\n tables: Map<string, Set<string>>;\n /** `schema.typename` of every enum type that already exists. */\n enums: Set<string>;\n}\n\nexport interface EnsureAction {\n kind: \"create-enum\" | \"create-table\" | \"add-column\";\n /** Qualified target, for logging: `public.posts` or `public.posts.title`. */\n target: string;\n sql: string;\n}\n\nexport interface EnsurePlan {\n actions: EnsureAction[];\n /** Every statement, in dependency order. Empty when the schema is current. */\n statements: string[];\n}\n\nfunction schemaOf(collection: CollectionConfig): string {\n return isPostgresCollectionConfig(collection) && collection.schema ? collection.schema : \"public\";\n}\n\nfunction qualified(collection: CollectionConfig): string {\n return `${schemaOf(collection)}.${getTableName(collection)}`;\n}\n\n/**\n * Enum types a collection's properties require, as `schema.typename`.\n *\n * Named exactly as the DDL generator names them (`<table>_<column>`), because\n * a column added here has to reference the same type the generator would have\n * created — a second, differently-named type for the same field would be a\n * silent schema fork.\n */\nfunction requiredEnums(collection: CollectionConfig): { name: string; values: string[] }[] {\n const table = getTableName(collection);\n const schema = schemaOf(collection);\n const out: { name: string; values: string[] }[] = [];\n for (const [propName, prop] of Object.entries(collection.properties ?? {})) {\n const p = prop as Property;\n if (!(\"enum\" in p) || !p.enum) continue;\n if (p.type !== \"string\" && p.type !== \"number\") continue;\n const values = (p.enum as unknown[])\n .map(entry =>\n entry && typeof entry === \"object\" && \"id\" in (entry as Record<string, unknown>)\n ? String((entry as Record<string, unknown>).id)\n : String(entry)\n )\n .filter(v => v.length > 0);\n if (values.length === 0) continue;\n out.push({ name: `${schema}.${table}_${resolveColumnName(propName, p)}`, values });\n }\n return out;\n}\n\n/** Single-quote escaping for an enum label. */\nfunction quoteLiteral(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Decide what to add. Pure — the caller supplies what exists and runs the result.\n *\n * Ordering matters and is deliberate: enum types before the tables and columns\n * that reference them, tables before the columns added to other tables (a new\n * table may be the target of a relation), and nothing is emitted twice.\n */\nexport function planCollectionSchemaEnsure(\n collections: CollectionConfig[],\n existing: ExistingSchema\n): EnsurePlan {\n const actions: EnsureAction[] = [];\n const plannedEnums = new Set<string>();\n\n // 1. Enum types. `CREATE TYPE` has no IF NOT EXISTS, so an existing type is\n // skipped by name rather than guarded in SQL.\n for (const collection of collections) {\n for (const { name, values } of requiredEnums(collection)) {\n if (existing.enums.has(name) || plannedEnums.has(name)) continue;\n plannedEnums.add(name);\n const [schema, typeName] = name.split(\".\");\n actions.push({\n kind: \"create-enum\",\n target: name,\n sql: `CREATE TYPE \"${schema}\".\"${typeName}\" AS ENUM (${values.map(quoteLiteral).join(\", \")});`\n });\n }\n }\n\n // 2. Missing tables. Only the identity column is created here; every other\n // column is added by step 3, so a new table and an existing table that\n // gained a field travel the exact same code path. One way to build a\n // column means one way for it to be wrong.\n const created = new Set<string>();\n for (const collection of collections) {\n const key = qualified(collection);\n if (existing.tables.has(key) || created.has(key)) continue;\n created.add(key);\n const schema = schemaOf(collection);\n const table = getTableName(collection);\n const idEntry = Object.entries(collection.properties ?? {}).find(([n, p]) =>\n isIdProperty(n, p as Property, collection)\n );\n const idName = idEntry ? resolveColumnName(idEntry[0], idEntry[1] as Property) : \"id\";\n const idProp = idEntry?.[1] as Property | undefined;\n let idDef: string;\n if (idProp?.type === \"number\") {\n idDef = `\"${idName}\" BIGSERIAL PRIMARY KEY`;\n } else if (\n idProp &&\n idProp.type === \"string\" &&\n (idProp as { isId?: unknown }).isId === \"uuid\"\n ) {\n idDef = `\"${idName}\" UUID PRIMARY KEY DEFAULT gen_random_uuid()`;\n } else {\n idDef = `\"${idName}\" TEXT PRIMARY KEY`;\n }\n actions.push({\n kind: \"create-table\",\n target: key,\n sql: `CREATE TABLE IF NOT EXISTS \"${schema}\".\"${table}\" (${idDef});`\n });\n }\n\n // 3. Missing columns, on both brand-new and pre-existing tables.\n for (const collection of collections) {\n const key = qualified(collection);\n const schema = schemaOf(collection);\n const table = getTableName(collection);\n const present = existing.tables.get(key) ?? new Set<string>();\n for (const [propName, prop] of Object.entries(collection.properties ?? {})) {\n const p = prop as Property;\n if (isIdProperty(propName, p, collection)) continue;\n // A relation's own column is emitted by the DDL generator with a\n // foreign key; adding a bare column here would create the column\n // without the constraint and make the generator's later output\n // disagree with the database. Left to a real migration.\n if (p.type === \"reference\" || p.type === \"relation\") continue;\n const column = resolveColumnName(propName, p);\n if (present.has(column)) continue;\n const type = getSqlColumnType(propName, p, collection, collections);\n actions.push({\n kind: \"add-column\",\n target: `${key}.${column}`,\n // Never NOT NULL: an existing table with rows cannot take a\n // non-null column without a default, and inventing one would be\n // guessing at the customer's data.\n sql: `ALTER TABLE \"${schema}\".\"${table}\" ADD COLUMN IF NOT EXISTS \"${column}\" ${type};`\n });\n }\n }\n\n return { actions, statements: actions.map(a => a.sql) };\n}\n\n/** Read what the database has, for the schemas the collections live in. */\nexport async function readExistingSchema(\n client: Queryable,\n schemas: string[]\n): Promise<ExistingSchema> {\n const tables = new Map<string, Set<string>>();\n const enums = new Set<string>();\n if (schemas.length === 0) return { tables, enums };\n\n const inList = schemas\n .map(schema => `'${assertSafeIdentifier(schema, \"schema name\")}'`)\n .join(\", \");\n\n const { rows: columns } = await client.query<{\n table_schema: string;\n table_name: string;\n column_name: string;\n }>(\n `SELECT table_schema, table_name, column_name\n FROM information_schema.columns\n WHERE table_schema IN (${inList})`\n );\n for (const row of columns) {\n const key = `${row.table_schema}.${row.table_name}`;\n if (!tables.has(key)) tables.set(key, new Set());\n tables.get(key)!.add(row.column_name);\n }\n\n const { rows: enumRows } = await client.query<{ schema: string; name: string }>(\n `SELECT n.nspname AS schema, t.typname AS name\n FROM pg_type t\n JOIN pg_namespace n ON t.typnamespace = n.oid\n WHERE t.typtype = 'e' AND n.nspname IN (${inList})`\n );\n for (const row of enumRows) enums.add(`${row.schema}.${row.name}`);\n\n return { tables, enums };\n}\n\n/**\n * Bring the database up to date. Returns what it did.\n *\n * Each statement runs on its own rather than in one transaction: they are all\n * independently safe and idempotent, and a single failure (an enum label that\n * cannot be added, say) should not roll back the tables that were created fine.\n * The error is surfaced with the statement that caused it.\n */\nexport async function ensureCollectionTables(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void\n): Promise<EnsurePlan> {\n const schemas = Array.from(new Set(collections.map(schemaOf)));\n for (const schema of schemas) {\n assertSafeIdentifier(schema, \"schema name\");\n if (schema !== \"public\") {\n await client.query(`CREATE SCHEMA IF NOT EXISTS \"${schema}\";`);\n }\n }\n\n const existing = await readExistingSchema(client, schemas);\n const plan = planCollectionSchemaEnsure(collections, existing);\n\n if (plan.actions.length === 0) {\n log?.(\"Schema is up to date; nothing to create.\");\n return plan;\n }\n\n for (const action of plan.actions) {\n try {\n await client.query(action.sql);\n log?.(`${action.kind}: ${action.target}`);\n } catch (err) {\n throw new Error(\n `Failed to ${action.kind} ${action.target}: ` +\n `${err instanceof Error ? err.message : String(err)}\\n ${action.sql}`\n );\n }\n }\n return plan;\n}\n"],"mappings":";;;;;;AAMA,IAAa,qBAAqB,UAAkB,SAAmC;CACnF,IAAI,QAAQ,gBAAgB,QAAQ,OAAO,KAAK,eAAe,UAC3D,OAAO,KAAK;CAEhB,OAAO,YAAY,QAAQ;AAC/B;AAEA,IAAM,qBAAqB,eAA+F;CACtH,IAAI,WAAW,YAAY;EACvB,MAAM,cAAc,OAAO,QAAQ,WAAW,UAAU,CAAC,CAAC,MAAM,CAAC,GAAG,UAAU,UAAW,QAA8B,QAAS,KAA4C,IAAI,CAAC;EACjL,IAAI,aAAa;GACb,MAAM,OAAO,YAAY;GACzB,MAAM,SAAS,KAAK,SAAS,YAAY,UAAU,QAAS,KAAmC,SAAS;GACxG,OAAO;IAAE,MAAM,YAAY;IAAI,MAAM,KAAK,SAAS,WAAW,WAAW;IAAU;GAAO;EAC9F;CACJ;CACA,MAAM,SAAS,WAAW,aAAa;CACvC,IAAI,QAAQ,SAAS,UACjB,OAAO;EAAE,MAAM;EAAM,MAAM;EAAU,QAAQ;CAAM;CAGvD,OAAO;EAAE,MAAM;EAAM,MAAM;EAAU,QADtB,QAAQ,SAAS,YAAY,UAAU,UAAW,OAAqC,SAAS;CAClD;AACjE;AAUA,IAAa,gBAAgB,UAAkB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