@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/scanner/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,GAAG,MAAM,IAAI,MAAM,EAAE,CAAC;AAEvD;;;;;;;;;GASG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;OAKG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,uEAAuE;IACvE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,SAAS;IACxB,iFAAiF;IACjF,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,yEAAyE;IACzE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IACzB,kEAAkE;IAClE,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,oEAAoE;IACpE,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,yEAAyE;IACzE,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,iDAAiD;IACjD,UAAU,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,MAAM,EAAE,CAAC;CAC7B;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,qBAAqB,EAAE,CAAC;IACjC,MAAM,EAAE,KAAK,CAAC;QACZ,OAAO,EAAE,MAAM,CAAC;QAChB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,MAAM,CAAC,EAAE,MAAM,CAAC;KACjB,CAAC,CAAC;CACJ;AAED,MAAM,WAAW,WAAW;IAC1B,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../src/scanner/types.ts"],"sourcesContent":["/**\n * Type definitions for AST scanning and manifest generation\n */\n\nimport type { SmartObjectConfig } from '../registry.js';\n\n/**\n * Qualified class name in format \"@package/name:ClassName\"\n * Example: \"@happyvertical/smrt-core:Product\"\n */\nexport type QualifiedClassName = `${string}:${string}`;\n\n/**\n * Static per-field UI hints authored via `@field({ ui })` (#2046).\n *\n * A pure presentation seed for the field-policy rail (epic #2045): it rides the\n * manifest under the field's `_meta.ui` (never promoted to a top-level\n * `FieldDefinition` key), reaches runtime at `field._meta.ui` via\n * `ObjectRegistry.getAllFields()`, and is emitted to the browser in generated\n * web-collection definitions. It has NO schema, persistence, or security\n * effect — `sensitive`/`readPermission` remain the security rail.\n */\nexport interface FieldUIHints {\n /**\n * Seed the field into the \"basic\" visibility tier (shown before the\n * advanced disclosure). Unmarked fields default per the cold-start rule:\n * an object with no basic markers renders everything basic; once any field\n * is marked, unmarked fields default to advanced.\n */\n basic?: boolean;\n /** Grouping key for form section/grouping (consumer-defined label). */\n group?: string;\n /** Relative sort order within the form/group (ascending). */\n order?: number;\n /**\n * Seed the field's policy as locked: org/user policy tiers may not\n * override it unless an org admin explicitly unlocks it.\n */\n locked?: boolean;\n}\n\n/**\n * Structured metadata attached to a field definition under `_meta`.\n *\n * Captures the field-helper options the scanner and schema/manifest\n * generators read off a field (`sqlType`, `nullable`, `__tenancy`, …). The\n * index signature keeps the bag open for forward-compatible keys without\n * forcing every consumer through `any`.\n */\nexport interface FieldMeta {\n /** Explicit SQL type override (e.g. 'UUID') applied during schema generation. */\n sqlType?: string;\n /** Storage type for cross-package reference ids ('text' forces TEXT). */\n idType?: 'uuid' | 'text';\n /** When true, the column is nullable regardless of `required`. */\n nullable?: boolean;\n /** Mirror of the field's required flag captured at registration. */\n required?: boolean;\n /** Default value carried in metadata for runtime-registry generation. */\n default?: unknown;\n /** Marks the field as the primary key column. */\n primaryKey?: boolean;\n /** Marks the column as unique. */\n unique?: boolean;\n /** Column description carried into generated schema. */\n description?: string;\n /** Static per-field UI hints authored via `@field({ ui })` (#2046). */\n ui?: FieldUIHints;\n /** Opt-in column/JSON-path indexing flag. */\n indexed?: boolean;\n /** Foreign-key delete action carried in metadata. */\n onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT';\n /** Excludes the field from persistence when true. */\n transient?: boolean;\n /** Numeric/length validation bounds and pattern. */\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n /**\n * Validation regex. A string source, a `RegExp`, or — when a manifest was\n * JSON-serialized and a `RegExp` collapsed to `{}` — an opaque object. Read\n * sites must narrow before accessing `.source`.\n */\n pattern?: unknown;\n /** Tenancy metadata injected for tenant-scoped models. */\n __tenancy?: {\n isTenantIdField?: boolean;\n [key: string]: unknown;\n };\n /** Report-aggregate metadata injected by the report normalizer. */\n __report?: {\n kind?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Controls how a class is exposed in manifests and across packages\n */\nexport type SmrtVisibility =\n | 'public' // Included in published manifest, available to all consumers\n | 'internal' // Package-only, excluded from published manifest\n | 'test'; // Test-only, never in any published manifest\n\nexport interface FieldDefinition {\n type:\n | 'text'\n | 'decimal'\n | 'boolean'\n | 'integer'\n | 'datetime'\n | 'json'\n | 'foreignKey'\n | 'crossPackageRef' // Cross-package reference — UUID id column by default, no DDL FK\n | 'oneToMany'\n | 'manyToMany'\n | 'meta'; // STI meta fields (_meta_type, _meta_data)\n required?: boolean;\n default?: unknown;\n min?: number;\n max?: number;\n maxLength?: number;\n minLength?: number;\n related?: string; // For foreignKey, crossPackageRef, oneToMany, manyToMany\n description?: string;\n _meta?: FieldMeta;\n transient?: boolean; // Field not persisted to database\n /**\n * Sensitive value (API secrets, credentials, tax IDs). Still persisted, but\n * excluded from `toPublicJSON()` (generated REST/MCP/SvelteKit responses) and\n * rejected as a `where` filter key.\n */\n sensitive?: boolean;\n /**\n * Read-only over generated write surfaces. Stripped from create/update\n * request bodies so callers cannot mass-assign it.\n */\n readonly?: boolean;\n /**\n * Permission slug required to include this field in public/read responses.\n * Omitted unless the serializer is given a resolved permission set that\n * includes this slug. `sensitive` still wins and hides the field for all\n * callers.\n */\n readPermission?: string;\n /**\n * Controls whether the field is included in JSON exports.\n * - `true`: Always exported (unless site explicitly excludes it)\n * - `false`: Never exported (cannot be overridden by site config)\n * - `undefined`: Uses site's fieldExportDefault setting\n */\n exported?: boolean;\n}\n\nexport interface MethodDefinition {\n name: string;\n async: boolean;\n parameters: Array<{\n name: string;\n type: string;\n optional: boolean;\n default?: unknown;\n }>;\n returnType: string;\n description?: string;\n isStatic: boolean;\n isPublic: boolean;\n}\n\n/**\n * Pre-generated schema column definition for manifest\n */\nexport interface ManifestColumnDefinition {\n type: string; // SQL type: TEXT, INTEGER, DECIMAL, BOOLEAN, DATETIME, JSON\n primaryKey?: boolean;\n /**\n * Non-DDL marker for SMRT-owned identifier/reference columns.\n */\n referenceKind?: 'id' | 'foreignKey' | 'crossPackageRef' | 'tenantId';\n notNull?: boolean;\n unique?: boolean;\n default?: unknown;\n}\n\n/**\n * Pre-generated schema index definition for manifest\n */\nexport interface ManifestIndexDefinition {\n name: string;\n columns: string[];\n unique?: boolean;\n where?: string;\n /**\n * Expression-based index target — when set, the DDL strategy renders the\n * index over a JSON path inside `column` (dialect-specific syntax).\n */\n jsonPath?: {\n column: string;\n path: string;\n };\n}\n\n/**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator, stored in manifest.json\n */\nexport interface ManifestSchema {\n tableName: string;\n ddl: string;\n columns: Record<string, ManifestColumnDefinition>;\n indexes: ManifestIndexDefinition[];\n version: string; // Hash of schema definition for migration tracking\n}\n\n/**\n * Validation rule type for pre-computed validators\n * These are serializable rules extracted from field definitions at build time,\n * eliminating the need to compile validator closures at runtime.\n */\nexport type ValidationRuleType =\n | 'required'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * Pre-computed validation rule for a field\n * Generated at build time by ManifestGenerator, stored in manifest.json\n *\n * These rules are evaluated at runtime without creating closure functions,\n * significantly reducing CLI startup time for projects with many SMRT objects.\n */\nexport interface ValidationRule {\n /** Field name to validate */\n field: string;\n /** Type of validation rule */\n rule: ValidationRuleType;\n /** Value for the rule (number for min/max/minLength/maxLength, string for pattern) */\n value?: number | string;\n /** Field type for context (text, integer, decimal, etc.) */\n fieldType?: string;\n}\n\n// ── Agent manifest types ────────────────────────────────────────────────\n\n/**\n * Permission declared by an agent\n * Generated from uiSlots (manage:*) and CLI/MCP methods (execute:*)\n */\nexport interface AgentPermission {\n id: string;\n label: string;\n category: 'slot' | 'method';\n defaultGranted?: boolean;\n}\n\n/**\n * Feature declared by an agent\n */\nexport interface AgentFeature {\n id: string;\n label: string;\n description?: string;\n type: 'slot' | 'method';\n}\n\n/**\n * Menu item derived from agent uiSlots\n */\nexport interface AgentMenuItem {\n id: string;\n label: string;\n icon?: string;\n order: number;\n path: string;\n requiredPermission?: string;\n}\n\n/**\n * Component export declaration derived from package.json exports\n */\nexport interface AgentComponentDeclaration {\n exportPath: string;\n type: string;\n}\n\n/**\n * UI slot definition captured from static uiSlots on Agent subclasses\n */\nexport interface AgentUISlotManifest {\n id: string;\n label: string;\n description?: string;\n icon?: string;\n order?: number;\n disabled?: boolean;\n /** Durable owner for settings written through this slot. */\n scope?: 'agent' | 'persona';\n /** Optional fallback form contract for host applications. */\n settingsSchema?: {\n version: number;\n fields: Array<{\n id: string;\n label: string;\n type: 'string' | 'number' | 'boolean' | 'select' | 'textarea' | 'json';\n description?: string;\n required?: boolean;\n default?: unknown;\n placeholder?: string;\n options?: Array<{ value: string; label: string }>;\n min?: number;\n max?: number;\n }>;\n };\n}\n\n/**\n * Admin route declared by an agent via static adminRoutes\n * Consumed by vitePluginAgentRoutes to register admin routes with SvelteKit\n */\nexport interface AgentAdminRouteManifest {\n /** Route path relative to agent root (e.g., 'sources/[sourceId]') */\n path: string;\n /** Component export name from the agent's admin entry point */\n component: string;\n /** Optional: export name for server load function */\n load?: string;\n}\n\n/**\n * Auto-generated agent manifest section\n * Produced by the manifest build pipeline for any class with `agent` decorator config\n */\nexport interface AgentManifest {\n name: string;\n slug: string;\n icon?: string;\n tier: 'free' | 'standard' | 'premium';\n description?: string;\n uiSlots: Record<string, AgentUISlotManifest>;\n adminRoutes?: AgentAdminRouteManifest[];\n /** Default signal subscriptions declared by this agent */\n signalSubscriptions?: string[];\n permissions: AgentPermission[];\n features: AgentFeature[];\n menuItems: AgentMenuItem[];\n components: AgentComponentDeclaration[];\n}\n\n// ── Core manifest types ─────────────────────────────────────────────────\n\nexport interface SmartObjectDefinition {\n /**\n * Qualified name in format \"@package/name:ClassName\"\n * This is the PRIMARY KEY for manifest lookups.\n * Example: \"@happyvertical/smrt-core:Product\"\n *\n * Optional during transition - will be required in future versions.\n */\n qualifiedName?: QualifiedClassName;\n\n /**\n * Simple class name (PascalCase)\n * Example: \"Product\"\n */\n className: string;\n\n /**\n * Package name where this class is defined.\n * Example: \"@happyvertical/smrt-core\"\n *\n * Optional during transition - will be required in future versions.\n */\n packageName?: string;\n\n /**\n * Visibility control for manifest inclusion\n * - 'public': Included in published manifest (default)\n * - 'internal': Package-only, excluded from published manifest\n * - 'test': Test-only, never in any published manifest\n *\n * Defaults to 'public' if not specified.\n */\n visibility?: SmrtVisibility;\n\n /**\n * @deprecated Use qualifiedName instead. Kept for transition period.\n * Lowercase class name, formerly used as manifest key.\n */\n name: string;\n\n collection: string; // Pluralized name for endpoints\n filePath: string;\n packageVersion?: string; // Package version for external manifest loading\n importPath?: string; // Import path for dynamic loading (e.g., \"@pkg/objects\")\n modulePath?: string; // Relative module path within package\n exportName?: string; // Named export to use (defaults to className)\n collectionExportName?: string; // Collection class export name\n fields: Record<string, FieldDefinition>;\n methods: Record<string, MethodDefinition>;\n decoratorConfig: SmartObjectConfig;\n extends?: string; // Base class name (simple name, not qualified)\n extendsQualified?: string; // Base class qualified name\n extendsTypeArg?: string; // Generic type argument (e.g., \"Meeting\" from \"SmrtCollection<Meeting>\")\n tools?: Array<{\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n };\n }>;\n /**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, consumers can use this pre-computed schema directly\n * without calling generateSchema() at runtime, eliminating latency.\n */\n schema?: ManifestSchema;\n\n /**\n * Pre-computed validation rules for efficient runtime validation\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, the registry uses these rules instead of compiling\n * validator closures at runtime, significantly reducing startup time.\n *\n * @see ValidationRule\n */\n validationRules?: ValidationRule[];\n\n /**\n * Static properties captured from the class definition\n * Currently used for `static uiSlots` on Agent subclasses\n */\n staticProperties?: Record<string, unknown>;\n\n /**\n * Auto-generated agent manifest\n * Only present for classes with `agent` in their decorator config\n * Generated at build time by ManifestGenerator fifth pass\n */\n agent?: AgentManifest;\n}\n\n/**\n * Fixed `timestamp` for every manifest that can reach build output.\n *\n * Manifests are inlined into bundles (`registerPackageManifest(JSON.parse(...))`),\n * so a wall-clock value changes the emitted bytes on every build. That changes\n * Vite's content hash, which changes `dist/`, which invalidates every\n * downstream package through `dependsOn: ['^build']` — one rebuilt package\n * churned 202 of 245 task hashes, and `typecheck` never reused a cache entry\n * across runs (#2223).\n *\n * Nothing reads the field: `getManifestTimestampsHash` invalidates on\n * filesystem mtimes, and `normalizeManifestForHash` deletes it before\n * comparing. A fixed value therefore costs no information.\n *\n * Genuine runtime caches that expire on elapsed time — the discovery cache in\n * `manifest/discover-smrt-packages.ts` — keep using the clock; they never\n * reach build output.\n */\nexport const MANIFEST_TIMESTAMP = 0;\n\n/**\n * Fixed `generatedAt` for knowledge artifacts emitted into `dist/`.\n *\n * Same reasoning as {@link MANIFEST_TIMESTAMP}: build output is compared\n * byte-for-byte, so it cannot carry the clock. The Unix epoch is used rather\n * than `0` because the field is an ISO-8601 string, and a parseable value\n * keeps any consumer that formats it working.\n *\n * The working copy under `.smrt/` keeps a real timestamp — it is useful to a\n * human there, and `preserveKnowledgeGeneratedAt` already stops it churning\n * across incremental rebuilds.\n */\nexport const DETERMINISTIC_GENERATED_AT = '1970-01-01T00:00:00.000Z';\n\nexport interface SmartObjectManifest {\n version: string;\n /** Always {@link MANIFEST_TIMESTAMP} for build-output manifests. */\n timestamp: number;\n packageName?: string; // Root package name (should be set for all new manifests)\n packageVersion?: string; // Root package version\n /**\n * Objects keyed by qualified name (e.g., \"@happyvertical/smrt-core:Product\")\n * Key is string for backward compatibility, but should be QualifiedClassName format.\n */\n objects: Record<string, SmartObjectDefinition>;\n moduleType?: string; // Module type identifier (e.g., \"smrt\") for package discovery\n smrtDependencies?: string[]; // Discovered SMRT packages from dependency tree\n}\n\nexport interface ScanResult {\n filePath: string;\n objects: SmartObjectDefinition[];\n errors: Array<{\n message: string;\n line?: number;\n column?: number;\n }>;\n}\n\nexport interface ScanOptions {\n includePrivateMethods?: boolean;\n includeStaticMethods?: boolean;\n followImports?: boolean;\n baseClasses?: string[]; // Classes to consider as SMRT base classes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAodA,IAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,6BAA6B"}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../src/scanner/types.ts"],"sourcesContent":["/**\n * Type definitions for AST scanning and manifest generation\n */\n\nimport type { SmartObjectConfig } from '../registry.js';\n\n/**\n * Qualified class name in format \"@package/name:ClassName\"\n * Example: \"@happyvertical/smrt-core:Product\"\n */\nexport type QualifiedClassName = `${string}:${string}`;\n\n/**\n * Static per-field UI hints authored via `@field({ ui })` (#2046).\n *\n * A pure presentation seed for the field-policy rail (epic #2045): it rides the\n * manifest under the field's `_meta.ui` (never promoted to a top-level\n * `FieldDefinition` key), reaches runtime at `field._meta.ui` via\n * `ObjectRegistry.getAllFields()`, and is emitted to the browser in generated\n * web-collection definitions. It has NO schema, persistence, or security\n * effect — `sensitive`/`readPermission` remain the security rail.\n */\nexport interface FieldUIHints {\n /**\n * Seed the field into the \"basic\" visibility tier (shown before the\n * advanced disclosure). Unmarked fields default per the cold-start rule:\n * an object with no basic markers renders everything basic; once any field\n * is marked, unmarked fields default to advanced.\n */\n basic?: boolean;\n /** Grouping key for form section/grouping (consumer-defined label). */\n group?: string;\n /** Relative sort order within the form/group (ascending). */\n order?: number;\n /**\n * Seed the field's policy as locked: org/user policy tiers may not\n * override it unless an org admin explicitly unlocks it.\n */\n locked?: boolean;\n}\n\n/**\n * Structured metadata attached to a field definition under `_meta`.\n *\n * Captures the field-helper options the scanner and schema/manifest\n * generators read off a field (`sqlType`, `nullable`, `__tenancy`, …). The\n * index signature keeps the bag open for forward-compatible keys without\n * forcing every consumer through `any`.\n */\nexport interface FieldMeta {\n /** Explicit SQL type override (e.g. 'UUID') applied during schema generation. */\n sqlType?: string;\n /** Storage type for cross-package reference ids ('text' forces TEXT). */\n idType?: 'uuid' | 'text';\n /** When true, the column is nullable regardless of `required`. */\n nullable?: boolean;\n /** Mirror of the field's required flag captured at registration. */\n required?: boolean;\n /** Default value carried in metadata for runtime-registry generation. */\n default?: unknown;\n /** Marks the field as the primary key column. */\n primaryKey?: boolean;\n /** Marks the column as unique. */\n unique?: boolean;\n /** Column description carried into generated schema. */\n description?: string;\n /** Static per-field UI hints authored via `@field({ ui })` (#2046). */\n ui?: FieldUIHints;\n /** Opt-in column/JSON-path indexing flag. */\n indexed?: boolean;\n /** Foreign-key delete action carried in metadata. */\n onDelete?: 'CASCADE' | 'SET NULL' | 'RESTRICT';\n /** Excludes the field from persistence when true. */\n transient?: boolean;\n /** Numeric/length validation bounds and pattern. */\n min?: number;\n max?: number;\n minLength?: number;\n maxLength?: number;\n /**\n * Validation regex. A string source, a `RegExp`, or — when a manifest was\n * JSON-serialized and a `RegExp` collapsed to `{}` — an opaque object. Read\n * sites must narrow before accessing `.source`.\n */\n pattern?: unknown;\n /** Tenancy metadata injected for tenant-scoped models. */\n __tenancy?: {\n isTenantIdField?: boolean;\n [key: string]: unknown;\n };\n /** Report-aggregate metadata injected by the report normalizer. */\n __report?: {\n kind?: string;\n [key: string]: unknown;\n };\n [key: string]: unknown;\n}\n\n/**\n * Controls how a class is exposed in manifests and across packages\n */\nexport type SmrtVisibility =\n | 'public' // Included in published manifest, available to all consumers\n | 'internal' // Package-only, excluded from published manifest\n | 'test'; // Test-only, never in any published manifest\n\nexport interface FieldDefinition {\n type:\n | 'text'\n | 'decimal'\n | 'boolean'\n | 'integer'\n | 'datetime'\n | 'json'\n | 'foreignKey'\n | 'crossPackageRef' // Cross-package reference — UUID id column by default, no DDL FK\n | 'oneToMany'\n | 'manyToMany'\n | 'meta'; // STI meta fields (_meta_type, _meta_data)\n required?: boolean;\n default?: unknown;\n min?: number;\n max?: number;\n maxLength?: number;\n minLength?: number;\n related?: string; // For foreignKey, crossPackageRef, oneToMany, manyToMany\n description?: string;\n _meta?: FieldMeta;\n transient?: boolean; // Field not persisted to database\n /**\n * Sensitive value (API secrets, credentials, tax IDs). Still persisted, but\n * excluded from `toPublicJSON()` (generated REST/MCP/SvelteKit responses) and\n * rejected as a `where` filter key.\n */\n sensitive?: boolean;\n /**\n * Read-only over generated write surfaces. Stripped from create/update\n * request bodies so callers cannot mass-assign it.\n */\n readonly?: boolean;\n /**\n * Permission slug required to include this field in public/read responses.\n * Omitted unless the serializer is given a resolved permission set that\n * includes this slug. `sensitive` still wins and hides the field for all\n * callers.\n */\n readPermission?: string;\n /**\n * Controls whether the field is included in JSON exports.\n * - `true`: Always exported (unless site explicitly excludes it)\n * - `false`: Never exported (cannot be overridden by site config)\n * - `undefined`: Uses site's fieldExportDefault setting\n */\n exported?: boolean;\n}\n\nexport interface MethodDefinition {\n name: string;\n async: boolean;\n parameters: Array<{\n name: string;\n type: string;\n optional: boolean;\n default?: unknown;\n }>;\n returnType: string;\n description?: string;\n isStatic: boolean;\n isPublic: boolean;\n}\n\n/**\n * Pre-generated schema column definition for manifest\n */\nexport interface ManifestColumnDefinition {\n type: string; // SQL type: TEXT, INTEGER, DECIMAL, BOOLEAN, DATETIME, JSON\n primaryKey?: boolean;\n /**\n * Non-DDL marker for SMRT-owned identifier/reference columns.\n */\n referenceKind?: 'id' | 'foreignKey' | 'crossPackageRef' | 'tenantId';\n notNull?: boolean;\n unique?: boolean;\n default?: unknown;\n}\n\n/**\n * Pre-generated schema index definition for manifest\n */\nexport interface ManifestIndexDefinition {\n name: string;\n columns: string[];\n unique?: boolean;\n where?: string;\n /**\n * Expression-based index target — when set, the DDL strategy renders the\n * index over a JSON path inside `column` (dialect-specific syntax).\n */\n jsonPath?: {\n column: string;\n path: string;\n };\n}\n\n/**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator, stored in manifest.json\n */\nexport interface ManifestSchema {\n tableName: string;\n /**\n * Engine-neutral CREATE TABLE preview. Not executable as-is: no indexes,\n * abstract SQL types. Consumers render `columns` + `indexes` through the\n * engine DDL strategy (see `schema/manifest-schema.ts`, #2358).\n */\n ddl: string;\n columns: Record<string, ManifestColumnDefinition>;\n indexes: ManifestIndexDefinition[];\n version: string; // Hash of schema definition for migration tracking\n}\n\n/**\n * Validation rule type for pre-computed validators\n * These are serializable rules extracted from field definitions at build time,\n * eliminating the need to compile validator closures at runtime.\n */\nexport type ValidationRuleType =\n | 'required'\n | 'min'\n | 'max'\n | 'minLength'\n | 'maxLength'\n | 'pattern';\n\n/**\n * Pre-computed validation rule for a field\n * Generated at build time by ManifestGenerator, stored in manifest.json\n *\n * These rules are evaluated at runtime without creating closure functions,\n * significantly reducing CLI startup time for projects with many SMRT objects.\n */\nexport interface ValidationRule {\n /** Field name to validate */\n field: string;\n /** Type of validation rule */\n rule: ValidationRuleType;\n /** Value for the rule (number for min/max/minLength/maxLength, string for pattern) */\n value?: number | string;\n /** Field type for context (text, integer, decimal, etc.) */\n fieldType?: string;\n}\n\n// ── Agent manifest types ────────────────────────────────────────────────\n\n/**\n * Permission declared by an agent\n * Generated from uiSlots (manage:*) and CLI/MCP methods (execute:*)\n */\nexport interface AgentPermission {\n id: string;\n label: string;\n category: 'slot' | 'method';\n defaultGranted?: boolean;\n}\n\n/**\n * Feature declared by an agent\n */\nexport interface AgentFeature {\n id: string;\n label: string;\n description?: string;\n type: 'slot' | 'method';\n}\n\n/**\n * Menu item derived from agent uiSlots\n */\nexport interface AgentMenuItem {\n id: string;\n label: string;\n icon?: string;\n order: number;\n path: string;\n requiredPermission?: string;\n}\n\n/**\n * Component export declaration derived from package.json exports\n */\nexport interface AgentComponentDeclaration {\n exportPath: string;\n type: string;\n}\n\n/**\n * UI slot definition captured from static uiSlots on Agent subclasses\n */\nexport interface AgentUISlotManifest {\n id: string;\n label: string;\n description?: string;\n icon?: string;\n order?: number;\n disabled?: boolean;\n /** Durable owner for settings written through this slot. */\n scope?: 'agent' | 'persona';\n /** Optional fallback form contract for host applications. */\n settingsSchema?: {\n version: number;\n fields: Array<{\n id: string;\n label: string;\n type: 'string' | 'number' | 'boolean' | 'select' | 'textarea' | 'json';\n description?: string;\n required?: boolean;\n default?: unknown;\n placeholder?: string;\n options?: Array<{ value: string; label: string }>;\n min?: number;\n max?: number;\n }>;\n };\n}\n\n/**\n * Admin route declared by an agent via static adminRoutes\n * Consumed by vitePluginAgentRoutes to register admin routes with SvelteKit\n */\nexport interface AgentAdminRouteManifest {\n /** Route path relative to agent root (e.g., 'sources/[sourceId]') */\n path: string;\n /** Component export name from the agent's admin entry point */\n component: string;\n /** Optional: export name for server load function */\n load?: string;\n}\n\n/**\n * Auto-generated agent manifest section\n * Produced by the manifest build pipeline for any class with `agent` decorator config\n */\nexport interface AgentManifest {\n name: string;\n slug: string;\n icon?: string;\n tier: 'free' | 'standard' | 'premium';\n description?: string;\n uiSlots: Record<string, AgentUISlotManifest>;\n adminRoutes?: AgentAdminRouteManifest[];\n /** Default signal subscriptions declared by this agent */\n signalSubscriptions?: string[];\n permissions: AgentPermission[];\n features: AgentFeature[];\n menuItems: AgentMenuItem[];\n components: AgentComponentDeclaration[];\n}\n\n// ── Core manifest types ─────────────────────────────────────────────────\n\nexport interface SmartObjectDefinition {\n /**\n * Qualified name in format \"@package/name:ClassName\"\n * This is the PRIMARY KEY for manifest lookups.\n * Example: \"@happyvertical/smrt-core:Product\"\n *\n * Optional during transition - will be required in future versions.\n */\n qualifiedName?: QualifiedClassName;\n\n /**\n * Simple class name (PascalCase)\n * Example: \"Product\"\n */\n className: string;\n\n /**\n * Package name where this class is defined.\n * Example: \"@happyvertical/smrt-core\"\n *\n * Optional during transition - will be required in future versions.\n */\n packageName?: string;\n\n /**\n * Visibility control for manifest inclusion\n * - 'public': Included in published manifest (default)\n * - 'internal': Package-only, excluded from published manifest\n * - 'test': Test-only, never in any published manifest\n *\n * Defaults to 'public' if not specified.\n */\n visibility?: SmrtVisibility;\n\n /**\n * @deprecated Use qualifiedName instead. Kept for transition period.\n * Lowercase class name, formerly used as manifest key.\n */\n name: string;\n\n collection: string; // Pluralized name for endpoints\n filePath: string;\n packageVersion?: string; // Package version for external manifest loading\n importPath?: string; // Import path for dynamic loading (e.g., \"@pkg/objects\")\n modulePath?: string; // Relative module path within package\n exportName?: string; // Named export to use (defaults to className)\n collectionExportName?: string; // Collection class export name\n fields: Record<string, FieldDefinition>;\n methods: Record<string, MethodDefinition>;\n decoratorConfig: SmartObjectConfig;\n extends?: string; // Base class name (simple name, not qualified)\n extendsQualified?: string; // Base class qualified name\n extendsTypeArg?: string; // Generic type argument (e.g., \"Meeting\" from \"SmrtCollection<Meeting>\")\n tools?: Array<{\n type: 'function';\n function: {\n name: string;\n description?: string;\n parameters?: Record<string, unknown>;\n };\n }>;\n /**\n * Pre-generated schema for efficient external package consumption\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, consumers can use this pre-computed schema directly\n * without calling generateSchema() at runtime, eliminating latency.\n */\n schema?: ManifestSchema;\n\n /**\n * Pre-computed validation rules for efficient runtime validation\n * Generated at build time by ManifestGenerator (smrt scan)\n *\n * When present, the registry uses these rules instead of compiling\n * validator closures at runtime, significantly reducing startup time.\n *\n * @see ValidationRule\n */\n validationRules?: ValidationRule[];\n\n /**\n * Static properties captured from the class definition\n * Currently used for `static uiSlots` on Agent subclasses\n */\n staticProperties?: Record<string, unknown>;\n\n /**\n * Auto-generated agent manifest\n * Only present for classes with `agent` in their decorator config\n * Generated at build time by ManifestGenerator fifth pass\n */\n agent?: AgentManifest;\n}\n\n/**\n * Fixed `timestamp` for every manifest that can reach build output.\n *\n * Manifests are inlined into bundles (`registerPackageManifest(JSON.parse(...))`),\n * so a wall-clock value changes the emitted bytes on every build. That changes\n * Vite's content hash, which changes `dist/`, which invalidates every\n * downstream package through `dependsOn: ['^build']` — one rebuilt package\n * churned 202 of 245 task hashes, and `typecheck` never reused a cache entry\n * across runs (#2223).\n *\n * Nothing reads the field: `getManifestTimestampsHash` invalidates on\n * filesystem mtimes, and `normalizeManifestForHash` deletes it before\n * comparing. A fixed value therefore costs no information.\n *\n * Genuine runtime caches that expire on elapsed time — the discovery cache in\n * `manifest/discover-smrt-packages.ts` — keep using the clock; they never\n * reach build output.\n */\nexport const MANIFEST_TIMESTAMP = 0;\n\n/**\n * Fixed `generatedAt` for knowledge artifacts emitted into `dist/`.\n *\n * Same reasoning as {@link MANIFEST_TIMESTAMP}: build output is compared\n * byte-for-byte, so it cannot carry the clock. The Unix epoch is used rather\n * than `0` because the field is an ISO-8601 string, and a parseable value\n * keeps any consumer that formats it working.\n *\n * The working copy under `.smrt/` keeps a real timestamp — it is useful to a\n * human there, and `preserveKnowledgeGeneratedAt` already stops it churning\n * across incremental rebuilds.\n */\nexport const DETERMINISTIC_GENERATED_AT = '1970-01-01T00:00:00.000Z';\n\nexport interface SmartObjectManifest {\n version: string;\n /** Always {@link MANIFEST_TIMESTAMP} for build-output manifests. */\n timestamp: number;\n packageName?: string; // Root package name (should be set for all new manifests)\n packageVersion?: string; // Root package version\n /**\n * Objects keyed by qualified name (e.g., \"@happyvertical/smrt-core:Product\")\n * Key is string for backward compatibility, but should be QualifiedClassName format.\n */\n objects: Record<string, SmartObjectDefinition>;\n moduleType?: string; // Module type identifier (e.g., \"smrt\") for package discovery\n smrtDependencies?: string[]; // Discovered SMRT packages from dependency tree\n}\n\nexport interface ScanResult {\n filePath: string;\n objects: SmartObjectDefinition[];\n errors: Array<{\n message: string;\n line?: number;\n column?: number;\n }>;\n}\n\nexport interface ScanOptions {\n includePrivateMethods?: boolean;\n includeStaticMethods?: boolean;\n followImports?: boolean;\n baseClasses?: string[]; // Classes to consider as SMRT base classes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAydA,IAAa,qBAAqB;;;;;;;;;;;;;AAclC,IAAa,6BAA6B"}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conflict target (upsert natural key) resolution shared by every schema path
|
|
3
|
+
* and by the runtime (#2360, epic #2382 finding B1/A4).
|
|
4
|
+
*
|
|
5
|
+
* `SmrtObject.save()` upserts a NEW object on
|
|
6
|
+
* `ObjectRegistry.getConflictColumns()`; the schema generator emits ONE unique
|
|
7
|
+
* index over the same columns so `INSERT … ON CONFLICT (…)` binds on every
|
|
8
|
+
* engine. Before #2360 the tenancy interceptor populated `tenant_id` on save
|
|
9
|
+
* but neither the conflict target nor the unique index carried it, so a
|
|
10
|
+
* second tenant creating the same natural key (`slug`, `context`) matched the
|
|
11
|
+
* first tenant's row and `DO UPDATE SET` rewrote its `id` and `tenant_id`
|
|
12
|
+
* (probed: tenant A's row was silently adopted by tenant B).
|
|
13
|
+
*
|
|
14
|
+
* The rule now: **a tenant-scoped class's default conflict target is
|
|
15
|
+
* `[tenantColumn, ...naturalKey]`** on the build path (manifest
|
|
16
|
+
* `decoratorConfig.conflictColumns`, materialized by
|
|
17
|
+
* `ManifestGenerator.normalizeConflictColumns()`) and on the runtime path
|
|
18
|
+
* (`ObjectRegistry.getConflictColumns()`), so schema and upsert agree by
|
|
19
|
+
* construction. Explicit `@smrt({ conflictColumns })` always wins and is
|
|
20
|
+
* never rewritten — a class that declares its own natural key owns it.
|
|
21
|
+
*
|
|
22
|
+
* NULL-tenant rows (`mode: 'optional'` outside a tenant context) keep the
|
|
23
|
+
* SDK's null-aware upsert semantics: `@happyvertical/sql` matches conflict
|
|
24
|
+
* columns with `IS NOT DISTINCT FROM`, so `(NULL, 'widget', '')` updates the
|
|
25
|
+
* existing `(NULL, 'widget', '')` row through the model layer even though the
|
|
26
|
+
* database index treats NULLs as distinct. Global rows therefore dedup among
|
|
27
|
+
* themselves exactly as every row did before, and per-tenant rows dedup per
|
|
28
|
+
* tenant.
|
|
29
|
+
*
|
|
30
|
+
* Index NAMES stay stable across this change — the tenant-led default key
|
|
31
|
+
* keeps `<table>_slug_context_idx` (CTI) / `<table>_slug_context_meta_type_idx`
|
|
32
|
+
* (STI) — so `SchemaComparer`'s same-name shape-drift repair swaps the columns
|
|
33
|
+
* in place (`DROP INDEX` + `CREATE UNIQUE INDEX`) instead of leaving the old
|
|
34
|
+
* global unique index behind to keep blocking cross-tenant duplicates. The new
|
|
35
|
+
* key is a superset of the old one, so creating it cannot fail on existing
|
|
36
|
+
* data.
|
|
37
|
+
*/
|
|
38
|
+
/** Default natural key of a class-per-table (CTI) object. */
|
|
39
|
+
export declare const DEFAULT_CTI_CONFLICT_COLUMNS: readonly string[];
|
|
40
|
+
/**
|
|
41
|
+
* Default natural key of a single-table-inheritance (STI) hierarchy: the
|
|
42
|
+
* discriminator participates in identity so two subtypes may share a slug.
|
|
43
|
+
*/
|
|
44
|
+
export declare const DEFAULT_STI_CONFLICT_COLUMNS: readonly string[];
|
|
45
|
+
export type ConflictTableStrategy = 'cti' | 'sti';
|
|
46
|
+
/**
|
|
47
|
+
* The default conflict target for a table with the given strategy, led by the
|
|
48
|
+
* tenant column when the schema-owning class is tenant-scoped.
|
|
49
|
+
*/
|
|
50
|
+
export declare function defaultConflictColumns(strategy: ConflictTableStrategy, tenantColumn?: string | null): string[];
|
|
51
|
+
/**
|
|
52
|
+
* Resolve the conflict target of a table.
|
|
53
|
+
*
|
|
54
|
+
* `explicit` (a declared `@smrt({ conflictColumns })`) always wins; otherwise
|
|
55
|
+
* the strategy default, tenant-led when `tenantColumn` is given.
|
|
56
|
+
*/
|
|
57
|
+
export declare function resolveConflictColumns(options: {
|
|
58
|
+
explicit?: readonly string[] | null;
|
|
59
|
+
strategy: ConflictTableStrategy;
|
|
60
|
+
tenantColumn?: string | null;
|
|
61
|
+
}): string[];
|
|
62
|
+
/**
|
|
63
|
+
* Whether `conflictColumns` is exactly a default natural key (CTI or STI),
|
|
64
|
+
* optionally led by `tenantColumn`. Used to keep the default index names
|
|
65
|
+
* stable when the tenant column is prepended.
|
|
66
|
+
*/
|
|
67
|
+
export declare function isDefaultNaturalKey(conflictColumns: readonly string[], tenantColumn?: string | null): boolean;
|
|
68
|
+
/**
|
|
69
|
+
* The stable name of the unique conflict index for `conflictColumns`.
|
|
70
|
+
*
|
|
71
|
+
* - default CTI key `(slug, context)` → `<table>_slug_context_idx`
|
|
72
|
+
* - default STI key `(slug, context, _meta_type)` →
|
|
73
|
+
* `<table>_slug_context_meta_type_idx`
|
|
74
|
+
* - either default led by the tenant column → the SAME name as without it
|
|
75
|
+
* (#2360: the differ swaps the columns in place by name)
|
|
76
|
+
* - any custom key → `<table>_<first two columns>_idx` (the historical rule;
|
|
77
|
+
* a longer key keeps the two-column name so existing databases are not
|
|
78
|
+
* renamed)
|
|
79
|
+
*
|
|
80
|
+
* @param tenantColumn - the table's tenant column, when the schema owner is
|
|
81
|
+
* tenant-scoped; only consulted to recognize a tenant-led default key
|
|
82
|
+
*/
|
|
83
|
+
export declare function conflictIndexName(tableName: string, conflictColumns: readonly string[], tenantColumn?: string | null): string;
|
|
84
|
+
/**
|
|
85
|
+
* Whether an unqualified index over `indexColumns` serves slug lookups
|
|
86
|
+
* (`loadFromSlug()` / `getId()` / `getSavedId()` filter on `slug`, `context`):
|
|
87
|
+
* it leads with `slug`, or it is the tenant-led default key — a tenant-scoped
|
|
88
|
+
* lookup carries the tenant predicate (#2365) and is served by the prefix.
|
|
89
|
+
*/
|
|
90
|
+
export declare function servesSlugLookup(indexColumns: readonly string[], tenantColumn?: string | null): boolean;
|
|
91
|
+
/**
|
|
92
|
+
* The tenant column of a table, from the schema-owning class's normalized
|
|
93
|
+
* tenant-scoped configuration. Returns `undefined` when the class is not
|
|
94
|
+
* tenant-scoped or the configured field is not among its fields (the field is
|
|
95
|
+
* always injected for tenant-scoped classes; the guard keeps the runtime and
|
|
96
|
+
* build paths honest about the column actually existing).
|
|
97
|
+
*
|
|
98
|
+
* @param tenantField - the configured tenant field name (`tenantScoped.field`,
|
|
99
|
+
* default `tenantId`), or `undefined` when the class is not tenant-scoped
|
|
100
|
+
* @param hasField - whether the schema owner declares that field
|
|
101
|
+
* @param toColumn - field-name → column-name conversion (`toSnakeCase`)
|
|
102
|
+
*/
|
|
103
|
+
export declare function resolveTenantColumn(tenantField: string | undefined | null, hasField: (fieldName: string) => boolean, toColumn: (fieldName: string) => string): string | undefined;
|
|
104
|
+
//# sourceMappingURL=conflict-target.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conflict-target.d.ts","sourceRoot":"","sources":["../../src/schema/conflict-target.ts"],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Q,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,MAAM,GACtC,MAAM,GAAG,SAAS,CAGpB"}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
//#region src/schema/conflict-target.ts
|
|
2
|
+
/**
|
|
3
|
+
* Conflict target (upsert natural key) resolution shared by every schema path
|
|
4
|
+
* and by the runtime (#2360, epic #2382 finding B1/A4).
|
|
5
|
+
*
|
|
6
|
+
* `SmrtObject.save()` upserts a NEW object on
|
|
7
|
+
* `ObjectRegistry.getConflictColumns()`; the schema generator emits ONE unique
|
|
8
|
+
* index over the same columns so `INSERT … ON CONFLICT (…)` binds on every
|
|
9
|
+
* engine. Before #2360 the tenancy interceptor populated `tenant_id` on save
|
|
10
|
+
* but neither the conflict target nor the unique index carried it, so a
|
|
11
|
+
* second tenant creating the same natural key (`slug`, `context`) matched the
|
|
12
|
+
* first tenant's row and `DO UPDATE SET` rewrote its `id` and `tenant_id`
|
|
13
|
+
* (probed: tenant A's row was silently adopted by tenant B).
|
|
14
|
+
*
|
|
15
|
+
* The rule now: **a tenant-scoped class's default conflict target is
|
|
16
|
+
* `[tenantColumn, ...naturalKey]`** on the build path (manifest
|
|
17
|
+
* `decoratorConfig.conflictColumns`, materialized by
|
|
18
|
+
* `ManifestGenerator.normalizeConflictColumns()`) and on the runtime path
|
|
19
|
+
* (`ObjectRegistry.getConflictColumns()`), so schema and upsert agree by
|
|
20
|
+
* construction. Explicit `@smrt({ conflictColumns })` always wins and is
|
|
21
|
+
* never rewritten — a class that declares its own natural key owns it.
|
|
22
|
+
*
|
|
23
|
+
* NULL-tenant rows (`mode: 'optional'` outside a tenant context) keep the
|
|
24
|
+
* SDK's null-aware upsert semantics: `@happyvertical/sql` matches conflict
|
|
25
|
+
* columns with `IS NOT DISTINCT FROM`, so `(NULL, 'widget', '')` updates the
|
|
26
|
+
* existing `(NULL, 'widget', '')` row through the model layer even though the
|
|
27
|
+
* database index treats NULLs as distinct. Global rows therefore dedup among
|
|
28
|
+
* themselves exactly as every row did before, and per-tenant rows dedup per
|
|
29
|
+
* tenant.
|
|
30
|
+
*
|
|
31
|
+
* Index NAMES stay stable across this change — the tenant-led default key
|
|
32
|
+
* keeps `<table>_slug_context_idx` (CTI) / `<table>_slug_context_meta_type_idx`
|
|
33
|
+
* (STI) — so `SchemaComparer`'s same-name shape-drift repair swaps the columns
|
|
34
|
+
* in place (`DROP INDEX` + `CREATE UNIQUE INDEX`) instead of leaving the old
|
|
35
|
+
* global unique index behind to keep blocking cross-tenant duplicates. The new
|
|
36
|
+
* key is a superset of the old one, so creating it cannot fail on existing
|
|
37
|
+
* data.
|
|
38
|
+
*/
|
|
39
|
+
/** Default natural key of a class-per-table (CTI) object. */
|
|
40
|
+
var DEFAULT_CTI_CONFLICT_COLUMNS = ["slug", "context"];
|
|
41
|
+
/**
|
|
42
|
+
* Default natural key of a single-table-inheritance (STI) hierarchy: the
|
|
43
|
+
* discriminator participates in identity so two subtypes may share a slug.
|
|
44
|
+
*/
|
|
45
|
+
var DEFAULT_STI_CONFLICT_COLUMNS = [
|
|
46
|
+
"slug",
|
|
47
|
+
"context",
|
|
48
|
+
"_meta_type"
|
|
49
|
+
];
|
|
50
|
+
/**
|
|
51
|
+
* The default conflict target for a table with the given strategy, led by the
|
|
52
|
+
* tenant column when the schema-owning class is tenant-scoped.
|
|
53
|
+
*/
|
|
54
|
+
function defaultConflictColumns(strategy, tenantColumn) {
|
|
55
|
+
const naturalKey = strategy === "sti" ? [...DEFAULT_STI_CONFLICT_COLUMNS] : [...DEFAULT_CTI_CONFLICT_COLUMNS];
|
|
56
|
+
return tenantColumn ? [tenantColumn, ...naturalKey] : naturalKey;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Resolve the conflict target of a table.
|
|
60
|
+
*
|
|
61
|
+
* `explicit` (a declared `@smrt({ conflictColumns })`) always wins; otherwise
|
|
62
|
+
* the strategy default, tenant-led when `tenantColumn` is given.
|
|
63
|
+
*/
|
|
64
|
+
function resolveConflictColumns(options) {
|
|
65
|
+
if (options.explicit && options.explicit.length > 0) return [...options.explicit];
|
|
66
|
+
return defaultConflictColumns(options.strategy, options.tenantColumn);
|
|
67
|
+
}
|
|
68
|
+
function sameColumns(a, b) {
|
|
69
|
+
return a.length === b.length && a.every((column, i) => column === b[i]);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Whether `conflictColumns` is exactly a default natural key (CTI or STI),
|
|
73
|
+
* optionally led by `tenantColumn`. Used to keep the default index names
|
|
74
|
+
* stable when the tenant column is prepended.
|
|
75
|
+
*/
|
|
76
|
+
function isDefaultNaturalKey(conflictColumns, tenantColumn) {
|
|
77
|
+
const key = tenantColumn && conflictColumns[0] === tenantColumn ? conflictColumns.slice(1) : conflictColumns;
|
|
78
|
+
return sameColumns(key, DEFAULT_CTI_CONFLICT_COLUMNS) || sameColumns(key, DEFAULT_STI_CONFLICT_COLUMNS);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* The stable name of the unique conflict index for `conflictColumns`.
|
|
82
|
+
*
|
|
83
|
+
* - default CTI key `(slug, context)` → `<table>_slug_context_idx`
|
|
84
|
+
* - default STI key `(slug, context, _meta_type)` →
|
|
85
|
+
* `<table>_slug_context_meta_type_idx`
|
|
86
|
+
* - either default led by the tenant column → the SAME name as without it
|
|
87
|
+
* (#2360: the differ swaps the columns in place by name)
|
|
88
|
+
* - any custom key → `<table>_<first two columns>_idx` (the historical rule;
|
|
89
|
+
* a longer key keeps the two-column name so existing databases are not
|
|
90
|
+
* renamed)
|
|
91
|
+
*
|
|
92
|
+
* @param tenantColumn - the table's tenant column, when the schema owner is
|
|
93
|
+
* tenant-scoped; only consulted to recognize a tenant-led default key
|
|
94
|
+
*/
|
|
95
|
+
function conflictIndexName(tableName, conflictColumns, tenantColumn) {
|
|
96
|
+
const key = tenantColumn && conflictColumns[0] === tenantColumn && isDefaultNaturalKey(conflictColumns, tenantColumn) ? conflictColumns.slice(1) : conflictColumns;
|
|
97
|
+
if (sameColumns(key, DEFAULT_STI_CONFLICT_COLUMNS)) return `${tableName}_slug_context_meta_type_idx`;
|
|
98
|
+
return `${tableName}_${(key.length > 2 ? key.slice(0, 2) : key).join("_")}_idx`;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Whether an unqualified index over `indexColumns` serves slug lookups
|
|
102
|
+
* (`loadFromSlug()` / `getId()` / `getSavedId()` filter on `slug`, `context`):
|
|
103
|
+
* it leads with `slug`, or it is the tenant-led default key — a tenant-scoped
|
|
104
|
+
* lookup carries the tenant predicate (#2365) and is served by the prefix.
|
|
105
|
+
*/
|
|
106
|
+
function servesSlugLookup(indexColumns, tenantColumn) {
|
|
107
|
+
if (indexColumns[0] === "slug") return true;
|
|
108
|
+
return Boolean(tenantColumn && indexColumns[0] === tenantColumn && indexColumns[1] === "slug" && indexColumns[2] === "context");
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* The tenant column of a table, from the schema-owning class's normalized
|
|
112
|
+
* tenant-scoped configuration. Returns `undefined` when the class is not
|
|
113
|
+
* tenant-scoped or the configured field is not among its fields (the field is
|
|
114
|
+
* always injected for tenant-scoped classes; the guard keeps the runtime and
|
|
115
|
+
* build paths honest about the column actually existing).
|
|
116
|
+
*
|
|
117
|
+
* @param tenantField - the configured tenant field name (`tenantScoped.field`,
|
|
118
|
+
* default `tenantId`), or `undefined` when the class is not tenant-scoped
|
|
119
|
+
* @param hasField - whether the schema owner declares that field
|
|
120
|
+
* @param toColumn - field-name → column-name conversion (`toSnakeCase`)
|
|
121
|
+
*/
|
|
122
|
+
function resolveTenantColumn(tenantField, hasField, toColumn) {
|
|
123
|
+
if (!tenantField || !hasField(tenantField)) return void 0;
|
|
124
|
+
return toColumn(tenantField);
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
127
|
+
export { DEFAULT_CTI_CONFLICT_COLUMNS, DEFAULT_STI_CONFLICT_COLUMNS, conflictIndexName, defaultConflictColumns, isDefaultNaturalKey, resolveConflictColumns, resolveTenantColumn, servesSlugLookup };
|
|
128
|
+
|
|
129
|
+
//# sourceMappingURL=conflict-target.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conflict-target.js","names":[],"sources":["../../src/schema/conflict-target.ts"],"sourcesContent":["/**\n * Conflict target (upsert natural key) resolution shared by every schema path\n * and by the runtime (#2360, epic #2382 finding B1/A4).\n *\n * `SmrtObject.save()` upserts a NEW object on\n * `ObjectRegistry.getConflictColumns()`; the schema generator emits ONE unique\n * index over the same columns so `INSERT … ON CONFLICT (…)` binds on every\n * engine. Before #2360 the tenancy interceptor populated `tenant_id` on save\n * but neither the conflict target nor the unique index carried it, so a\n * second tenant creating the same natural key (`slug`, `context`) matched the\n * first tenant's row and `DO UPDATE SET` rewrote its `id` and `tenant_id`\n * (probed: tenant A's row was silently adopted by tenant B).\n *\n * The rule now: **a tenant-scoped class's default conflict target is\n * `[tenantColumn, ...naturalKey]`** on the build path (manifest\n * `decoratorConfig.conflictColumns`, materialized by\n * `ManifestGenerator.normalizeConflictColumns()`) and on the runtime path\n * (`ObjectRegistry.getConflictColumns()`), so schema and upsert agree by\n * construction. Explicit `@smrt({ conflictColumns })` always wins and is\n * never rewritten — a class that declares its own natural key owns it.\n *\n * NULL-tenant rows (`mode: 'optional'` outside a tenant context) keep the\n * SDK's null-aware upsert semantics: `@happyvertical/sql` matches conflict\n * columns with `IS NOT DISTINCT FROM`, so `(NULL, 'widget', '')` updates the\n * existing `(NULL, 'widget', '')` row through the model layer even though the\n * database index treats NULLs as distinct. Global rows therefore dedup among\n * themselves exactly as every row did before, and per-tenant rows dedup per\n * tenant.\n *\n * Index NAMES stay stable across this change — the tenant-led default key\n * keeps `<table>_slug_context_idx` (CTI) / `<table>_slug_context_meta_type_idx`\n * (STI) — so `SchemaComparer`'s same-name shape-drift repair swaps the columns\n * in place (`DROP INDEX` + `CREATE UNIQUE INDEX`) instead of leaving the old\n * global unique index behind to keep blocking cross-tenant duplicates. The new\n * key is a superset of the old one, so creating it cannot fail on existing\n * data.\n */\n\n/** Default natural key of a class-per-table (CTI) object. */\nexport const DEFAULT_CTI_CONFLICT_COLUMNS: readonly string[] = [\n 'slug',\n 'context',\n];\n\n/**\n * Default natural key of a single-table-inheritance (STI) hierarchy: the\n * discriminator participates in identity so two subtypes may share a slug.\n */\nexport const DEFAULT_STI_CONFLICT_COLUMNS: readonly string[] = [\n 'slug',\n 'context',\n '_meta_type',\n];\n\nexport type ConflictTableStrategy = 'cti' | 'sti';\n\n/**\n * The default conflict target for a table with the given strategy, led by the\n * tenant column when the schema-owning class is tenant-scoped.\n */\nexport function defaultConflictColumns(\n strategy: ConflictTableStrategy,\n tenantColumn?: string | null,\n): string[] {\n const naturalKey =\n strategy === 'sti'\n ? [...DEFAULT_STI_CONFLICT_COLUMNS]\n : [...DEFAULT_CTI_CONFLICT_COLUMNS];\n return tenantColumn ? [tenantColumn, ...naturalKey] : naturalKey;\n}\n\n/**\n * Resolve the conflict target of a table.\n *\n * `explicit` (a declared `@smrt({ conflictColumns })`) always wins; otherwise\n * the strategy default, tenant-led when `tenantColumn` is given.\n */\nexport function resolveConflictColumns(options: {\n explicit?: readonly string[] | null;\n strategy: ConflictTableStrategy;\n tenantColumn?: string | null;\n}): string[] {\n if (options.explicit && options.explicit.length > 0) {\n return [...options.explicit];\n }\n return defaultConflictColumns(options.strategy, options.tenantColumn);\n}\n\nfunction sameColumns(a: readonly string[], b: readonly string[]): boolean {\n return a.length === b.length && a.every((column, i) => column === b[i]);\n}\n\n/**\n * Whether `conflictColumns` is exactly a default natural key (CTI or STI),\n * optionally led by `tenantColumn`. Used to keep the default index names\n * stable when the tenant column is prepended.\n */\nexport function isDefaultNaturalKey(\n conflictColumns: readonly string[],\n tenantColumn?: string | null,\n): boolean {\n const key =\n tenantColumn && conflictColumns[0] === tenantColumn\n ? conflictColumns.slice(1)\n : conflictColumns;\n return (\n sameColumns(key, DEFAULT_CTI_CONFLICT_COLUMNS) ||\n sameColumns(key, DEFAULT_STI_CONFLICT_COLUMNS)\n );\n}\n\n/**\n * The stable name of the unique conflict index for `conflictColumns`.\n *\n * - default CTI key `(slug, context)` → `<table>_slug_context_idx`\n * - default STI key `(slug, context, _meta_type)` →\n * `<table>_slug_context_meta_type_idx`\n * - either default led by the tenant column → the SAME name as without it\n * (#2360: the differ swaps the columns in place by name)\n * - any custom key → `<table>_<first two columns>_idx` (the historical rule;\n * a longer key keeps the two-column name so existing databases are not\n * renamed)\n *\n * @param tenantColumn - the table's tenant column, when the schema owner is\n * tenant-scoped; only consulted to recognize a tenant-led default key\n */\nexport function conflictIndexName(\n tableName: string,\n conflictColumns: readonly string[],\n tenantColumn?: string | null,\n): string {\n const key =\n tenantColumn &&\n conflictColumns[0] === tenantColumn &&\n isDefaultNaturalKey(conflictColumns, tenantColumn)\n ? conflictColumns.slice(1)\n : conflictColumns;\n if (sameColumns(key, DEFAULT_STI_CONFLICT_COLUMNS)) {\n return `${tableName}_slug_context_meta_type_idx`;\n }\n const nameColumns = key.length > 2 ? key.slice(0, 2) : key;\n return `${tableName}_${nameColumns.join('_')}_idx`;\n}\n\n/**\n * Whether an unqualified index over `indexColumns` serves slug lookups\n * (`loadFromSlug()` / `getId()` / `getSavedId()` filter on `slug`, `context`):\n * it leads with `slug`, or it is the tenant-led default key — a tenant-scoped\n * lookup carries the tenant predicate (#2365) and is served by the prefix.\n */\nexport function servesSlugLookup(\n indexColumns: readonly string[],\n tenantColumn?: string | null,\n): boolean {\n if (indexColumns[0] === 'slug') return true;\n return Boolean(\n tenantColumn &&\n indexColumns[0] === tenantColumn &&\n indexColumns[1] === 'slug' &&\n indexColumns[2] === 'context',\n );\n}\n\n/**\n * The tenant column of a table, from the schema-owning class's normalized\n * tenant-scoped configuration. Returns `undefined` when the class is not\n * tenant-scoped or the configured field is not among its fields (the field is\n * always injected for tenant-scoped classes; the guard keeps the runtime and\n * build paths honest about the column actually existing).\n *\n * @param tenantField - the configured tenant field name (`tenantScoped.field`,\n * default `tenantId`), or `undefined` when the class is not tenant-scoped\n * @param hasField - whether the schema owner declares that field\n * @param toColumn - field-name → column-name conversion (`toSnakeCase`)\n */\nexport function resolveTenantColumn(\n tenantField: string | undefined | null,\n hasField: (fieldName: string) => boolean,\n toColumn: (fieldName: string) => string,\n): string | undefined {\n if (!tenantField || !hasField(tenantField)) return undefined;\n return toColumn(tenantField);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAa,+BAAkD,CAC7D,QACA,SACF;;;;;AAMA,IAAa,+BAAkD;CAC7D;CACA;CACA;AACF;;;;;AAQA,SAAgB,uBACd,UACA,cACU;CACV,MAAM,aACJ,aAAa,QACT,CAAC,GAAG,4BAA4B,IAChC,CAAC,GAAG,4BAA4B;CACtC,OAAO,eAAe,CAAC,cAAc,GAAG,UAAU,IAAI;AACxD;;;;;;;AAQA,SAAgB,uBAAuB,SAI1B;CACX,IAAI,QAAQ,YAAY,QAAQ,SAAS,SAAS,GAChD,OAAO,CAAC,GAAG,QAAQ,QAAQ;CAE7B,OAAO,uBAAuB,QAAQ,UAAU,QAAQ,YAAY;AACtE;AAEA,SAAS,YAAY,GAAsB,GAA+B;CACxE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,QAAQ,MAAM,WAAW,EAAE,EAAE;AACxE;;;;;;AAOA,SAAgB,oBACd,iBACA,cACS;CACT,MAAM,MACJ,gBAAgB,gBAAgB,OAAO,eACnC,gBAAgB,MAAM,CAAC,IACvB;CACN,OACE,YAAY,KAAK,4BAA4B,KAC7C,YAAY,KAAK,4BAA4B;AAEjD;;;;;;;;;;;;;;;;AAiBA,SAAgB,kBACd,WACA,iBACA,cACQ;CACR,MAAM,MACJ,gBACA,gBAAgB,OAAO,gBACvB,oBAAoB,iBAAiB,YAAY,IAC7C,gBAAgB,MAAM,CAAC,IACvB;CACN,IAAI,YAAY,KAAK,4BAA4B,GAC/C,OAAO,GAAG,UAAU;CAGtB,OAAO,GAAG,UAAU,IADA,IAAI,SAAS,IAAI,IAAI,MAAM,GAAG,CAAC,IAAI,IAAA,CACpB,KAAK,GAAG,EAAE;AAC/C;;;;;;;AAQA,SAAgB,iBACd,cACA,cACS;CACT,IAAI,aAAa,OAAO,QAAQ,OAAO;CACvC,OAAO,QACL,gBACE,aAAa,OAAO,gBACpB,aAAa,OAAO,UACpB,aAAa,OAAO,SACxB;AACF;;;;;;;;;;;;;AAcA,SAAgB,oBACd,aACA,UACA,UACoB;CACpB,IAAI,CAAC,eAAe,CAAC,SAAS,WAAW,GAAG,OAAO,KAAA;CACnD,OAAO,SAAS,WAAW;AAC7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-strategy.d.ts","sourceRoot":"","sources":["../../../src/schema/ddl/base-strategy.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAUH,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EAClB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA4B9D;;;;;GAKG;AACH,8BAAsB,eAAgB,YAAW,WAAW;IAC1D,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAEzC;;OAEG;IACH,mBAAmB,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM;IAuBrD;;;;OAIG;IACH,wBAAwB,CACtB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,gBAAgB,GAC1B,MAAM;
|
|
1
|
+
{"version":3,"file":"base-strategy.d.ts","sourceRoot":"","sources":["../../../src/schema/ddl/base-strategy.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAUH,OAAO,KAAK,EACV,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,WAAW,EACX,iBAAiB,EAClB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AA4B9D;;;;;GAKG;AACH,8BAAsB,eAAgB,YAAW,WAAW;IAC1D,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAEzC;;OAEG;IACH,mBAAmB,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM;IAuBrD;;;;OAIG;IACH,wBAAwB,CACtB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,gBAAgB,GAC1B,MAAM;IA4CT;;;OAGG;IACH,SAAS,CAAC,+BAA+B,CACvC,OAAO,EAAE,eAAe,EAAE,GACzB,MAAM,EAAE;IA8BX;;;OAGG;IACH,eAAe,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM,EAAE;IAwDnD;;;;;OAKG;IACH,SAAS,CAAC,6BAA6B,CACrC,UAAU,EAAE,MAAM,EAClB,IAAI,EAAE,MAAM,GACX,MAAM;IAKT;;;OAGG;IACH,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM,EAAE;IAsBpD;;;OAGG;IACH,SAAS,CAAC,wBAAwB,CAChC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,iBAAiB,GACzB,MAAM;IAcT;;;OAGG;IACH,OAAO,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM;IA2BlC;;;;;;;;;OASG;IACH,kBAAkB,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,GAAG,MAAM;IAS7D;;;OAGG;IACH,SAAS,CAAC,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM;IAItD;;;OAGG;IACH,gBAAgB,IAAI,OAAO;IAI3B;;;OAGG;IACH,oBAAoB,IAAI,OAAO;CAGhC"}
|
|
@@ -53,8 +53,8 @@ var BaseDDLStrategy = class {
|
|
|
53
53
|
*/
|
|
54
54
|
generateColumnDefinition(columnName, columnDef) {
|
|
55
55
|
const parts = [quoteIdentifier(columnName), this.mapType(columnDef.type)];
|
|
56
|
-
if (columnDef.primaryKey) parts.push("PRIMARY KEY");
|
|
57
|
-
if (columnDef.notNull
|
|
56
|
+
if (columnDef.primaryKey) parts.push("PRIMARY KEY", "NOT NULL");
|
|
57
|
+
else if (columnDef.notNull) parts.push("NOT NULL");
|
|
58
58
|
if (columnDef.unique && !columnDef.primaryKey) parts.push("UNIQUE");
|
|
59
59
|
if (columnDef.defaultValue !== void 0) {
|
|
60
60
|
const formatted = this.formatDefaultValue(columnDef.defaultValue, columnDef.type);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-strategy.js","names":[],"sources":["../../../src/schema/ddl/base-strategy.ts"],"sourcesContent":["/**\n * Base DDL Strategy - Shared logic for all database engines\n *\n * Provides common DDL generation logic that engine-specific strategies\n * can override for their particular requirements.\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport {\n formatDefaultValue as formatDefaultValueShared,\n isSafeIdentifier,\n isSafeIdentifierPath,\n quoteIdentifier,\n quoteStringLiteral,\n} from '../sql-identifiers.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaDefinition,\n SQLDataType,\n TriggerDefinition,\n} from '../types.js';\nimport type { DatabaseEngine, DDLStrategy } from './types.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Validate the column + JSON path used to build a JSON-path index expression.\n *\n * The path segment is embedded as a SQL string literal inside a dialect\n * function/operator (`json_extract(\"col\", '$.path')` / `\"col\"->>'path'`), and\n * the column as a delimited identifier. We escape both, but also reject paths\n * or columns that aren't simple (dotted) identifiers so a malformed `@meta`\n * field name can't smuggle structure into the expression even after escaping.\n * These names are developer-controlled build-time inputs, so an invalid one is\n * a programming error and throwing is the safest, loudest outcome.\n */\nfunction assertSafeJsonPathTarget(jsonColumn: string, path: string): void {\n if (!isSafeIdentifier(jsonColumn)) {\n throw new Error(\n `[DDL] Unsafe JSON-path index column \"${jsonColumn}\": must be a simple identifier`,\n );\n }\n if (!isSafeIdentifierPath(path)) {\n throw new Error(\n `[DDL] Unsafe JSON-path index path \"${path}\": must be a simple (dotted) identifier`,\n );\n }\n}\n\n/**\n * Abstract base class for DDL strategies\n *\n * Implements common DDL generation patterns. Engine-specific strategies\n * extend this class and override methods as needed.\n */\nexport abstract class BaseDDLStrategy implements DDLStrategy {\n abstract readonly engine: DatabaseEngine;\n\n /**\n * Generate CREATE TABLE statement\n */\n generateCreateTable(schema: SchemaDefinition): string {\n const { tableName, columns, indexes = [] } = schema;\n\n let sql = `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(tableName)} (\\n`;\n\n // Generate column definitions\n const columnDefs: string[] = [];\n for (const [columnName, columnDef] of Object.entries(columns)) {\n columnDefs.push(this.generateColumnDefinition(columnName, columnDef));\n }\n\n // Add inline UNIQUE constraints for engines that require them\n if (this.requiresInlineUnique() && indexes.length > 0) {\n const uniqueConstraints = this.generateInlineUniqueConstraints(indexes);\n columnDefs.push(...uniqueConstraints);\n }\n\n sql += columnDefs.map((def) => ` ${def}`).join(',\\n');\n sql += '\\n);';\n\n return sql;\n }\n\n /**\n * Generate a single column definition\n *\n * Public so SchemaManager can reuse it for ALTER TABLE ADD COLUMN.\n */\n generateColumnDefinition(\n columnName: string,\n columnDef: ColumnDefinition,\n ): string {\n const parts: string[] = [\n quoteIdentifier(columnName),\n this.mapType(columnDef.type),\n ];\n\n // Primary key\n if (columnDef.primaryKey) {\n parts.push('PRIMARY KEY');\n }\n\n // NOT NULL (skip for primary key - it's implicit)\n if (columnDef.notNull && !columnDef.primaryKey) {\n parts.push('NOT NULL');\n }\n\n // Column-level UNIQUE is already inline and must be preserved for every\n // engine. Some published manifests express single-column uniqueness only\n // on the column definition (without a duplicate IndexDefinition), so\n // suppressing it for DuckDB/JSON would silently weaken the schema.\n if (columnDef.unique && !columnDef.primaryKey) {\n parts.push('UNIQUE');\n }\n\n // DEFAULT value\n if (columnDef.defaultValue !== undefined) {\n const formatted = this.formatDefaultValue(\n columnDef.defaultValue,\n columnDef.type,\n );\n parts.push(`DEFAULT ${formatted}`);\n }\n\n // CHECK constraint\n if (columnDef.check) {\n parts.push(`CHECK (${columnDef.check})`);\n }\n\n return parts.join(' ');\n }\n\n /**\n * Generate inline UNIQUE constraints for composite indexes\n * Used by engines that require inline UNIQUE for UPSERT to work (DuckDB)\n */\n protected generateInlineUniqueConstraints(\n indexes: IndexDefinition[],\n ): string[] {\n const constraints: string[] = [];\n\n if (!indexes || !Array.isArray(indexes)) {\n return constraints;\n }\n\n for (const index of indexes) {\n // Skip malformed index entries\n if (!index?.columns || !Array.isArray(index.columns)) {\n continue;\n }\n\n // Partial and expression-backed unique indexes are not valid generic\n // ON CONFLICT(column, ...) targets and cannot be represented as an\n // inline column UNIQUE constraint without changing their semantics.\n if (\n index.unique &&\n !index.where &&\n !index.jsonPath &&\n index.columns.length > 0\n ) {\n const columns = index.columns.map((c) => quoteIdentifier(c)).join(', ');\n constraints.push(`UNIQUE(${columns})`);\n }\n }\n\n return constraints;\n }\n\n /**\n * Generate CREATE INDEX statements\n * Override in engine-specific strategies if needed\n */\n generateIndexes(schema: SchemaDefinition): string[] {\n const { tableName, indexes = [] } = schema;\n const statements: string[] = [];\n\n if (!indexes || indexes.length === 0) {\n return statements;\n }\n\n for (const index of indexes) {\n // Narrow the jsonPath target up-front so the formatter call doesn't\n // need optional-chained args (and so the malformed-entry check has a\n // single source of truth).\n const jsonPath =\n index?.jsonPath?.column && index.jsonPath.path ? index.jsonPath : null;\n if (\n !index ||\n (!jsonPath &&\n (!index.columns ||\n !Array.isArray(index.columns) ||\n index.columns.length === 0))\n ) {\n logger.warn(`[DDL] Skipping malformed index: ${JSON.stringify(index)}`);\n continue;\n }\n\n // Skip UNIQUE indexes if engine requires them inline\n if (index.unique && this.requiresInlineUnique()) {\n continue;\n }\n\n const indexType = index.unique ? 'UNIQUE INDEX' : 'INDEX';\n\n // JSON-path indexes use a dialect-specific expression\n const target = jsonPath\n ? `(${this.formatJsonPathIndexExpression(\n jsonPath.column,\n jsonPath.path,\n )})`\n : index.columns.map((c) => quoteIdentifier(c)).join(', ');\n\n let sql = `CREATE ${indexType} IF NOT EXISTS ${quoteIdentifier(\n index.name,\n )} ON ${quoteIdentifier(tableName)} (${target})`;\n\n // Partial index condition\n if (index.where) {\n sql += ` WHERE ${index.where}`;\n }\n\n sql += ';';\n statements.push(sql);\n }\n\n return statements;\n }\n\n /**\n * Render the SQL expression used to index a JSON path inside a JSONB column.\n * Subclasses override for dialect-specific syntax.\n *\n * Default (ANSI-ish): `<jsonColumn>->>'<path>'` — works on Postgres.\n */\n protected formatJsonPathIndexExpression(\n jsonColumn: string,\n path: string,\n ): string {\n assertSafeJsonPathTarget(jsonColumn, path);\n return `${quoteIdentifier(jsonColumn)}->>${quoteStringLiteral(path)}`;\n }\n\n /**\n * Generate CREATE TRIGGER statements\n * Override in engine-specific strategies - DuckDB returns empty\n */\n generateTriggers(schema: SchemaDefinition): string[] {\n if (!this.supportsTriggers()) {\n return [];\n }\n\n const { tableName, triggers = [] } = schema;\n const statements: string[] = [];\n\n if (!triggers || triggers.length === 0) {\n return statements;\n }\n\n for (const trigger of triggers) {\n const sql = this.generateTriggerStatement(tableName, trigger);\n if (sql) {\n statements.push(sql);\n }\n }\n\n return statements;\n }\n\n /**\n * Generate a single trigger statement\n * Can be overridden for engine-specific trigger syntax\n */\n protected generateTriggerStatement(\n tableName: string,\n trigger: TriggerDefinition,\n ): string {\n // Default SQLite-style trigger syntax\n let sql = `CREATE TRIGGER IF NOT EXISTS ${quoteIdentifier(trigger.name)}\\n`;\n sql += `${trigger.when} ${trigger.event} ON ${quoteIdentifier(tableName)}\\n`;\n\n if (trigger.condition) {\n sql += `WHEN ${trigger.condition}\\n`;\n }\n\n sql += `BEGIN\\n${trigger.body}\\nEND;`;\n\n return sql;\n }\n\n /**\n * Map abstract SQL type to engine-specific type\n * Default implementation - override for engine-specific types\n */\n mapType(type: SQLDataType): string {\n // Default mapping works for most engines\n switch (type) {\n case 'TEXT':\n return 'TEXT';\n case 'INTEGER':\n return 'INTEGER';\n case 'REAL':\n return 'REAL';\n case 'BLOB':\n return 'BLOB';\n case 'BOOLEAN':\n return 'BOOLEAN';\n case 'JSON':\n return 'JSON';\n case 'TIMESTAMP':\n return 'TIMESTAMP';\n case 'UUID':\n // Fallback for engines without a native uuid type (e.g. SQLite):\n // store as TEXT. PostgreSQL/DuckDB override this with their native\n // uuid type. (R11)\n return 'TEXT';\n default:\n return 'TEXT';\n }\n }\n\n /**\n * Format default value for SQL.\n *\n * Delegates to the shared, injection-safe `formatDefaultValue`\n * (`schema/sql-identifiers.ts`) so every DDL path uses one set of rules:\n * an allowlist of SQL keyword/function defaults (not \"contains `(`\"),\n * type-driven literal quoting, and no folding of the string `\"null\"` into\n * the SQL NULL keyword. Boolean rendering is bridged through\n * `formatBooleanDefault` so engine overrides (SQLite → 0/1) still apply.\n */\n formatDefaultValue(value: unknown, type: SQLDataType): string {\n return formatDefaultValueShared(value, type, {\n booleanLiterals: [\n this.formatBooleanDefault(true),\n this.formatBooleanDefault(false),\n ],\n });\n }\n\n /**\n * Format boolean default\n * Override for engines that use INTEGER (SQLite)\n */\n protected formatBooleanDefault(value: boolean): string {\n return value ? 'TRUE' : 'FALSE';\n }\n\n /**\n * Whether this engine supports triggers\n * Override in DuckDB strategy to return false\n */\n supportsTriggers(): boolean {\n return true;\n }\n\n /**\n * Whether UNIQUE constraints must be inline for UPSERT\n * Override in DuckDB strategy to return true\n */\n requiresInlineUnique(): boolean {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;AAwBA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;;;;;;;;;;;AAa7C,SAAS,yBAAyB,YAAoB,MAAoB;CACxE,IAAI,CAAC,iBAAiB,UAAU,GAC9B,MAAM,IAAI,MACR,wCAAwC,WAAW,+BACrD;CAEF,IAAI,CAAC,qBAAqB,IAAI,GAC5B,MAAM,IAAI,MACR,sCAAsC,KAAK,wCAC7C;AAEJ;;;;;;;AAQA,IAAsB,kBAAtB,MAA6D;;;;CAM3D,oBAAoB,QAAkC;EACp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WAAW,CAAC,MAAM;EACrC,MAAM,aAAuB,CAAC;EAE9B,IAAI,CAAC,YAAY,SAAS,WAAW,GACnC,OAAO;EAGT,KAAK,MAAM,WAAW,UAAU;GAC9B,MAAM,MAAM,KAAK,yBAAyB,WAAW,OAAO;GAC5D,IAAI,KACF,WAAW,KAAK,GAAG;EAEvB;EAEA,OAAO;CACT;;;;;CAMA,yBACE,WACA,SACQ;EAER,IAAI,MAAM,gCAAgC,gBAAgB,QAAQ,IAAI,EAAE;EACxE,OAAO,GAAG,QAAQ,KAAK,GAAG,QAAQ,MAAM,MAAM,gBAAgB,SAAS,EAAE;EAEzE,IAAI,QAAQ,WACV,OAAO,QAAQ,QAAQ,UAAU;EAGnC,OAAO,UAAU,QAAQ,KAAK;EAE9B,OAAO;CACT;;;;;CAMA,QAAQ,MAA2B;EAEjC,QAAQ,MAAR;GACE,KAAK,QACH,OAAO;GACT,KAAK,WACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,KAAK,WACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,KAAK,aACH,OAAO;GACT,KAAK,QAIH,OAAO;GACT,SACE,OAAO;EACX;CACF;;;;;;;;;;;CAYA,mBAAmB,OAAgB,MAA2B;EAC5D,OAAO,mBAAyB,OAAO,MAAM,EAC3C,iBAAiB,CACf,KAAK,qBAAqB,IAAI,GAC9B,KAAK,qBAAqB,KAAK,CACjC,EACF,CAAC;CACH;;;;;CAMA,qBAA+B,OAAwB;EACrD,OAAO,QAAQ,SAAS;CAC1B;;;;;CAMA,mBAA4B;EAC1B,OAAO;CACT;;;;;CAMA,uBAAgC;EAC9B,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"base-strategy.js","names":[],"sources":["../../../src/schema/ddl/base-strategy.ts"],"sourcesContent":["/**\n * Base DDL Strategy - Shared logic for all database engines\n *\n * Provides common DDL generation logic that engine-specific strategies\n * can override for their particular requirements.\n */\n\nimport { createLogger } from '@happyvertical/logger';\nimport {\n formatDefaultValue as formatDefaultValueShared,\n isSafeIdentifier,\n isSafeIdentifierPath,\n quoteIdentifier,\n quoteStringLiteral,\n} from '../sql-identifiers.js';\nimport type {\n ColumnDefinition,\n IndexDefinition,\n SchemaDefinition,\n SQLDataType,\n TriggerDefinition,\n} from '../types.js';\nimport type { DatabaseEngine, DDLStrategy } from './types.js';\n\nconst logger = createLogger({ level: 'info' });\n\n/**\n * Validate the column + JSON path used to build a JSON-path index expression.\n *\n * The path segment is embedded as a SQL string literal inside a dialect\n * function/operator (`json_extract(\"col\", '$.path')` / `\"col\"->>'path'`), and\n * the column as a delimited identifier. We escape both, but also reject paths\n * or columns that aren't simple (dotted) identifiers so a malformed `@meta`\n * field name can't smuggle structure into the expression even after escaping.\n * These names are developer-controlled build-time inputs, so an invalid one is\n * a programming error and throwing is the safest, loudest outcome.\n */\nfunction assertSafeJsonPathTarget(jsonColumn: string, path: string): void {\n if (!isSafeIdentifier(jsonColumn)) {\n throw new Error(\n `[DDL] Unsafe JSON-path index column \"${jsonColumn}\": must be a simple identifier`,\n );\n }\n if (!isSafeIdentifierPath(path)) {\n throw new Error(\n `[DDL] Unsafe JSON-path index path \"${path}\": must be a simple (dotted) identifier`,\n );\n }\n}\n\n/**\n * Abstract base class for DDL strategies\n *\n * Implements common DDL generation patterns. Engine-specific strategies\n * extend this class and override methods as needed.\n */\nexport abstract class BaseDDLStrategy implements DDLStrategy {\n abstract readonly engine: DatabaseEngine;\n\n /**\n * Generate CREATE TABLE statement\n */\n generateCreateTable(schema: SchemaDefinition): string {\n const { tableName, columns, indexes = [] } = schema;\n\n let sql = `CREATE TABLE IF NOT EXISTS ${quoteIdentifier(tableName)} (\\n`;\n\n // Generate column definitions\n const columnDefs: string[] = [];\n for (const [columnName, columnDef] of Object.entries(columns)) {\n columnDefs.push(this.generateColumnDefinition(columnName, columnDef));\n }\n\n // Add inline UNIQUE constraints for engines that require them\n if (this.requiresInlineUnique() && indexes.length > 0) {\n const uniqueConstraints = this.generateInlineUniqueConstraints(indexes);\n columnDefs.push(...uniqueConstraints);\n }\n\n sql += columnDefs.map((def) => ` ${def}`).join(',\\n');\n sql += '\\n);';\n\n return sql;\n }\n\n /**\n * Generate a single column definition\n *\n * Public so SchemaManager can reuse it for ALTER TABLE ADD COLUMN.\n */\n generateColumnDefinition(\n columnName: string,\n columnDef: ColumnDefinition,\n ): string {\n const parts: string[] = [\n quoteIdentifier(columnName),\n this.mapType(columnDef.type),\n ];\n\n // Primary key. NOT NULL is emitted explicitly as well: SQLite's legacy\n // behaviour lets a non-INTEGER PRIMARY KEY column hold NULL, so a bare\n // `\"id\" TEXT PRIMARY KEY` accepts NULL ids there (#2358). PostgreSQL and\n // DuckDB already imply NOT NULL for a primary key; the explicit clause is\n // redundant but valid on every engine, and matches the engine-neutral\n // `SchemaGenerator.generateSQL()` output for SMRT-generated id columns\n // (which always carry `notNull: true`).\n if (columnDef.primaryKey) {\n parts.push('PRIMARY KEY', 'NOT NULL');\n } else if (columnDef.notNull) {\n parts.push('NOT NULL');\n }\n\n // Column-level UNIQUE is already inline and must be preserved for every\n // engine. Some published manifests express single-column uniqueness only\n // on the column definition (without a duplicate IndexDefinition), so\n // suppressing it for DuckDB/JSON would silently weaken the schema.\n if (columnDef.unique && !columnDef.primaryKey) {\n parts.push('UNIQUE');\n }\n\n // DEFAULT value\n if (columnDef.defaultValue !== undefined) {\n const formatted = this.formatDefaultValue(\n columnDef.defaultValue,\n columnDef.type,\n );\n parts.push(`DEFAULT ${formatted}`);\n }\n\n // CHECK constraint\n if (columnDef.check) {\n parts.push(`CHECK (${columnDef.check})`);\n }\n\n return parts.join(' ');\n }\n\n /**\n * Generate inline UNIQUE constraints for composite indexes\n * Used by engines that require inline UNIQUE for UPSERT to work (DuckDB)\n */\n protected generateInlineUniqueConstraints(\n indexes: IndexDefinition[],\n ): string[] {\n const constraints: string[] = [];\n\n if (!indexes || !Array.isArray(indexes)) {\n return constraints;\n }\n\n for (const index of indexes) {\n // Skip malformed index entries\n if (!index?.columns || !Array.isArray(index.columns)) {\n continue;\n }\n\n // Partial and expression-backed unique indexes are not valid generic\n // ON CONFLICT(column, ...) targets and cannot be represented as an\n // inline column UNIQUE constraint without changing their semantics.\n if (\n index.unique &&\n !index.where &&\n !index.jsonPath &&\n index.columns.length > 0\n ) {\n const columns = index.columns.map((c) => quoteIdentifier(c)).join(', ');\n constraints.push(`UNIQUE(${columns})`);\n }\n }\n\n return constraints;\n }\n\n /**\n * Generate CREATE INDEX statements\n * Override in engine-specific strategies if needed\n */\n generateIndexes(schema: SchemaDefinition): string[] {\n const { tableName, indexes = [] } = schema;\n const statements: string[] = [];\n\n if (!indexes || indexes.length === 0) {\n return statements;\n }\n\n for (const index of indexes) {\n // Narrow the jsonPath target up-front so the formatter call doesn't\n // need optional-chained args (and so the malformed-entry check has a\n // single source of truth).\n const jsonPath =\n index?.jsonPath?.column && index.jsonPath.path ? index.jsonPath : null;\n if (\n !index ||\n (!jsonPath &&\n (!index.columns ||\n !Array.isArray(index.columns) ||\n index.columns.length === 0))\n ) {\n logger.warn(`[DDL] Skipping malformed index: ${JSON.stringify(index)}`);\n continue;\n }\n\n // Skip UNIQUE indexes if engine requires them inline\n if (index.unique && this.requiresInlineUnique()) {\n continue;\n }\n\n const indexType = index.unique ? 'UNIQUE INDEX' : 'INDEX';\n\n // JSON-path indexes use a dialect-specific expression\n const target = jsonPath\n ? `(${this.formatJsonPathIndexExpression(\n jsonPath.column,\n jsonPath.path,\n )})`\n : index.columns.map((c) => quoteIdentifier(c)).join(', ');\n\n let sql = `CREATE ${indexType} IF NOT EXISTS ${quoteIdentifier(\n index.name,\n )} ON ${quoteIdentifier(tableName)} (${target})`;\n\n // Partial index condition\n if (index.where) {\n sql += ` WHERE ${index.where}`;\n }\n\n sql += ';';\n statements.push(sql);\n }\n\n return statements;\n }\n\n /**\n * Render the SQL expression used to index a JSON path inside a JSONB column.\n * Subclasses override for dialect-specific syntax.\n *\n * Default (ANSI-ish): `<jsonColumn>->>'<path>'` — works on Postgres.\n */\n protected formatJsonPathIndexExpression(\n jsonColumn: string,\n path: string,\n ): string {\n assertSafeJsonPathTarget(jsonColumn, path);\n return `${quoteIdentifier(jsonColumn)}->>${quoteStringLiteral(path)}`;\n }\n\n /**\n * Generate CREATE TRIGGER statements\n * Override in engine-specific strategies - DuckDB returns empty\n */\n generateTriggers(schema: SchemaDefinition): string[] {\n if (!this.supportsTriggers()) {\n return [];\n }\n\n const { tableName, triggers = [] } = schema;\n const statements: string[] = [];\n\n if (!triggers || triggers.length === 0) {\n return statements;\n }\n\n for (const trigger of triggers) {\n const sql = this.generateTriggerStatement(tableName, trigger);\n if (sql) {\n statements.push(sql);\n }\n }\n\n return statements;\n }\n\n /**\n * Generate a single trigger statement\n * Can be overridden for engine-specific trigger syntax\n */\n protected generateTriggerStatement(\n tableName: string,\n trigger: TriggerDefinition,\n ): string {\n // Default SQLite-style trigger syntax\n let sql = `CREATE TRIGGER IF NOT EXISTS ${quoteIdentifier(trigger.name)}\\n`;\n sql += `${trigger.when} ${trigger.event} ON ${quoteIdentifier(tableName)}\\n`;\n\n if (trigger.condition) {\n sql += `WHEN ${trigger.condition}\\n`;\n }\n\n sql += `BEGIN\\n${trigger.body}\\nEND;`;\n\n return sql;\n }\n\n /**\n * Map abstract SQL type to engine-specific type\n * Default implementation - override for engine-specific types\n */\n mapType(type: SQLDataType): string {\n // Default mapping works for most engines\n switch (type) {\n case 'TEXT':\n return 'TEXT';\n case 'INTEGER':\n return 'INTEGER';\n case 'REAL':\n return 'REAL';\n case 'BLOB':\n return 'BLOB';\n case 'BOOLEAN':\n return 'BOOLEAN';\n case 'JSON':\n return 'JSON';\n case 'TIMESTAMP':\n return 'TIMESTAMP';\n case 'UUID':\n // Fallback for engines without a native uuid type (e.g. SQLite):\n // store as TEXT. PostgreSQL/DuckDB override this with their native\n // uuid type. (R11)\n return 'TEXT';\n default:\n return 'TEXT';\n }\n }\n\n /**\n * Format default value for SQL.\n *\n * Delegates to the shared, injection-safe `formatDefaultValue`\n * (`schema/sql-identifiers.ts`) so every DDL path uses one set of rules:\n * an allowlist of SQL keyword/function defaults (not \"contains `(`\"),\n * type-driven literal quoting, and no folding of the string `\"null\"` into\n * the SQL NULL keyword. Boolean rendering is bridged through\n * `formatBooleanDefault` so engine overrides (SQLite → 0/1) still apply.\n */\n formatDefaultValue(value: unknown, type: SQLDataType): string {\n return formatDefaultValueShared(value, type, {\n booleanLiterals: [\n this.formatBooleanDefault(true),\n this.formatBooleanDefault(false),\n ],\n });\n }\n\n /**\n * Format boolean default\n * Override for engines that use INTEGER (SQLite)\n */\n protected formatBooleanDefault(value: boolean): string {\n return value ? 'TRUE' : 'FALSE';\n }\n\n /**\n * Whether this engine supports triggers\n * Override in DuckDB strategy to return false\n */\n supportsTriggers(): boolean {\n return true;\n }\n\n /**\n * Whether UNIQUE constraints must be inline for UPSERT\n * Override in DuckDB strategy to return true\n */\n requiresInlineUnique(): boolean {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;AAwBA,IAAM,SAAS,aAAa,EAAE,OAAO,OAAO,CAAC;;;;;;;;;;;;AAa7C,SAAS,yBAAyB,YAAoB,MAAoB;CACxE,IAAI,CAAC,iBAAiB,UAAU,GAC9B,MAAM,IAAI,MACR,wCAAwC,WAAW,+BACrD;CAEF,IAAI,CAAC,qBAAqB,IAAI,GAC5B,MAAM,IAAI,MACR,sCAAsC,KAAK,wCAC7C;AAEJ;;;;;;;AAQA,IAAsB,kBAAtB,MAA6D;;;;CAM3D,oBAAoB,QAAkC;EACpD,MAAM,EAAE,WAAW,SAAS,UAAU,CAAC,MAAM;EAE7C,IAAI,MAAM,8BAA8B,gBAAgB,SAAS,EAAE;EAGnE,MAAM,aAAuB,CAAC;EAC9B,KAAK,MAAM,CAAC,YAAY,cAAc,OAAO,QAAQ,OAAO,GAC1D,WAAW,KAAK,KAAK,yBAAyB,YAAY,SAAS,CAAC;EAItE,IAAI,KAAK,qBAAqB,KAAK,QAAQ,SAAS,GAAG;GACrD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,MAAM,EAAE,gBAAgB,GAAG,MAAM,EAAE;
|
|
1
|
+
{"version":3,"file":"duckdb-strategy.d.ts","sourceRoot":"","sources":["../../../src/schema/ddl/duckdb-strategy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACjE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,qBAAa,cAAe,SAAQ,eAAe;IACjD,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAY;IAE3C;;;OAGG;IACH,OAAO,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM;IAalC;;;;OAIG;IACH,eAAe,CAAC,MAAM,EAAE,gBAAgB,GAAG,MAAM,EAAE;IAwCnD;;OAEG;IACH,gBAAgB,CAAC,OAAO,EAAE,gBAAgB,GAAG,MAAM,EAAE;IAIrD;;OAEG;IACH,gBAAgB,IAAI,OAAO;IAI3B;;;;;OAKG;IACH,oBAAoB,IAAI,OAAO;CAGhC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { BaseDDLStrategy } from "./base-strategy.js";
|
|
2
|
-
import { renderIndexTarget } from "../index-utils.js";
|
|
2
|
+
import { isStiSubtypeUniqueIndex, renderIndexTarget } from "../index-utils.js";
|
|
3
3
|
//#region src/schema/ddl/duckdb-strategy.ts
|
|
4
4
|
/**
|
|
5
5
|
* DuckDB DDL Strategy
|
|
@@ -37,6 +37,7 @@ var DuckDBStrategy = class extends BaseDDLStrategy {
|
|
|
37
37
|
const statements = [];
|
|
38
38
|
for (const index of indexes) {
|
|
39
39
|
if (index.unique && !index.where && !index.jsonPath) continue;
|
|
40
|
+
if (isStiSubtypeUniqueIndex(index)) continue;
|
|
40
41
|
const target = renderIndexTarget(index, this.engine);
|
|
41
42
|
if (!target) continue;
|
|
42
43
|
let sql = `CREATE ${index.unique ? "UNIQUE INDEX" : "INDEX"} IF NOT EXISTS "${index.name}" ON "${tableName}" (${target})`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"duckdb-strategy.js","names":[],"sources":["../../../src/schema/ddl/duckdb-strategy.ts"],"sourcesContent":["/**\n * DuckDB DDL Strategy\n *\n * DuckDB-specific DDL generation with the following characteristics:\n * - UNIQUE constraints MUST be inline for UPSERT to work (DuckDB issue #12684)\n * - Supports CAST in DEFAULT values\n * - Native BOOLEAN, JSON types\n * - Does NOT support triggers\n *\n * CRITICAL: DuckDB's ON CONFLICT clause only works with inline UNIQUE constraints,\n * not with separate UNIQUE indexes. This is a known DuckDB limitation.\n */\n\nimport { renderIndexTarget } from '../index-utils.js';\nimport type { SchemaDefinition, SQLDataType } from '../types.js';\nimport { BaseDDLStrategy } from './base-strategy.js';\nimport type { DatabaseEngine } from './types.js';\n\nexport class DuckDBStrategy extends BaseDDLStrategy {\n readonly engine: DatabaseEngine = 'duckdb';\n\n /**\n * Map types for DuckDB\n * DuckDB has native support for most types\n */\n mapType(type: SQLDataType): string {\n switch (type) {\n case 'TIMESTAMP':\n return 'TIMESTAMP'; // DuckDB supports TIMESTAMP natively\n case 'JSON':\n return 'JSON'; // DuckDB has native JSON type\n case 'UUID':\n return 'UUID'; // DuckDB has a native UUID type (R11)\n default:\n return super.mapType(type);\n }\n }\n\n /**\n * Generate CREATE INDEX statements\n *\n * CRITICAL: Skip UNIQUE indexes - they must be inline constraints for UPSERT\n */\n generateIndexes(schema: SchemaDefinition): string[] {\n const { tableName, indexes } = schema;\n const statements: string[] = [];\n\n for (const index of indexes) {\n // Skip UNIQUE indexes - they're inline constraints\n if (index.unique && !index.where && !index.jsonPath) {\n continue;\n }\n\n const target = renderIndexTarget(index, this.engine);\n if (!target) {\n continue;\n }\n const indexType = index.unique ? 'UNIQUE INDEX' : 'INDEX';\n let sql = `CREATE ${indexType} IF NOT EXISTS \"${index.name}\" ON \"${tableName}\" (${target})`;\n\n // DuckDB (and the JSON adapter backed by it) rejects partial indexes.\n // Match the migration differ's documented compatibility behavior by\n // degrading the declaration to a full index while preserving UNIQUE.\n\n sql += ';';\n statements.push(sql);\n }\n\n return statements;\n }\n\n /**\n * DuckDB does NOT support triggers\n */\n generateTriggers(_schema: SchemaDefinition): string[] {\n return []; // DuckDB doesn't support triggers\n }\n\n /**\n * DuckDB does NOT support triggers\n */\n supportsTriggers(): boolean {\n return false;\n }\n\n /**\n * CRITICAL: DuckDB requires inline UNIQUE for UPSERT\n *\n * DuckDB issue #12684: ON CONFLICT only works with inline UNIQUE constraints,\n * not with separate CREATE UNIQUE INDEX statements.\n */\n requiresInlineUnique(): boolean {\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,iBAAb,cAAoC,gBAAgB;CAClD,SAAkC;;;;;CAMlC,QAAQ,MAA2B;EACjC,QAAQ,MAAR;GACE,KAAK,aACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,SACE,OAAO,MAAM,QAAQ,IAAI;EAC7B;CACF;;;;;;CAOA,gBAAgB,QAAoC;EAClD,MAAM,EAAE,WAAW,YAAY;EAC/B,MAAM,aAAuB,CAAC;EAE9B,KAAK,MAAM,SAAS,SAAS;GAE3B,IAAI,MAAM,UAAU,CAAC,MAAM,SAAS,CAAC,MAAM,UACzC;GAGF,MAAM,SAAS,kBAAkB,OAAO,KAAK,MAAM;GACnD,IAAI,CAAC,QACH;GAGF,IAAI,MAAM,UADQ,MAAM,SAAS,iBAAiB,QACpB,kBAAkB,MAAM,KAAK,QAAQ,UAAU,KAAK,OAAO;GAMzF,OAAO;GACP,WAAW,KAAK,GAAG;EACrB;EAEA,OAAO;CACT;;;;CAKA,iBAAiB,SAAqC;EACpD,OAAO,CAAC;CACV;;;;CAKA,mBAA4B;EAC1B,OAAO;CACT;;;;;;;CAQA,uBAAgC;EAC9B,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"duckdb-strategy.js","names":[],"sources":["../../../src/schema/ddl/duckdb-strategy.ts"],"sourcesContent":["/**\n * DuckDB DDL Strategy\n *\n * DuckDB-specific DDL generation with the following characteristics:\n * - UNIQUE constraints MUST be inline for UPSERT to work (DuckDB issue #12684)\n * - Supports CAST in DEFAULT values\n * - Native BOOLEAN, JSON types\n * - Does NOT support triggers\n *\n * CRITICAL: DuckDB's ON CONFLICT clause only works with inline UNIQUE constraints,\n * not with separate UNIQUE indexes. This is a known DuckDB limitation.\n */\n\nimport { isStiSubtypeUniqueIndex, renderIndexTarget } from '../index-utils.js';\nimport type { SchemaDefinition, SQLDataType } from '../types.js';\nimport { BaseDDLStrategy } from './base-strategy.js';\nimport type { DatabaseEngine } from './types.js';\n\nexport class DuckDBStrategy extends BaseDDLStrategy {\n readonly engine: DatabaseEngine = 'duckdb';\n\n /**\n * Map types for DuckDB\n * DuckDB has native support for most types\n */\n mapType(type: SQLDataType): string {\n switch (type) {\n case 'TIMESTAMP':\n return 'TIMESTAMP'; // DuckDB supports TIMESTAMP natively\n case 'JSON':\n return 'JSON'; // DuckDB has native JSON type\n case 'UUID':\n return 'UUID'; // DuckDB has a native UUID type (R11)\n default:\n return super.mapType(type);\n }\n }\n\n /**\n * Generate CREATE INDEX statements\n *\n * CRITICAL: Skip UNIQUE indexes - they must be inline constraints for UPSERT\n */\n generateIndexes(schema: SchemaDefinition): string[] {\n const { tableName, indexes } = schema;\n const statements: string[] = [];\n\n for (const index of indexes) {\n // Skip UNIQUE indexes - they're inline constraints\n if (index.unique && !index.where && !index.jsonPath) {\n continue;\n }\n\n // An STI subtype-scoped UNIQUE (`unique: true` declared only on a\n // descendant, #2359) cannot degrade to a full index the way the other\n // partial indexes below do: dropping the predicate while keeping UNIQUE\n // would enforce one subtype's constraint across every sibling's rows in\n // the shared table. DuckDB has no faithful shape for it, so it is not\n // emitted here (nor by the migration differ on this engine) — the\n // constraint is simply not enforced on DuckDB/JSON. Caller-declared\n // partial uniques (`WHERE active = TRUE`) keep degrading to full UNIQUE.\n if (isStiSubtypeUniqueIndex(index)) {\n continue;\n }\n\n const target = renderIndexTarget(index, this.engine);\n if (!target) {\n continue;\n }\n const indexType = index.unique ? 'UNIQUE INDEX' : 'INDEX';\n let sql = `CREATE ${indexType} IF NOT EXISTS \"${index.name}\" ON \"${tableName}\" (${target})`;\n\n // DuckDB (and the JSON adapter backed by it) rejects partial indexes.\n // Match the migration differ's documented compatibility behavior by\n // degrading the declaration to a full index while preserving UNIQUE.\n\n sql += ';';\n statements.push(sql);\n }\n\n return statements;\n }\n\n /**\n * DuckDB does NOT support triggers\n */\n generateTriggers(_schema: SchemaDefinition): string[] {\n return []; // DuckDB doesn't support triggers\n }\n\n /**\n * DuckDB does NOT support triggers\n */\n supportsTriggers(): boolean {\n return false;\n }\n\n /**\n * CRITICAL: DuckDB requires inline UNIQUE for UPSERT\n *\n * DuckDB issue #12684: ON CONFLICT only works with inline UNIQUE constraints,\n * not with separate CREATE UNIQUE INDEX statements.\n */\n requiresInlineUnique(): boolean {\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAa,iBAAb,cAAoC,gBAAgB;CAClD,SAAkC;;;;;CAMlC,QAAQ,MAA2B;EACjC,QAAQ,MAAR;GACE,KAAK,aACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,SACE,OAAO,MAAM,QAAQ,IAAI;EAC7B;CACF;;;;;;CAOA,gBAAgB,QAAoC;EAClD,MAAM,EAAE,WAAW,YAAY;EAC/B,MAAM,aAAuB,CAAC;EAE9B,KAAK,MAAM,SAAS,SAAS;GAE3B,IAAI,MAAM,UAAU,CAAC,MAAM,SAAS,CAAC,MAAM,UACzC;GAWF,IAAI,wBAAwB,KAAK,GAC/B;GAGF,MAAM,SAAS,kBAAkB,OAAO,KAAK,MAAM;GACnD,IAAI,CAAC,QACH;GAGF,IAAI,MAAM,UADQ,MAAM,SAAS,iBAAiB,QACpB,kBAAkB,MAAM,KAAK,QAAQ,UAAU,KAAK,OAAO;GAMzF,OAAO;GACP,WAAW,KAAK,GAAG;EACrB;EAEA,OAAO;CACT;;;;CAKA,iBAAiB,SAAqC;EACpD,OAAO,CAAC;CACV;;;;CAKA,mBAA4B;EAC1B,OAAO;CACT;;;;;;;CAQA,uBAAgC;EAC9B,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-strategy.d.ts","sourceRoot":"","sources":["../../../src/schema/ddl/postgres-strategy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;
|
|
1
|
+
{"version":3,"file":"postgres-strategy.d.ts","sourceRoot":"","sources":["../../../src/schema/ddl/postgres-strategy.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,qBAAa,gBAAiB,SAAQ,eAAe;IACnD,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAc;IAE7C;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,WAAW,GAAG,MAAM;IAkBlC;;;;;OAKG;IACH,SAAS,CAAC,wBAAwB,CAChC,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE,iBAAiB,GACzB,MAAM;IAsDT;;OAEG;IACH,gBAAgB,IAAI,OAAO;IAI3B;;;OAGG;IACH,oBAAoB,IAAI,OAAO;CAGhC"}
|
|
@@ -1,5 +1,16 @@
|
|
|
1
1
|
import { BaseDDLStrategy } from "./base-strategy.js";
|
|
2
|
+
import { shortenIdentifier } from "../index-utils.js";
|
|
2
3
|
//#region src/schema/ddl/postgres-strategy.ts
|
|
4
|
+
/**
|
|
5
|
+
* PostgreSQL DDL Strategy
|
|
6
|
+
*
|
|
7
|
+
* PostgreSQL-specific DDL generation with the following characteristics:
|
|
8
|
+
* - JSONB type for JSON columns (more efficient than JSON)
|
|
9
|
+
* - Native BOOLEAN type
|
|
10
|
+
* - Full trigger support with PL/pgSQL functions
|
|
11
|
+
* - UNIQUE can be inline or separate indexes
|
|
12
|
+
* - Supports CAST in DEFAULT values
|
|
13
|
+
*/
|
|
3
14
|
var PostgresStrategy = class extends BaseDDLStrategy {
|
|
4
15
|
engine = "postgres";
|
|
5
16
|
/**
|
|
@@ -24,7 +35,7 @@ var PostgresStrategy = class extends BaseDDLStrategy {
|
|
|
24
35
|
*/
|
|
25
36
|
generateTriggerStatement(tableName, trigger) {
|
|
26
37
|
if (trigger.name.includes("updated_at")) {
|
|
27
|
-
const functionName = `update_${tableName}_updated_at
|
|
38
|
+
const functionName = shortenIdentifier(`update_${tableName}_updated_at`);
|
|
28
39
|
let sql = `-- Function for ${trigger.name}\n`;
|
|
29
40
|
sql += `CREATE OR REPLACE FUNCTION ${functionName}()\n`;
|
|
30
41
|
sql += `RETURNS TRIGGER AS $$\n`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postgres-strategy.js","names":[],"sources":["../../../src/schema/ddl/postgres-strategy.ts"],"sourcesContent":["/**\n * PostgreSQL DDL Strategy\n *\n * PostgreSQL-specific DDL generation with the following characteristics:\n * - JSONB type for JSON columns (more efficient than JSON)\n * - Native BOOLEAN type\n * - Full trigger support with PL/pgSQL functions\n * - UNIQUE can be inline or separate indexes\n * - Supports CAST in DEFAULT values\n */\n\nimport type { SQLDataType, TriggerDefinition } from '../types.js';\nimport { BaseDDLStrategy } from './base-strategy.js';\nimport type { DatabaseEngine } from './types.js';\n\nexport class PostgresStrategy extends BaseDDLStrategy {\n readonly engine: DatabaseEngine = 'postgres';\n\n /**\n * Map types for PostgreSQL\n * - JSON → JSONB (more efficient, supports indexing)\n * - TIMESTAMP → TIMESTAMP WITH TIME ZONE (best practice)\n */\n mapType(type: SQLDataType): string {\n switch (type) {\n case 'JSON':\n return 'JSONB'; // PostgreSQL JSONB is more efficient\n case 'TIMESTAMP':\n // JavaScript Date represents an instant. Preserve that contract in\n // PostgreSQL instead of discarding the ISO offset in a timezone-naive\n // TIMESTAMP column and reinterpreting the wall time at hydration.\n return 'TIMESTAMPTZ';\n case 'REAL':\n return 'DOUBLE PRECISION'; // PostgreSQL convention\n case 'UUID':\n return 'uuid'; // Native 16-byte uuid (R11) — vs 37-byte text\n default:\n return super.mapType(type);\n }\n }\n\n /**\n * Generate trigger for PostgreSQL\n *\n * PostgreSQL triggers require a separate function, then the trigger.\n * For updated_at timestamps, we generate both.\n */\n protected generateTriggerStatement(\n tableName: string,\n trigger: TriggerDefinition,\n ): string {\n // For simple triggers, we need to create a function first\n // This is PostgreSQL's two-step trigger process\n\n // Check if this is an updated_at trigger\n if (trigger.name.includes('updated_at')) {\n // Generate the function and trigger for updated_at\n const functionName = `update_${tableName}_updated_at
|
|
1
|
+
{"version":3,"file":"postgres-strategy.js","names":[],"sources":["../../../src/schema/ddl/postgres-strategy.ts"],"sourcesContent":["/**\n * PostgreSQL DDL Strategy\n *\n * PostgreSQL-specific DDL generation with the following characteristics:\n * - JSONB type for JSON columns (more efficient than JSON)\n * - Native BOOLEAN type\n * - Full trigger support with PL/pgSQL functions\n * - UNIQUE can be inline or separate indexes\n * - Supports CAST in DEFAULT values\n */\n\nimport { shortenIdentifier } from '../index-utils.js';\nimport type { SQLDataType, TriggerDefinition } from '../types.js';\nimport { BaseDDLStrategy } from './base-strategy.js';\nimport type { DatabaseEngine } from './types.js';\n\nexport class PostgresStrategy extends BaseDDLStrategy {\n readonly engine: DatabaseEngine = 'postgres';\n\n /**\n * Map types for PostgreSQL\n * - JSON → JSONB (more efficient, supports indexing)\n * - TIMESTAMP → TIMESTAMP WITH TIME ZONE (best practice)\n */\n mapType(type: SQLDataType): string {\n switch (type) {\n case 'JSON':\n return 'JSONB'; // PostgreSQL JSONB is more efficient\n case 'TIMESTAMP':\n // JavaScript Date represents an instant. Preserve that contract in\n // PostgreSQL instead of discarding the ISO offset in a timezone-naive\n // TIMESTAMP column and reinterpreting the wall time at hydration.\n return 'TIMESTAMPTZ';\n case 'REAL':\n return 'DOUBLE PRECISION'; // PostgreSQL convention\n case 'UUID':\n return 'uuid'; // Native 16-byte uuid (R11) — vs 37-byte text\n default:\n return super.mapType(type);\n }\n }\n\n /**\n * Generate trigger for PostgreSQL\n *\n * PostgreSQL triggers require a separate function, then the trigger.\n * For updated_at timestamps, we generate both.\n */\n protected generateTriggerStatement(\n tableName: string,\n trigger: TriggerDefinition,\n ): string {\n // For simple triggers, we need to create a function first\n // This is PostgreSQL's two-step trigger process\n\n // Check if this is an updated_at trigger\n if (trigger.name.includes('updated_at')) {\n // Generate the function and trigger for updated_at. The function name is\n // a PostgreSQL identifier like any other, so it is subject to the same\n // 63-byte limit — and unlike an index it is *referenced* by the trigger\n // below, so a truncation that CREATE FUNCTION accepts would leave\n // EXECUTE FUNCTION pointing at a name PostgreSQL never stored (#2374).\n const functionName = shortenIdentifier(`update_${tableName}_updated_at`);\n\n let sql = `-- Function for ${trigger.name}\\n`;\n sql += `CREATE OR REPLACE FUNCTION ${functionName}()\\n`;\n sql += `RETURNS TRIGGER AS $$\\n`;\n sql += `BEGIN\\n`;\n sql += ` NEW.updated_at = CURRENT_TIMESTAMP;\\n`;\n sql += ` RETURN NEW;\\n`;\n sql += `END;\\n`;\n sql += `$$ LANGUAGE plpgsql;\\n\\n`;\n\n sql += `-- Trigger\\n`;\n sql += `DROP TRIGGER IF EXISTS \"${trigger.name}\" ON \"${tableName}\";\\n`;\n sql += `CREATE TRIGGER \"${trigger.name}\"\\n`;\n sql += `${trigger.when} ${trigger.event} ON \"${tableName}\"\\n`;\n sql += `FOR EACH ROW\\n`;\n sql += `EXECUTE FUNCTION ${functionName}();`;\n\n return sql;\n }\n\n // For custom triggers, use the provided body\n let sql = `DROP TRIGGER IF EXISTS \"${trigger.name}\" ON \"${tableName}\";\\n`;\n sql += `CREATE TRIGGER \"${trigger.name}\"\\n`;\n sql += `${trigger.when} ${trigger.event} ON \"${tableName}\"\\n`;\n sql += `FOR EACH ROW\\n`;\n\n if (trigger.condition) {\n sql += `WHEN (${trigger.condition})\\n`;\n }\n\n // PostgreSQL triggers need EXECUTE FUNCTION or EXECUTE PROCEDURE\n // If body contains a function call, use it directly\n if (trigger.body.includes('EXECUTE')) {\n sql += trigger.body;\n } else {\n // Wrap in anonymous DO block or assume it's a function name\n sql += `EXECUTE FUNCTION ${trigger.body}`;\n }\n\n return `${sql};`;\n }\n\n /**\n * PostgreSQL supports triggers\n */\n supportsTriggers(): boolean {\n return true;\n }\n\n /**\n * PostgreSQL doesn't require inline UNIQUE for UPSERT\n * Both inline and separate indexes work with ON CONFLICT\n */\n requiresInlineUnique(): boolean {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,IAAa,mBAAb,cAAsC,gBAAgB;CACpD,SAAkC;;;;;;CAOlC,QAAQ,MAA2B;EACjC,QAAQ,MAAR;GACE,KAAK,QACH,OAAO;GACT,KAAK,aAIH,OAAO;GACT,KAAK,QACH,OAAO;GACT,KAAK,QACH,OAAO;GACT,SACE,OAAO,MAAM,QAAQ,IAAI;EAC7B;CACF;;;;;;;CAQA,yBACE,WACA,SACQ;EAKR,IAAI,QAAQ,KAAK,SAAS,YAAY,GAAG;GAMvC,MAAM,eAAe,kBAAkB,UAAU,UAAU,YAAY;GAEvE,IAAI,MAAM,mBAAmB,QAAQ,KAAK;GAC1C,OAAO,8BAA8B,aAAa;GAClD,OAAO;GACP,OAAO;GACP,OAAO;GACP,OAAO;GACP,OAAO;GACP,OAAO;GAEP,OAAO;GACP,OAAO,2BAA2B,QAAQ,KAAK,QAAQ,UAAU;GACjE,OAAO,mBAAmB,QAAQ,KAAK;GACvC,OAAO,GAAG,QAAQ,KAAK,GAAG,QAAQ,MAAM,OAAO,UAAU;GACzD,OAAO;GACP,OAAO,oBAAoB,aAAa;GAExC,OAAO;EACT;EAGA,IAAI,MAAM,2BAA2B,QAAQ,KAAK,QAAQ,UAAU;EACpE,OAAO,mBAAmB,QAAQ,KAAK;EACvC,OAAO,GAAG,QAAQ,KAAK,GAAG,QAAQ,MAAM,OAAO,UAAU;EACzD,OAAO;EAEP,IAAI,QAAQ,WACV,OAAO,SAAS,QAAQ,UAAU;EAKpC,IAAI,QAAQ,KAAK,SAAS,SAAS,GACjC,OAAO,QAAQ;OAGf,OAAO,oBAAoB,QAAQ;EAGrC,OAAO,GAAG,IAAI;CAChB;;;;CAKA,mBAA4B;EAC1B,OAAO;CACT;;;;;CAMA,uBAAgC;EAC9B,OAAO;CACT;AACF"}
|