@happyvertical/smrt-core 0.40.69 → 0.41.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +29 -4
- package/README.md +20 -1
- package/agents/change-feed.md +1 -1
- package/agents/query-bounds.md +45 -0
- package/agents/schema-paths.md +786 -0
- package/dist/browser.d.ts +1 -0
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +5 -3
- package/dist/cascade.d.ts +120 -0
- package/dist/cascade.d.ts.map +1 -0
- package/dist/cascade.js +430 -0
- package/dist/cascade.js.map +1 -0
- package/dist/change-feed.d.ts +34 -2
- package/dist/change-feed.d.ts.map +1 -1
- package/dist/change-feed.js +52 -11
- package/dist/change-feed.js.map +1 -1
- package/dist/class.d.ts +36 -3
- package/dist/class.d.ts.map +1 -1
- package/dist/class.js +87 -9
- package/dist/class.js.map +1 -1
- package/dist/collection-cache.js +0 -0
- package/dist/collection-cache.js.map +1 -1
- package/dist/collection.d.ts +130 -2
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +290 -57
- package/dist/collection.js.map +1 -1
- package/dist/config.d.ts +10 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js.map +1 -1
- package/dist/database.d.ts +8 -0
- package/dist/database.d.ts.map +1 -1
- package/dist/database.js +16 -8
- package/dist/database.js.map +1 -1
- package/dist/db-errors.d.ts +105 -0
- package/dist/db-errors.d.ts.map +1 -0
- package/dist/db-errors.js +382 -0
- package/dist/db-errors.js.map +1 -0
- package/dist/decorators/index.d.ts +80 -6
- package/dist/decorators/index.d.ts.map +1 -1
- package/dist/decorators/index.js +102 -12
- package/dist/decorators/index.js.map +1 -1
- package/dist/dispatch/bus.d.ts.map +1 -1
- package/dist/dispatch/bus.js +4 -3
- package/dist/dispatch/bus.js.map +1 -1
- package/dist/dispatch/collections/Dispatches.d.ts.map +1 -1
- package/dist/dispatch/collections/Dispatches.js +19 -4
- package/dist/dispatch/collections/Dispatches.js.map +1 -1
- package/dist/dispatch/types.d.ts +5 -0
- package/dist/dispatch/types.d.ts.map +1 -1
- package/dist/embedded-write-queue.d.ts +46 -0
- package/dist/embedded-write-queue.d.ts.map +1 -0
- package/dist/embedded-write-queue.js +66 -0
- package/dist/embedded-write-queue.js.map +1 -0
- package/dist/embeddings/storage.d.ts +7 -0
- package/dist/embeddings/storage.d.ts.map +1 -1
- package/dist/embeddings/storage.js +29 -12
- package/dist/embeddings/storage.js.map +1 -1
- package/dist/errors.d.ts +31 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +34 -2
- package/dist/errors.js.map +1 -1
- package/dist/generators/changes-route.d.ts.map +1 -1
- package/dist/generators/changes-route.js +6 -3
- package/dist/generators/changes-route.js.map +1 -1
- package/dist/generators/mcp-runtime-template.d.ts +8 -0
- package/dist/generators/mcp-runtime-template.d.ts.map +1 -1
- package/dist/generators/mcp-runtime-template.js +38 -4
- package/dist/generators/mcp-runtime-template.js.map +1 -1
- package/dist/generators/mcp.d.ts +16 -0
- package/dist/generators/mcp.d.ts.map +1 -1
- package/dist/generators/mcp.js +41 -3
- package/dist/generators/mcp.js.map +1 -1
- package/dist/generators/rest.d.ts +22 -0
- package/dist/generators/rest.d.ts.map +1 -1
- package/dist/generators/rest.js +34 -3
- package/dist/generators/rest.js.map +1 -1
- package/dist/hierarchical.js +1 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -5
- package/dist/interceptors.d.ts +21 -0
- package/dist/interceptors.d.ts.map +1 -1
- package/dist/interceptors.js +27 -1
- package/dist/interceptors.js.map +1 -1
- package/dist/manifest/generator.d.ts.map +1 -1
- package/dist/manifest/generator.js +4 -7
- package/dist/manifest/generator.js.map +1 -1
- package/dist/manifest/static-manifest.js +10 -10
- package/dist/manifest/static-manifest.js.map +1 -1
- package/dist/manifest/store.js +1 -1
- package/dist/manifest/store.js.map +1 -1
- package/dist/manifest.json +19 -19
- package/dist/migrations/differ.d.ts +211 -9
- package/dist/migrations/differ.d.ts.map +1 -1
- package/dist/migrations/differ.js +613 -50
- package/dist/migrations/differ.js.map +1 -1
- package/dist/migrations/generator.d.ts +31 -4
- package/dist/migrations/generator.d.ts.map +1 -1
- package/dist/migrations/generator.js +49 -5
- package/dist/migrations/generator.js.map +1 -1
- package/dist/migrations/index.d.ts +4 -2
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/migrations/index.js +6 -3
- package/dist/migrations/minor-units.d.ts +162 -0
- package/dist/migrations/minor-units.d.ts.map +1 -0
- package/dist/migrations/minor-units.js +381 -0
- package/dist/migrations/minor-units.js.map +1 -0
- package/dist/migrations/orchestrate.js +35 -6
- package/dist/migrations/orchestrate.js.map +1 -1
- package/dist/migrations/sqlite-rebuild.d.ts +142 -0
- package/dist/migrations/sqlite-rebuild.d.ts.map +1 -0
- package/dist/migrations/sqlite-rebuild.js +514 -0
- package/dist/migrations/sqlite-rebuild.js.map +1 -0
- package/dist/migrations/tracker.d.ts +114 -1
- package/dist/migrations/tracker.d.ts.map +1 -1
- package/dist/migrations/tracker.js +331 -16
- package/dist/migrations/tracker.js.map +1 -1
- package/dist/migrations/types.d.ts +19 -4
- package/dist/migrations/types.d.ts.map +1 -1
- package/dist/migrations.js +6 -3
- package/dist/object.d.ts +142 -10
- package/dist/object.d.ts.map +1 -1
- package/dist/object.js +196 -41
- package/dist/object.js.map +1 -1
- package/dist/postgres-timeouts.d.ts +240 -0
- package/dist/postgres-timeouts.d.ts.map +1 -0
- package/dist/postgres-timeouts.js +204 -0
- package/dist/postgres-timeouts.js.map +1 -0
- package/dist/query-bounds.d.ts +101 -0
- package/dist/query-bounds.d.ts.map +1 -0
- package/dist/query-bounds.js +177 -0
- package/dist/query-bounds.js.map +1 -0
- package/dist/registry/class-registration.d.ts.map +1 -1
- package/dist/registry/class-registration.js +3 -1
- package/dist/registry/class-registration.js.map +1 -1
- package/dist/registry/manifest-field-merge.d.ts +12 -0
- package/dist/registry/manifest-field-merge.d.ts.map +1 -1
- package/dist/registry/manifest-field-merge.js +14 -2
- package/dist/registry/manifest-field-merge.js.map +1 -1
- package/dist/registry/schema-builder.d.ts +22 -1
- package/dist/registry/schema-builder.d.ts.map +1 -1
- package/dist/registry/schema-builder.js +205 -165
- package/dist/registry/schema-builder.js.map +1 -1
- package/dist/registry/types.d.ts +35 -3
- package/dist/registry/types.d.ts.map +1 -1
- package/dist/registry.d.ts +41 -46
- package/dist/registry.d.ts.map +1 -1
- package/dist/registry.js +61 -83
- package/dist/registry.js.map +1 -1
- package/dist/scanner/manifest-generator.d.ts +45 -0
- package/dist/scanner/manifest-generator.d.ts.map +1 -1
- package/dist/scanner/manifest-generator.js +92 -28
- package/dist/scanner/manifest-generator.js.map +1 -1
- package/dist/scanner/types.d.ts +5 -0
- package/dist/scanner/types.d.ts.map +1 -1
- package/dist/scanner/types.js.map +1 -1
- package/dist/schema/conflict-target.d.ts +104 -0
- package/dist/schema/conflict-target.d.ts.map +1 -0
- package/dist/schema/conflict-target.js +129 -0
- package/dist/schema/conflict-target.js.map +1 -0
- package/dist/schema/ddl/base-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/base-strategy.js +2 -2
- package/dist/schema/ddl/base-strategy.js.map +1 -1
- package/dist/schema/ddl/duckdb-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/duckdb-strategy.js +2 -1
- package/dist/schema/ddl/duckdb-strategy.js.map +1 -1
- package/dist/schema/ddl/postgres-strategy.d.ts.map +1 -1
- package/dist/schema/ddl/postgres-strategy.js +12 -1
- package/dist/schema/ddl/postgres-strategy.js.map +1 -1
- package/dist/schema/generator.d.ts +307 -6
- package/dist/schema/generator.d.ts.map +1 -1
- package/dist/schema/generator.js +510 -87
- package/dist/schema/generator.js.map +1 -1
- package/dist/schema/index-utils.d.ts +120 -0
- package/dist/schema/index-utils.d.ts.map +1 -1
- package/dist/schema/index-utils.js +242 -1
- package/dist/schema/index-utils.js.map +1 -1
- package/dist/schema/index.d.ts +3 -0
- package/dist/schema/index.d.ts.map +1 -1
- package/dist/schema/index.js +4 -1
- package/dist/schema/live-parity.d.ts +90 -0
- package/dist/schema/live-parity.d.ts.map +1 -0
- package/dist/schema/live-parity.js +602 -0
- package/dist/schema/live-parity.js.map +1 -0
- package/dist/schema/manifest-schema.d.ts +121 -0
- package/dist/schema/manifest-schema.d.ts.map +1 -0
- package/dist/schema/manifest-schema.js +267 -0
- package/dist/schema/manifest-schema.js.map +1 -0
- package/dist/schema/schema-aggregator.d.ts +24 -10
- package/dist/schema/schema-aggregator.d.ts.map +1 -1
- package/dist/schema/schema-aggregator.js +35 -90
- package/dist/schema/schema-aggregator.js.map +1 -1
- package/dist/schema/system-table-shapes.d.ts +65 -0
- package/dist/schema/system-table-shapes.d.ts.map +1 -0
- package/dist/schema/system-table-shapes.js +187 -0
- package/dist/schema/system-table-shapes.js.map +1 -0
- package/dist/schema/types.d.ts +103 -4
- package/dist/schema/types.d.ts.map +1 -1
- package/dist/schema/utils.d.ts +2 -1
- package/dist/schema/utils.d.ts.map +1 -1
- package/dist/schema/utils.js +5 -3
- package/dist/schema/utils.js.map +1 -1
- package/dist/schema.js +4 -1
- package/dist/smrt-knowledge.json +20 -8
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/apply.js +9 -16
- package/dist/sync/apply.js.map +1 -1
- package/dist/system/compatibility.d.ts +42 -0
- package/dist/system/compatibility.d.ts.map +1 -1
- package/dist/system/compatibility.js +182 -9
- package/dist/system/compatibility.js.map +1 -1
- package/dist/system/index.d.ts +1 -0
- package/dist/system/index.d.ts.map +1 -1
- package/dist/system/index.js +3 -2
- package/dist/system/retention.d.ts +237 -0
- package/dist/system/retention.d.ts.map +1 -0
- package/dist/system/retention.js +497 -0
- package/dist/system/retention.js.map +1 -0
- package/dist/system/schema.d.ts +100 -15
- package/dist/system/schema.d.ts.map +1 -1
- package/dist/system/schema.js +81 -45
- package/dist/system/schema.js.map +1 -1
- package/dist/system/types.d.ts +0 -2
- package/dist/system/types.d.ts.map +1 -1
- package/dist/testing/database.d.ts.map +1 -1
- package/dist/testing/database.js +1 -0
- package/dist/testing/database.js.map +1 -1
- package/dist/vite-plugin/index.d.ts.map +1 -1
- package/dist/vite-plugin/index.js +4 -9
- package/dist/vite-plugin/index.js.map +1 -1
- package/dist/vite-plugin/sveltekit-generator.d.ts.map +1 -1
- package/dist/vite-plugin/sveltekit-generator.js +71 -5
- package/dist/vite-plugin/sveltekit-generator.js.map +1 -1
- package/dist/vite-plugin/web-collections.d.ts.map +1 -1
- package/dist/vite-plugin/web-collections.js +6 -4
- package/dist/vite-plugin/web-collections.js.map +1 -1
- package/package.json +5 -5
package/dist/schema/generator.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { classnameToTablename } from "../utils/naming.js";
|
|
1
2
|
import { formatDefaultValue, quoteIdentifier, quoteStringLiteral } from "./sql-identifiers.js";
|
|
3
|
+
import { assertIdentifierFits, enforceIdentifierLimits, shortenIdentifier } from "./index-utils.js";
|
|
2
4
|
import { getDDLStrategy } from "./ddl/index.js";
|
|
3
|
-
import {
|
|
5
|
+
import { conflictIndexName, resolveConflictColumns, resolveTenantColumn, servesSlugLookup } from "./conflict-target.js";
|
|
4
6
|
import { createHash } from "node:crypto";
|
|
5
7
|
//#region src/schema/generator.ts
|
|
6
8
|
/**
|
|
@@ -17,14 +19,21 @@ var SchemaGenerator = class {
|
|
|
17
19
|
const indexes = this.generateIndexes(objectDef, columns);
|
|
18
20
|
const triggers = this.generateTriggers(objectDef, tableName);
|
|
19
21
|
const foreignKeys = this.extractForeignKeys(columns);
|
|
22
|
+
const dependencies = this.extractDependencies(objectDef, foreignKeys);
|
|
23
|
+
const version = this.generateVersion(objectDef);
|
|
24
|
+
this.ensureDefaultListOrderingIndex(indexes, columns, tableName);
|
|
25
|
+
this.ensurePolymorphicAssociationIndex(indexes, columns, tableName);
|
|
26
|
+
this.ensureReferenceColumnIndexes(indexes, columns, tableName);
|
|
27
|
+
enforceIdentifierLimits(tableName, indexes);
|
|
28
|
+
for (const trigger of triggers) trigger.name = shortenIdentifier(trigger.name);
|
|
20
29
|
return {
|
|
21
30
|
tableName,
|
|
22
31
|
columns,
|
|
23
32
|
indexes,
|
|
24
33
|
triggers,
|
|
25
34
|
foreignKeys,
|
|
26
|
-
dependencies
|
|
27
|
-
version
|
|
35
|
+
dependencies,
|
|
36
|
+
version,
|
|
28
37
|
packageName: this.extractPackageName(objectDef.filePath),
|
|
29
38
|
baseClass: objectDef.extends
|
|
30
39
|
};
|
|
@@ -138,6 +147,412 @@ var SchemaGenerator = class {
|
|
|
138
147
|
return columns;
|
|
139
148
|
}
|
|
140
149
|
/**
|
|
150
|
+
* Whether an existing index already leads with `leadingColumns`, in order.
|
|
151
|
+
*
|
|
152
|
+
* Only an UNQUALIFIED index (no partial `WHERE`, no JSON-path expression)
|
|
153
|
+
* counts. A partial index such as `... WHERE _meta_type = 'Article'` cannot
|
|
154
|
+
* serve a base-class polymorphic query, which carries no subtype predicate,
|
|
155
|
+
* so it must not suppress the standalone index (#2359, review of #2384).
|
|
156
|
+
*
|
|
157
|
+
* A B-tree serves any prefix of its column list, so an index over
|
|
158
|
+
* `(tenant_id, created_at, status)` covers both `(tenant_id)` equality
|
|
159
|
+
* lookups and `(tenant_id, created_at)` ordering — hence the prefix test
|
|
160
|
+
* rather than an exact match (#2363).
|
|
161
|
+
*/
|
|
162
|
+
hasUnqualifiedLeadingColumns(indexes, leadingColumns) {
|
|
163
|
+
return indexes.some((index) => !index.where && !index.jsonPath && (index.columns?.length ?? 0) >= leadingColumns.length && leadingColumns.every((column, i) => index.columns[i] === column));
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Whether an existing index already serves equality lookups on `column`.
|
|
167
|
+
*
|
|
168
|
+
* Single-column shorthand for {@link hasUnqualifiedLeadingColumns}.
|
|
169
|
+
*/
|
|
170
|
+
hasUnqualifiedLeadingIndex(indexes, column) {
|
|
171
|
+
return this.hasUnqualifiedLeadingColumns(indexes, [column]);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* The column list of the default list-ordering index for a table.
|
|
175
|
+
*
|
|
176
|
+
* Every generated list surface — REST, MCP, and the SvelteKit list route —
|
|
177
|
+
* pages with `ORDER BY created_at DESC, <pk> ASC` (`DEFAULT_LIST_ORDER_BY`,
|
|
178
|
+
* #2367). On a tenant-scoped table that page is always preceded by a
|
|
179
|
+
* `tenant_id = ?` equality filter from the tenancy interceptor, so the
|
|
180
|
+
* serving index leads with the tenant column and orders inside it.
|
|
181
|
+
*
|
|
182
|
+
* `created_at` is generator-owned on every path — a declared `createdAt`
|
|
183
|
+
* field is rewritten to the same `TIMESTAMP NOT NULL DEFAULT
|
|
184
|
+
* current_timestamp` column — so it is never a primary key and never
|
|
185
|
+
* inline-UNIQUE. That is why only `indexes` needs checking for existing
|
|
186
|
+
* coverage: no constraint-backed index can already order this column.
|
|
187
|
+
*
|
|
188
|
+
* Returns `null` when the table has no `created_at` column (no path emits
|
|
189
|
+
* such a table today, but the helper stays total).
|
|
190
|
+
*/
|
|
191
|
+
getDefaultListOrderingColumns(columns) {
|
|
192
|
+
if (!columns.created_at) return null;
|
|
193
|
+
const tenantColumn = Object.entries(columns).find(([, columnDef]) => columnDef?.referenceKind === "tenantId")?.[0];
|
|
194
|
+
return tenantColumn ? [tenantColumn, "created_at"] : ["created_at"];
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Ensure the table can serve its own default list page from an index.
|
|
198
|
+
*
|
|
199
|
+
* Generated REST/MCP/SvelteKit list routes all page with
|
|
200
|
+
* `ORDER BY created_at DESC, <pk> ASC LIMIT n` and no `created_at` index
|
|
201
|
+
* existed on any schema path (the dead AST path indexed `updated_at`
|
|
202
|
+
* instead), so every default list page was a sequential scan plus a top-N
|
|
203
|
+
* sort of the whole table — 21 ms against 0.1 ms with the right composite on
|
|
204
|
+
* the workload the assessment measured (#2363, finding A2).
|
|
205
|
+
*
|
|
206
|
+
* Emitted shape:
|
|
207
|
+
*
|
|
208
|
+
* - tenant-scoped table → `(<tenant column>, created_at)`. The tenancy
|
|
209
|
+
* interceptor adds `tenant_id = ?` to every list, so the tenant column
|
|
210
|
+
* leads and `created_at` orders within it.
|
|
211
|
+
* - otherwise → `(created_at)`.
|
|
212
|
+
*
|
|
213
|
+
* No `DESC` declaration: PostgreSQL scans a B-tree backwards just as
|
|
214
|
+
* cheaply, and `IndexDefinition` carries no per-column direction. The
|
|
215
|
+
* trailing primary-key tiebreak is left out deliberately — its direction is
|
|
216
|
+
* opposite to `created_at`'s, so no single-direction index can satisfy the
|
|
217
|
+
* whole key anyway; the leading columns turn a full sort into an index scan
|
|
218
|
+
* with an incremental sort over rows that share a timestamp.
|
|
219
|
+
*
|
|
220
|
+
* Call this AFTER {@link appendDeclaredIndexes} and BEFORE
|
|
221
|
+
* {@link ensureReferenceColumnIndexes}: a declared composite that already
|
|
222
|
+
* leads with the same columns suppresses this one, and this composite in
|
|
223
|
+
* turn suppresses the standalone tenant index that would otherwise be a
|
|
224
|
+
* redundant prefix of it.
|
|
225
|
+
*/
|
|
226
|
+
ensureDefaultListOrderingIndex(indexes, columns, tableName) {
|
|
227
|
+
const orderingColumns = this.getDefaultListOrderingColumns(columns);
|
|
228
|
+
if (!orderingColumns) return;
|
|
229
|
+
if (this.hasUnqualifiedLeadingColumns(indexes, orderingColumns)) return;
|
|
230
|
+
const name = `${tableName}_${orderingColumns.join("_")}_idx`;
|
|
231
|
+
if (indexes.some((index) => index.name === name)) return;
|
|
232
|
+
indexes.push({
|
|
233
|
+
name,
|
|
234
|
+
columns: orderingColumns
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The `(meta_type, meta_id)` owner-lookup columns for a polymorphic
|
|
239
|
+
* association table, or `null` when the table isn't one.
|
|
240
|
+
*
|
|
241
|
+
* `SmrtPolymorphicAssociation` contributes `metaType`/`metaId`/`role` (and
|
|
242
|
+
* `sortOrder`) to any concrete subclass's manifest — the scanner's
|
|
243
|
+
* `FRAMEWORK_ABSTRACT_BASE_NAMES` wiring merges the abstract base's fields
|
|
244
|
+
* directly into the subclass, because the base carries no `@smrt()`
|
|
245
|
+
* decorator of its own to declare an index on. Detected structurally, by
|
|
246
|
+
* the same three-column test `cascade.ts`'s `isPolymorphicAssociationClass`
|
|
247
|
+
* uses on registry field maps: requiring all three keeps an unrelated class
|
|
248
|
+
* that merely happens to carry a `metaType` column from being treated as an
|
|
249
|
+
* association table.
|
|
250
|
+
*/
|
|
251
|
+
getPolymorphicAssociationOwnerColumns(columns) {
|
|
252
|
+
if (!Object.hasOwn(columns, "meta_type") || !Object.hasOwn(columns, "meta_id") || !Object.hasOwn(columns, "role")) return null;
|
|
253
|
+
return ["meta_type", "meta_id"];
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* Ensure a polymorphic association table indexes its owner lookup
|
|
257
|
+
* `(meta_type, meta_id)` (#2364, epic #2382 finding A3).
|
|
258
|
+
*
|
|
259
|
+
* A concrete association's `conflictColumns` lead with its own FK (e.g.
|
|
260
|
+
* `AssetAssociation`'s `asset_id, meta_type, meta_id, role`), so
|
|
261
|
+
* `meta_type`/`meta_id` sit in the *middle* of that unique index — a
|
|
262
|
+
* lookup like `AssetAssociationCollection.byLeft(metaType, metaId)`
|
|
263
|
+
* ("what points at this target") filters columns 2-3 of a 4-column index
|
|
264
|
+
* and cannot use it as a leading prefix. `metaId` is deliberately a bare
|
|
265
|
+
* string, never a typed `@foreignKey`/`@crossPackageRef` (there is no
|
|
266
|
+
* single target table), so {@link ensureReferenceColumnIndexes} never
|
|
267
|
+
* covers it either.
|
|
268
|
+
*
|
|
269
|
+
* Call this alongside {@link ensureDefaultListOrderingIndex}, before
|
|
270
|
+
* {@link ensureReferenceColumnIndexes}.
|
|
271
|
+
*
|
|
272
|
+
* Blast radius: this applies retroactively to every
|
|
273
|
+
* `SmrtPolymorphicAssociation` subclass across every package on the next
|
|
274
|
+
* `db:migrate`, not only the ones a given change touches — roll the wave
|
|
275
|
+
* out with `smrt db:migrate --postgres-safe` (#2362), same as any other
|
|
276
|
+
* bulk index addition.
|
|
277
|
+
*/
|
|
278
|
+
ensurePolymorphicAssociationIndex(indexes, columns, tableName) {
|
|
279
|
+
const ownerColumns = this.getPolymorphicAssociationOwnerColumns(columns);
|
|
280
|
+
if (!ownerColumns) return;
|
|
281
|
+
if (this.hasUnqualifiedLeadingColumns(indexes, ownerColumns)) return;
|
|
282
|
+
const name = `${tableName}_${ownerColumns.join("_")}_idx`;
|
|
283
|
+
if (indexes.some((index) => index.name === name)) return;
|
|
284
|
+
indexes.push({
|
|
285
|
+
name,
|
|
286
|
+
columns: ownerColumns
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Append `@smrt({ indexes: [...] })` declarations to a generated index set
|
|
291
|
+
* (#2357).
|
|
292
|
+
*
|
|
293
|
+
* Shared by every schema path — build-time AST, runtime registry CTI/STI, and
|
|
294
|
+
* manifest CTI/STI — so one declaration behaves identically however the schema
|
|
295
|
+
* was derived. Call it *first*, ahead of
|
|
296
|
+
* {@link ensureDefaultListOrderingIndex} (#2363) and
|
|
297
|
+
* {@link ensureReferenceColumnIndexes}: a declared composite leading with a
|
|
298
|
+
* reference column (e.g. `tenant_id`), or with the default ordering columns,
|
|
299
|
+
* is exactly what those helpers' leads-with check is meant to defer to, and
|
|
300
|
+
* appending afterwards would leave the table with a redundant standalone
|
|
301
|
+
* index (#2384, #2359).
|
|
302
|
+
*
|
|
303
|
+
* Nothing is dropped quietly. A column that resolves to no column on the
|
|
304
|
+
* table, a malformed entry, and a name collision with a different index are
|
|
305
|
+
* all hard errors — a silently missing index is a production performance bug
|
|
306
|
+
* that surfaces only under load.
|
|
307
|
+
*
|
|
308
|
+
* @param indexes - Generated index set, appended in place
|
|
309
|
+
* @param declared - The object's `indexes` config, from any config source
|
|
310
|
+
* @param columns - Emitted columns, keyed by column name
|
|
311
|
+
* @param tableName - Table the indexes belong to (for error messages)
|
|
312
|
+
*/
|
|
313
|
+
appendDeclaredIndexes(indexes, declared, columns, tableName) {
|
|
314
|
+
if (declared === void 0 || declared === null) return;
|
|
315
|
+
if (!Array.isArray(declared)) throw new Error(`@smrt({ indexes }) on "${tableName}" must be an array of index declarations.`);
|
|
316
|
+
for (const entry of declared) {
|
|
317
|
+
const spec = this.validateDeclaredIndex(entry, tableName);
|
|
318
|
+
const mappedColumns = spec.columns.map((column) => this.resolveDeclaredIndexColumn(column, columns));
|
|
319
|
+
const unknownColumns = mappedColumns.filter((column) => !Object.hasOwn(columns, column));
|
|
320
|
+
if (unknownColumns.length > 0) throw new Error(`Declared index "${spec.name}" on "${tableName}" references unknown column(s): ${unknownColumns.join(", ")}. Declared index columns must name a field or column on the object.`);
|
|
321
|
+
const index = {
|
|
322
|
+
name: spec.name,
|
|
323
|
+
columns: mappedColumns,
|
|
324
|
+
...spec.unique === true ? { unique: true } : {},
|
|
325
|
+
...spec.where !== void 0 ? { where: spec.where } : {}
|
|
326
|
+
};
|
|
327
|
+
const existing = indexes.find((other) => other.name === index.name);
|
|
328
|
+
if (existing) {
|
|
329
|
+
if (this.sameIndexTarget(existing, index)) continue;
|
|
330
|
+
throw new Error(`Declared index "${index.name}" on "${tableName}" collides with a different index of the same name. Rename the declared index.`);
|
|
331
|
+
}
|
|
332
|
+
indexes.push(index);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
/** Narrow one raw `indexes[]` entry, rejecting anything unusable. */
|
|
336
|
+
validateDeclaredIndex(entry, tableName) {
|
|
337
|
+
const spec = entry;
|
|
338
|
+
const describe = () => {
|
|
339
|
+
try {
|
|
340
|
+
return JSON.stringify(entry) ?? String(entry);
|
|
341
|
+
} catch {
|
|
342
|
+
return String(entry);
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
if (typeof spec !== "object" || spec === null || Array.isArray(spec)) throw new Error(`Declared index on "${tableName}" must be an object: got ${describe()}.`);
|
|
346
|
+
if (typeof spec.name !== "string" || spec.name.length === 0) throw new Error(`Declared index on "${tableName}" needs a non-empty "name": got ${describe()}.`);
|
|
347
|
+
assertIdentifierFits(spec.name, "Declared index", `table "${tableName}"`);
|
|
348
|
+
if (!Array.isArray(spec.columns) || spec.columns.length === 0 || !spec.columns.every((column) => typeof column === "string" && column.length > 0)) throw new Error(`Declared index "${spec.name}" on "${tableName}" needs a non-empty "columns" array of field or column names.`);
|
|
349
|
+
if (spec.unique !== void 0 && typeof spec.unique !== "boolean") throw new Error(`Declared index "${spec.name}" on "${tableName}" has a non-boolean "unique": got ${describe()}.`);
|
|
350
|
+
if (spec.where !== void 0 && (typeof spec.where !== "string" || spec.where.trim().length === 0)) throw new Error(`Declared index "${spec.name}" on "${tableName}" has an empty or non-string "where" predicate.`);
|
|
351
|
+
return spec;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* Resolve a declared index column to an emitted column name.
|
|
355
|
+
*
|
|
356
|
+
* Declarations name SMRT fields, but only the runtime/manifest paths
|
|
357
|
+
* snake_case them into columns — the build-time AST path keys columns by the
|
|
358
|
+
* field name itself. Prefer an exact column hit, then the snake_case form, and
|
|
359
|
+
* otherwise return the input unchanged so the caller reports it as unknown.
|
|
360
|
+
*/
|
|
361
|
+
resolveDeclaredIndexColumn(name, columns) {
|
|
362
|
+
if (Object.hasOwn(columns, name)) return name;
|
|
363
|
+
const snakeCased = this.toSnakeCase(name);
|
|
364
|
+
return Object.hasOwn(columns, snakeCased) ? snakeCased : name;
|
|
365
|
+
}
|
|
366
|
+
/** Whether two index definitions describe the same database object. */
|
|
367
|
+
sameIndexTarget(a, b) {
|
|
368
|
+
return a.columns.length === b.columns.length && a.columns.every((column, i) => column === b.columns[i]) && (a.unique ?? false) === (b.unique ?? false) && (a.where ?? null) === (b.where ?? null);
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Ensure every reference column — `@foreignKey`, `@crossPackageRef`, and the
|
|
372
|
+
* tenancy-injected `tenant_id` — has an index leading with it.
|
|
373
|
+
*
|
|
374
|
+
* These are the columns every relationship load, `include:` batch, reverse
|
|
375
|
+
* ownership lookup and tenant-scoped read filters on. Before #2359 only the
|
|
376
|
+
* registry (test) paths indexed foreign keys, the manifest (production)
|
|
377
|
+
* paths indexed none of them, and `tenant_id` was indexed nowhere (#2356):
|
|
378
|
+
* 196/231 `@foreignKey` and 91/92 `@crossPackageRef` columns shipped with no
|
|
379
|
+
* serving index. Every schema path now calls this helper so the four paths
|
|
380
|
+
* stay in step (see `schema-path-parity.test.ts`).
|
|
381
|
+
*
|
|
382
|
+
* "Leading with it" rather than "always add": a table that already has an
|
|
383
|
+
* unqualified index starting on the column (commonly the `conflictColumns`
|
|
384
|
+
* unique index, or an `indexed: true` opt-in) is already served, and a
|
|
385
|
+
* standalone duplicate would only cost writes. A *partial* index does not
|
|
386
|
+
* count — see {@link hasUnqualifiedLeadingIndex}.
|
|
387
|
+
*
|
|
388
|
+
* Reference columns are therefore always indexed; `indexed: true` on one of
|
|
389
|
+
* them is redundant and harmless.
|
|
390
|
+
*
|
|
391
|
+
* Call this LAST in every path, after every other index (conflict, opt-in,
|
|
392
|
+
* unique, the declared composites, the default list-ordering composite, and
|
|
393
|
+
* any future addition) has been appended, so the leads-with suppression sees
|
|
394
|
+
* the full set. In particular {@link ensureDefaultListOrderingIndex} runs
|
|
395
|
+
* first on a tenant-scoped table: its `(tenant_id, created_at)` composite
|
|
396
|
+
* serves the tenant equality filter too, so no standalone tenant index is
|
|
397
|
+
* added (#2363).
|
|
398
|
+
*/
|
|
399
|
+
ensureReferenceColumnIndexes(indexes, columns, tableName) {
|
|
400
|
+
for (const [columnName, columnDef] of Object.entries(columns)) {
|
|
401
|
+
const kind = columnDef?.referenceKind;
|
|
402
|
+
if (kind !== "foreignKey" && kind !== "crossPackageRef" && kind !== "tenantId") continue;
|
|
403
|
+
if (columnDef?.primaryKey || columnDef?.unique) continue;
|
|
404
|
+
if (this.hasUnqualifiedLeadingIndex(indexes, columnName)) continue;
|
|
405
|
+
const name = `${tableName}_${columnName}_idx`;
|
|
406
|
+
if (indexes.some((index) => index.name === name)) continue;
|
|
407
|
+
indexes.push({
|
|
408
|
+
name,
|
|
409
|
+
columns: [columnName]
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Whether `conflictColumns` names exactly the primary key column(s).
|
|
415
|
+
*
|
|
416
|
+
* `ON CONFLICT (id)` binds to the primary-key constraint on every engine, so
|
|
417
|
+
* a separate unique index over the same column set is a second B-tree over
|
|
418
|
+
* the same random UUIDs with nothing to add (#2359, finding A5).
|
|
419
|
+
*/
|
|
420
|
+
conflictColumnsArePrimaryKey(conflictColumns, columns) {
|
|
421
|
+
const primaryKeyColumns = Object.entries(columns).filter(([, columnDef]) => columnDef?.primaryKey === true).map(([name]) => name);
|
|
422
|
+
return primaryKeyColumns.length > 0 && primaryKeyColumns.length === conflictColumns.length && primaryKeyColumns.every((column) => conflictColumns.includes(column));
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* The table's tenant column as the generated columns describe it: the
|
|
426
|
+
* column carrying `referenceKind: 'tenantId'` (set from the field's
|
|
427
|
+
* `__tenancy.isTenantIdField` marker on every path).
|
|
428
|
+
*/
|
|
429
|
+
findTenantColumn(columns) {
|
|
430
|
+
for (const [columnName, columnDef] of Object.entries(columns)) if (columnDef?.referenceKind === "tenantId") return columnName;
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Resolve the conflict target the unique conflict index must cover
|
|
434
|
+
* (#2360). `config.conflictColumns` wins when the caller resolved it —
|
|
435
|
+
* registry callers pass `ObjectRegistry.getConflictColumns()`, the manifest
|
|
436
|
+
* pipeline passes the normalized `decoratorConfig` — otherwise the strategy
|
|
437
|
+
* default, led by the tenant column when `config.tenantScoped` names a
|
|
438
|
+
* tenant field that exists as a column. Both roads apply the same rule as
|
|
439
|
+
* `ObjectRegistry.getConflictColumns()`, so schema and upsert agree by
|
|
440
|
+
* construction (`schema-path-parity.test.ts`).
|
|
441
|
+
*/
|
|
442
|
+
resolveConflictTarget(strategy, columns, config) {
|
|
443
|
+
const tenantColumn = this.findTenantColumn(columns);
|
|
444
|
+
if (config?.conflictColumns && config.conflictColumns.length > 0) return {
|
|
445
|
+
conflictColumns: [...config.conflictColumns],
|
|
446
|
+
tenantColumn
|
|
447
|
+
};
|
|
448
|
+
const tenantScoped = config?.tenantScoped;
|
|
449
|
+
return {
|
|
450
|
+
conflictColumns: resolveConflictColumns({
|
|
451
|
+
strategy,
|
|
452
|
+
tenantColumn: tenantScoped ? resolveTenantColumn(typeof tenantScoped === "object" ? tenantScoped.field ?? "tenantId" : "tenantId", (fieldName) => Boolean(columns[this.toSnakeCase(fieldName)]), (fieldName) => this.toSnakeCase(fieldName)) : void 0
|
|
453
|
+
}),
|
|
454
|
+
tenantColumn
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Keep `(slug, context)` lookups served when `conflictColumns` are custom.
|
|
459
|
+
*
|
|
460
|
+
* The default conflict index is `(slug, context)`, and `loadFromSlug()`,
|
|
461
|
+
* `getId()` and `getSavedId()` all filter on `slug`/`context` regardless of
|
|
462
|
+
* the configured conflict key. A class that declares custom conflict
|
|
463
|
+
* columns replaces that unique index and, before #2359, left those lookups
|
|
464
|
+
* with no index at all — 120 tables (finding A7).
|
|
465
|
+
*
|
|
466
|
+
* Emitting a plain `(slug, context)` index is the safer of the two fixes:
|
|
467
|
+
* routing the lookups through the conflict key would change which row a
|
|
468
|
+
* slug resolves to on every such class, whereas an extra non-unique index
|
|
469
|
+
* is purely additive. It is skipped when an unqualified index already
|
|
470
|
+
* serves the lookup — one leading with `slug` (e.g. custom conflict columns
|
|
471
|
+
* that still start with it), or the tenant-led default key
|
|
472
|
+
* `(tenant_id, slug, context)` of a tenant-scoped table (#2360): every slug
|
|
473
|
+
* lookup on such a table carries the tenant predicate (#2365) and is served
|
|
474
|
+
* by that prefix, so a second index would only cost writes.
|
|
475
|
+
*/
|
|
476
|
+
ensureSlugLookupIndex(indexes, columns, tableName) {
|
|
477
|
+
if (!columns.slug || !columns.context) return;
|
|
478
|
+
const tenantColumn = this.findTenantColumn(columns);
|
|
479
|
+
if (indexes.some((index) => !index.where && !index.jsonPath && servesSlugLookup(index.columns ?? [], tenantColumn))) return;
|
|
480
|
+
const name = `${tableName}_slug_context_idx`;
|
|
481
|
+
if (indexes.some((index) => index.name === name)) return;
|
|
482
|
+
indexes.push({
|
|
483
|
+
name,
|
|
484
|
+
columns: ["slug", "context"]
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Emit the unique conflict index of an STI table from the resolved
|
|
489
|
+
* conflict target (#2360): the STI default `(slug, context, _meta_type)`,
|
|
490
|
+
* a custom `@smrt({ conflictColumns })` declared on the STI root, or the
|
|
491
|
+
* default led by the tenant column when the root is tenant-scoped. Shared
|
|
492
|
+
* by the registry and manifest STI paths so they cannot drift.
|
|
493
|
+
*
|
|
494
|
+
* No index is emitted when the target is the primary key itself
|
|
495
|
+
* (`ON CONFLICT (id)` binds to the PK constraint), matching the CTI paths.
|
|
496
|
+
*/
|
|
497
|
+
emitStiConflictIndex(indexes, columns, tableName, config) {
|
|
498
|
+
const { conflictColumns, tenantColumn } = this.resolveConflictTarget("sti", columns, config);
|
|
499
|
+
if (this.conflictColumnsArePrimaryKey(conflictColumns, columns)) return;
|
|
500
|
+
indexes.push({
|
|
501
|
+
name: conflictIndexName(tableName, conflictColumns, tenantColumn),
|
|
502
|
+
columns: conflictColumns,
|
|
503
|
+
unique: true
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Emit unique indexes for `@field({ unique: true })` columns on an STI table.
|
|
508
|
+
*
|
|
509
|
+
* STI columns are the union of every class in the hierarchy, all nullable,
|
|
510
|
+
* so a column-level `UNIQUE` (what CTI renders inline) is not enough on its
|
|
511
|
+
* own: the migration differ cannot add a column constraint to an existing
|
|
512
|
+
* table, but it can add an index. Two shapes (#2359, finding A4):
|
|
513
|
+
*
|
|
514
|
+
* - declared on the STI **base** (and therefore inherited by every class in
|
|
515
|
+
* the table): one full unique index, table-wide like CTI;
|
|
516
|
+
* - declared only on a **descendant**: one partial unique index per class
|
|
517
|
+
* that carries the flag (the declaring class and, through inherited field
|
|
518
|
+
* metadata, its own descendants), `WHERE _meta_type = '<qualified>'`, so
|
|
519
|
+
* siblings that merely share the column name are not constrained.
|
|
520
|
+
* Uniqueness is then enforced per concrete class, not across the subtree
|
|
521
|
+
* — a documented limitation of the discriminator-partial shape. Engines
|
|
522
|
+
* without partial indexes (DuckDB, JSON) skip this shape entirely rather
|
|
523
|
+
* than widen it to a table-wide UNIQUE (see DuckDBStrategy.generateIndexes
|
|
524
|
+
* and SchemaComparer.compareIndexes).
|
|
525
|
+
*
|
|
526
|
+
* @param declarers - column name → classes whose field metadata carries
|
|
527
|
+
* `unique: true` for that column, in hierarchy order (base first).
|
|
528
|
+
*/
|
|
529
|
+
emitStiUniqueIndexes(indexes, declarers, baseClassName, tableName) {
|
|
530
|
+
for (const [columnName, classNames] of declarers.entries()) {
|
|
531
|
+
if (classNames.has(baseClassName)) {
|
|
532
|
+
indexes.push({
|
|
533
|
+
name: `${tableName}_${columnName}_unique_idx`,
|
|
534
|
+
columns: [columnName],
|
|
535
|
+
unique: true
|
|
536
|
+
});
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
for (const className of classNames) {
|
|
540
|
+
const simpleName = className.includes(":") ? className.slice(className.lastIndexOf(":") + 1) : className;
|
|
541
|
+
let name = `${tableName}_${columnName}_${this.toSnakeCase(simpleName)}_unique_idx`;
|
|
542
|
+
if (indexes.some((index) => index.name === name)) {
|
|
543
|
+
const digest = createHash("sha256").update(className).digest("hex").slice(0, 6);
|
|
544
|
+
name = `${tableName}_${columnName}_${this.toSnakeCase(simpleName)}_${digest}_unique_idx`;
|
|
545
|
+
}
|
|
546
|
+
indexes.push({
|
|
547
|
+
name,
|
|
548
|
+
columns: [columnName],
|
|
549
|
+
unique: true,
|
|
550
|
+
where: `_meta_type = ${quoteStringLiteral(className)}`
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
/**
|
|
141
556
|
* Generate index definitions
|
|
142
557
|
*/
|
|
143
558
|
generateIndexes(objectDef, columns) {
|
|
@@ -159,6 +574,7 @@ var SchemaGenerator = class {
|
|
|
159
574
|
unique: true,
|
|
160
575
|
description: `Unique index for ${columnName}`
|
|
161
576
|
});
|
|
577
|
+
this.appendDeclaredIndexes(indexes, objectDef.decoratorConfig?.indexes, columns, tableName);
|
|
162
578
|
return indexes;
|
|
163
579
|
}
|
|
164
580
|
/**
|
|
@@ -331,37 +747,25 @@ var SchemaGenerator = class {
|
|
|
331
747
|
this.reconcileRegistryForeignKeyColumnTypes(columns, fields, config?.registry);
|
|
332
748
|
const indexes = [];
|
|
333
749
|
if (!hasCustomPK) {
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
description: "Primary key index"
|
|
338
|
-
});
|
|
339
|
-
const conflictColumns = config?.conflictColumns || ["slug", "context"];
|
|
340
|
-
const conflictIndexName = conflictColumns.length > 2 ? `${tableName}_${conflictColumns.slice(0, 2).join("_")}_idx` : `${tableName}_${conflictColumns.join("_")}_idx`;
|
|
341
|
-
indexes.push({
|
|
342
|
-
name: conflictIndexName,
|
|
750
|
+
const { conflictColumns, tenantColumn } = this.resolveConflictTarget("cti", columns, config);
|
|
751
|
+
if (!this.conflictColumnsArePrimaryKey(conflictColumns, columns)) indexes.push({
|
|
752
|
+
name: conflictIndexName(tableName, conflictColumns, tenantColumn),
|
|
343
753
|
columns: conflictColumns,
|
|
344
754
|
unique: true,
|
|
345
755
|
description: `Unique conflict index for ${className}`
|
|
346
756
|
});
|
|
347
|
-
} else for (const [colName, colDef] of Object.entries(columns)) if (colDef.primaryKey) {
|
|
348
|
-
indexes.push({
|
|
349
|
-
name: `${tableName}_${colName}_idx`,
|
|
350
|
-
columns: [colName],
|
|
351
|
-
description: `Primary key index`
|
|
352
|
-
});
|
|
353
|
-
break;
|
|
354
757
|
}
|
|
355
|
-
|
|
356
|
-
name: `idx_${tableName}_${colName}`,
|
|
357
|
-
columns: [colName],
|
|
358
|
-
description: `Foreign key index for ${colName}`
|
|
359
|
-
});
|
|
758
|
+
this.ensureSlugLookupIndex(indexes, columns, tableName);
|
|
360
759
|
for (const colName of indexedColumns) indexes.push({
|
|
361
760
|
name: `${tableName}_${colName}_idx`,
|
|
362
761
|
columns: [colName],
|
|
363
762
|
description: `Index for ${colName}`
|
|
364
763
|
});
|
|
764
|
+
this.appendDeclaredIndexes(indexes, config?.indexes, columns, tableName);
|
|
765
|
+
this.ensureDefaultListOrderingIndex(indexes, columns, tableName);
|
|
766
|
+
this.ensurePolymorphicAssociationIndex(indexes, columns, tableName);
|
|
767
|
+
this.ensureReferenceColumnIndexes(indexes, columns, tableName);
|
|
768
|
+
enforceIdentifierLimits(tableName, indexes);
|
|
365
769
|
return {
|
|
366
770
|
tableName,
|
|
367
771
|
columns,
|
|
@@ -381,7 +785,14 @@ var SchemaGenerator = class {
|
|
|
381
785
|
* - _meta_type: Discriminator column to identify class type
|
|
382
786
|
* - _meta_data: JSON column for flexible field storage
|
|
383
787
|
* - Union of all FK columns from descendants (all nullable)
|
|
384
|
-
* -
|
|
788
|
+
* - One plain index per reference column (FK / cross-package ref /
|
|
789
|
+
* tenant_id). Plain rather than partial-by-class: base-class polymorphic
|
|
790
|
+
* queries carry no `_meta_type` predicate, so a partial index could not
|
|
791
|
+
* serve them, while a plain index serves both those and the child
|
|
792
|
+
* collections' `_meta_type = X AND fk = ?` filters — one index per column
|
|
793
|
+
* instead of one per (column, class) (#2359).
|
|
794
|
+
* - Unique indexes for `@field({ unique: true })` columns — see
|
|
795
|
+
* {@link emitStiUniqueIndexes}.
|
|
385
796
|
*
|
|
386
797
|
* @param baseClassName - Base class name for the STI hierarchy
|
|
387
798
|
* @param tableName - Shared table name (from base class)
|
|
@@ -441,12 +852,11 @@ var SchemaGenerator = class {
|
|
|
441
852
|
let hasUpdatedAt = false;
|
|
442
853
|
const descendants = ObjectRegistry.getDescendants(baseClassName);
|
|
443
854
|
const allClassNames = [baseClassName, ...descendants];
|
|
444
|
-
const fkColumnsByClass = /* @__PURE__ */ new Map();
|
|
445
855
|
const indexedMetaFields = /* @__PURE__ */ new Set();
|
|
446
856
|
const indexedStiColumns = /* @__PURE__ */ new Set();
|
|
857
|
+
const uniqueColumnDeclarers = /* @__PURE__ */ new Map();
|
|
447
858
|
for (const className of allClassNames) {
|
|
448
859
|
const classFields = await ObjectRegistry.getAllFields(className);
|
|
449
|
-
fkColumnsByClass.set(className, /* @__PURE__ */ new Set());
|
|
450
860
|
for (const [fieldName, field] of classFields.entries()) {
|
|
451
861
|
if (field.transient || field._meta?.transient) continue;
|
|
452
862
|
if (field.type === "meta" && (field.indexed === true || field._meta?.indexed === true)) indexedMetaFields.add(fieldName);
|
|
@@ -476,6 +886,14 @@ var SchemaGenerator = class {
|
|
|
476
886
|
if (field.type === "oneToMany" || field.type === "manyToMany") continue;
|
|
477
887
|
if (field.type === "meta") continue;
|
|
478
888
|
const columnName = this.toSnakeCase(fieldName);
|
|
889
|
+
if (field._meta?.unique === true) {
|
|
890
|
+
let declarers = uniqueColumnDeclarers.get(columnName);
|
|
891
|
+
if (!declarers) {
|
|
892
|
+
declarers = /* @__PURE__ */ new Set();
|
|
893
|
+
uniqueColumnDeclarers.set(columnName, declarers);
|
|
894
|
+
}
|
|
895
|
+
declarers.add(className);
|
|
896
|
+
}
|
|
479
897
|
if (columns[columnName]) continue;
|
|
480
898
|
const columnDef = {
|
|
481
899
|
type: this.getRelationshipColumnType(field),
|
|
@@ -489,15 +907,12 @@ var SchemaGenerator = class {
|
|
|
489
907
|
if (field.type === "foreignKey") {
|
|
490
908
|
const relatedName = field.related;
|
|
491
909
|
const onDeleteAction = field._meta?.onDelete;
|
|
492
|
-
if (relatedName) {
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
};
|
|
499
|
-
fkColumnsByClass.get(className)?.add(columnName);
|
|
500
|
-
}
|
|
910
|
+
if (relatedName) columnDef.foreignKey = {
|
|
911
|
+
table: this.classNameToTableName(relatedName),
|
|
912
|
+
column: "id",
|
|
913
|
+
onDelete: onDeleteAction || "CASCADE",
|
|
914
|
+
onUpdate: "CASCADE"
|
|
915
|
+
};
|
|
501
916
|
}
|
|
502
917
|
if ((field._meta?.indexed === true || field.indexed === true) && !columnDef.foreignKey) indexedStiColumns.add(columnName);
|
|
503
918
|
columns[columnName] = columnDef;
|
|
@@ -520,32 +935,14 @@ var SchemaGenerator = class {
|
|
|
520
935
|
this.reconcileRegistryForeignKeyColumnTypes(columns, classFields, ObjectRegistry);
|
|
521
936
|
}
|
|
522
937
|
const indexes = [];
|
|
523
|
-
|
|
524
|
-
name: `${tableName}_id_idx`,
|
|
525
|
-
columns: ["id"],
|
|
526
|
-
description: "Primary key index"
|
|
527
|
-
});
|
|
528
|
-
indexes.push({
|
|
529
|
-
name: `${tableName}_slug_context_meta_type_idx`,
|
|
530
|
-
columns: [
|
|
531
|
-
"slug",
|
|
532
|
-
"context",
|
|
533
|
-
"_meta_type"
|
|
534
|
-
],
|
|
535
|
-
unique: true,
|
|
536
|
-
description: "Unique index for slug, context, and type"
|
|
537
|
-
});
|
|
938
|
+
this.emitStiConflictIndex(indexes, columns, tableName, config);
|
|
538
939
|
indexes.push({
|
|
539
940
|
name: `${tableName}_meta_type_idx`,
|
|
540
941
|
columns: ["_meta_type"],
|
|
541
942
|
description: "Index for type discriminator queries"
|
|
542
943
|
});
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
columns: [fkColumn],
|
|
546
|
-
where: `_meta_type = ${quoteStringLiteral(className)}`,
|
|
547
|
-
description: `Partial index for ${fkColumn} in ${className} rows`
|
|
548
|
-
});
|
|
944
|
+
this.emitStiUniqueIndexes(indexes, uniqueColumnDeclarers, baseClassName, tableName);
|
|
945
|
+
this.ensureSlugLookupIndex(indexes, columns, tableName);
|
|
549
946
|
for (const fieldName of indexedMetaFields) indexes.push({
|
|
550
947
|
name: `${tableName}_meta_${this.toSnakeCase(fieldName)}_idx`,
|
|
551
948
|
columns: [],
|
|
@@ -560,6 +957,11 @@ var SchemaGenerator = class {
|
|
|
560
957
|
columns: [colName],
|
|
561
958
|
description: `Index for ${colName}`
|
|
562
959
|
});
|
|
960
|
+
this.appendDeclaredIndexes(indexes, config?.indexes, columns, tableName);
|
|
961
|
+
this.ensureDefaultListOrderingIndex(indexes, columns, tableName);
|
|
962
|
+
this.ensurePolymorphicAssociationIndex(indexes, columns, tableName);
|
|
963
|
+
this.ensureReferenceColumnIndexes(indexes, columns, tableName);
|
|
964
|
+
enforceIdentifierLimits(tableName, indexes);
|
|
563
965
|
return {
|
|
564
966
|
tableName,
|
|
565
967
|
columns,
|
|
@@ -624,15 +1026,15 @@ var SchemaGenerator = class {
|
|
|
624
1026
|
notNull: true,
|
|
625
1027
|
default: "current_timestamp"
|
|
626
1028
|
};
|
|
627
|
-
const
|
|
628
|
-
const
|
|
629
|
-
const
|
|
1029
|
+
const baseKey = this.resolveManifestClassKey(baseClassName, manifest);
|
|
1030
|
+
const descendants = this.findDescendantsInManifest(baseKey, manifest);
|
|
1031
|
+
const allClassNames = [baseKey, ...descendants];
|
|
630
1032
|
const indexedMetaFields = /* @__PURE__ */ new Set();
|
|
631
1033
|
const indexedStiColumns = /* @__PURE__ */ new Set();
|
|
1034
|
+
const uniqueColumnDeclarers = /* @__PURE__ */ new Map();
|
|
632
1035
|
for (const className of allClassNames) {
|
|
633
1036
|
const objDef = manifest.objects[className];
|
|
634
1037
|
if (!objDef) continue;
|
|
635
|
-
fkColumnsByClass.set(className, /* @__PURE__ */ new Set());
|
|
636
1038
|
for (const [fieldName, field] of Object.entries(objDef.fields)) {
|
|
637
1039
|
if (field.transient || field._meta?.transient) continue;
|
|
638
1040
|
const indexedField = field;
|
|
@@ -641,6 +1043,14 @@ var SchemaGenerator = class {
|
|
|
641
1043
|
if (field.type === "oneToMany" || field.type === "manyToMany") continue;
|
|
642
1044
|
if (field.type === "meta") continue;
|
|
643
1045
|
const columnName = this.toSnakeCase(fieldName);
|
|
1046
|
+
if (field._meta?.unique === true) {
|
|
1047
|
+
let declarers = uniqueColumnDeclarers.get(columnName);
|
|
1048
|
+
if (!declarers) {
|
|
1049
|
+
declarers = /* @__PURE__ */ new Set();
|
|
1050
|
+
uniqueColumnDeclarers.set(columnName, declarers);
|
|
1051
|
+
}
|
|
1052
|
+
declarers.add(className);
|
|
1053
|
+
}
|
|
644
1054
|
if (columns[columnName]) continue;
|
|
645
1055
|
const columnDef = {
|
|
646
1056
|
type: this.getRelationshipColumnType(field),
|
|
@@ -648,29 +1058,18 @@ var SchemaGenerator = class {
|
|
|
648
1058
|
notNull: false
|
|
649
1059
|
};
|
|
650
1060
|
if (field.default !== void 0 && this.shouldEmitDefault(field, field.default)) columnDef.default = field.default;
|
|
651
|
-
if (field.type === "foreignKey") fkColumnsByClass.get(className)?.add(columnName);
|
|
652
1061
|
if ((indexedField.indexed === true || field._meta?.indexed === true) && field.type !== "foreignKey") indexedStiColumns.add(columnName);
|
|
653
1062
|
columns[columnName] = columnDef;
|
|
654
1063
|
}
|
|
655
1064
|
}
|
|
656
1065
|
const indexes = [];
|
|
657
|
-
|
|
658
|
-
name: `${tableName}_id_idx`,
|
|
659
|
-
columns: ["id"]
|
|
660
|
-
});
|
|
661
|
-
indexes.push({
|
|
662
|
-
name: `${tableName}_slug_context_meta_type_idx`,
|
|
663
|
-
columns: [
|
|
664
|
-
"slug",
|
|
665
|
-
"context",
|
|
666
|
-
"_meta_type"
|
|
667
|
-
],
|
|
668
|
-
unique: true
|
|
669
|
-
});
|
|
1066
|
+
this.emitStiConflictIndex(indexes, columns, tableName, config);
|
|
670
1067
|
indexes.push({
|
|
671
1068
|
name: `${tableName}_meta_type_idx`,
|
|
672
1069
|
columns: ["_meta_type"]
|
|
673
1070
|
});
|
|
1071
|
+
this.emitStiUniqueIndexes(indexes, uniqueColumnDeclarers, baseKey, tableName);
|
|
1072
|
+
this.ensureSlugLookupIndex(indexes, columns, tableName);
|
|
674
1073
|
for (const fieldName of indexedMetaFields) indexes.push({
|
|
675
1074
|
name: `${tableName}_meta_${this.toSnakeCase(fieldName)}_idx`,
|
|
676
1075
|
columns: [],
|
|
@@ -683,6 +1082,11 @@ var SchemaGenerator = class {
|
|
|
683
1082
|
name: `${tableName}_${colName}_idx`,
|
|
684
1083
|
columns: [colName]
|
|
685
1084
|
});
|
|
1085
|
+
this.appendDeclaredIndexes(indexes, config?.indexes, columns, tableName);
|
|
1086
|
+
this.ensureDefaultListOrderingIndex(indexes, columns, tableName);
|
|
1087
|
+
this.ensurePolymorphicAssociationIndex(indexes, columns, tableName);
|
|
1088
|
+
this.ensureReferenceColumnIndexes(indexes, columns, tableName);
|
|
1089
|
+
enforceIdentifierLimits(tableName, indexes);
|
|
686
1090
|
const schemaDefinition = {
|
|
687
1091
|
tableName,
|
|
688
1092
|
columns: this.convertManifestColumnsToSchemaColumns(columns),
|
|
@@ -764,21 +1168,22 @@ var SchemaGenerator = class {
|
|
|
764
1168
|
columns[columnName] = columnDef;
|
|
765
1169
|
}
|
|
766
1170
|
const indexes = [];
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
});
|
|
771
|
-
const conflictColumns = config?.conflictColumns || ["slug", "context"];
|
|
772
|
-
const indexName = conflictColumns.length > 2 ? `${tableName}_${conflictColumns.slice(0, 2).join("_")}_idx` : `${tableName}_${conflictColumns.join("_")}_idx`;
|
|
773
|
-
indexes.push({
|
|
774
|
-
name: indexName,
|
|
1171
|
+
const { conflictColumns, tenantColumn } = this.resolveConflictTarget("cti", columns, config);
|
|
1172
|
+
if (!this.conflictColumnsArePrimaryKey(conflictColumns, columns)) indexes.push({
|
|
1173
|
+
name: conflictIndexName(tableName, conflictColumns, tenantColumn),
|
|
775
1174
|
columns: conflictColumns,
|
|
776
1175
|
unique: true
|
|
777
1176
|
});
|
|
1177
|
+
this.ensureSlugLookupIndex(indexes, columns, tableName);
|
|
778
1178
|
for (const colName of indexedColumns) indexes.push({
|
|
779
1179
|
name: `${tableName}_${colName}_idx`,
|
|
780
1180
|
columns: [colName]
|
|
781
1181
|
});
|
|
1182
|
+
this.appendDeclaredIndexes(indexes, config?.indexes, columns, tableName);
|
|
1183
|
+
this.ensureDefaultListOrderingIndex(indexes, columns, tableName);
|
|
1184
|
+
this.ensurePolymorphicAssociationIndex(indexes, columns, tableName);
|
|
1185
|
+
this.ensureReferenceColumnIndexes(indexes, columns, tableName);
|
|
1186
|
+
enforceIdentifierLimits(tableName, indexes);
|
|
782
1187
|
const schemaDefinition = {
|
|
783
1188
|
tableName,
|
|
784
1189
|
columns: this.convertManifestColumnsToSchemaColumns(columns),
|
|
@@ -807,6 +1212,18 @@ var SchemaGenerator = class {
|
|
|
807
1212
|
};
|
|
808
1213
|
}
|
|
809
1214
|
/**
|
|
1215
|
+
* Resolve a class name (simple or qualified) to the key it is stored under
|
|
1216
|
+
* in `manifest.objects`. Falls back to the input when the manifest does not
|
|
1217
|
+
* carry the class (e.g. an external STI base absent from the aggregated
|
|
1218
|
+
* manifest), so callers can keep using it as an opaque label.
|
|
1219
|
+
*/
|
|
1220
|
+
resolveManifestClassKey(className, manifest) {
|
|
1221
|
+
if (manifest.objects[className]) return className;
|
|
1222
|
+
const simpleName = className.includes(":") ? className.slice(className.lastIndexOf(":") + 1) : className;
|
|
1223
|
+
for (const [key, obj] of Object.entries(manifest.objects)) if (obj.qualifiedName === className || obj.className === simpleName) return key;
|
|
1224
|
+
return className;
|
|
1225
|
+
}
|
|
1226
|
+
/**
|
|
810
1227
|
* Find all descendants of a class in the manifest
|
|
811
1228
|
*
|
|
812
1229
|
* Note: Manifest keys are now qualified names (@pkg:ClassName) but `extends` field
|
|
@@ -851,13 +1268,19 @@ var SchemaGenerator = class {
|
|
|
851
1268
|
return str.replace(/([A-Z])/g, "_$1").toLowerCase().replace(/^_/, "");
|
|
852
1269
|
}
|
|
853
1270
|
/**
|
|
854
|
-
* Generate
|
|
1271
|
+
* Generate the CREATE TABLE statement for a schema definition.
|
|
855
1272
|
*
|
|
856
|
-
*
|
|
857
|
-
*
|
|
1273
|
+
* With an `engine` this delegates to that engine's DDL strategy. Without
|
|
1274
|
+
* one it renders the engine-neutral preview stored in `schema.ddl` and
|
|
1275
|
+
* `manifest.json`: abstract SQL types, no indexes, no triggers. That
|
|
1276
|
+
* preview is NOT an executable representation of the table (#2358) —
|
|
1277
|
+
* executable paths (`db:migrate`, `MigrationGenerator`, `SchemaAggregator`,
|
|
1278
|
+
* `createIsolatedTestDbFromManifest`) render `schema.columns` and
|
|
1279
|
+
* `schema.indexes` through `getDDLStrategy(engine)` instead.
|
|
858
1280
|
*
|
|
859
1281
|
* @param schema - Schema definition object
|
|
860
|
-
* @
|
|
1282
|
+
* @param engine - Optional target engine; omit for the neutral preview
|
|
1283
|
+
* @returns SQL CREATE TABLE statement (no indexes)
|
|
861
1284
|
*/
|
|
862
1285
|
generateSQL(schema, engine) {
|
|
863
1286
|
if (engine) return getDDLStrategy(engine).generateCreateTable(schema);
|