@marinoscar/platform-db 0.0.0-stage → 0.1.0-next.3

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.
Files changed (208) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -0
  3. package/README.md +382 -2
  4. package/bin/platform.js +28 -0
  5. package/dist/baseline/deps.d.ts +32 -0
  6. package/dist/baseline/deps.d.ts.map +1 -0
  7. package/dist/baseline/deps.js +64 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +34 -0
  10. package/dist/baseline/errors.d.ts.map +1 -0
  11. package/dist/baseline/errors.js +23 -0
  12. package/dist/baseline/errors.js.map +1 -0
  13. package/dist/baseline/fs.d.ts +9 -0
  14. package/dist/baseline/fs.d.ts.map +1 -0
  15. package/dist/baseline/fs.js +39 -0
  16. package/dist/baseline/fs.js.map +1 -0
  17. package/dist/baseline/index.d.ts +8 -0
  18. package/dist/baseline/index.d.ts.map +1 -0
  19. package/dist/baseline/index.js +24 -0
  20. package/dist/baseline/index.js.map +1 -0
  21. package/dist/baseline/mapping.d.ts +43 -0
  22. package/dist/baseline/mapping.d.ts.map +1 -0
  23. package/dist/baseline/mapping.js +80 -0
  24. package/dist/baseline/mapping.js.map +1 -0
  25. package/dist/baseline/normalise.d.ts +42 -0
  26. package/dist/baseline/normalise.d.ts.map +1 -0
  27. package/dist/baseline/normalise.js +133 -0
  28. package/dist/baseline/normalise.js.map +1 -0
  29. package/dist/baseline/plan.d.ts +66 -0
  30. package/dist/baseline/plan.d.ts.map +1 -0
  31. package/dist/baseline/plan.js +105 -0
  32. package/dist/baseline/plan.js.map +1 -0
  33. package/dist/baseline/report.d.ts +125 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +85 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +106 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +339 -0
  40. package/dist/baseline/run.js.map +1 -0
  41. package/dist/bin/db-commands.d.ts +31 -0
  42. package/dist/bin/db-commands.d.ts.map +1 -0
  43. package/dist/bin/db-commands.js +276 -0
  44. package/dist/bin/db-commands.js.map +1 -0
  45. package/dist/bin/fs-io.d.ts +7 -0
  46. package/dist/bin/fs-io.d.ts.map +1 -0
  47. package/dist/bin/fs-io.js +45 -0
  48. package/dist/bin/fs-io.js.map +1 -0
  49. package/dist/bin/platform.d.ts +21 -0
  50. package/dist/bin/platform.d.ts.map +1 -0
  51. package/dist/bin/platform.js +99 -0
  52. package/dist/bin/platform.js.map +1 -0
  53. package/dist/compose/api.d.ts +84 -0
  54. package/dist/compose/api.d.ts.map +1 -0
  55. package/dist/compose/api.js +101 -0
  56. package/dist/compose/api.js.map +1 -0
  57. package/dist/compose/compose.d.ts +51 -0
  58. package/dist/compose/compose.d.ts.map +1 -0
  59. package/dist/compose/compose.js +177 -0
  60. package/dist/compose/compose.js.map +1 -0
  61. package/dist/compose/diff.d.ts +7 -0
  62. package/dist/compose/diff.d.ts.map +1 -0
  63. package/dist/compose/diff.js +68 -0
  64. package/dist/compose/diff.js.map +1 -0
  65. package/dist/compose/errors.d.ts +31 -0
  66. package/dist/compose/errors.d.ts.map +1 -0
  67. package/dist/compose/errors.js +35 -0
  68. package/dist/compose/errors.js.map +1 -0
  69. package/dist/compose/index.d.ts +3 -0
  70. package/dist/compose/index.d.ts.map +1 -0
  71. package/dist/compose/index.js +11 -0
  72. package/dist/compose/index.js.map +1 -0
  73. package/dist/compose/parse.d.ts +65 -0
  74. package/dist/compose/parse.d.ts.map +1 -0
  75. package/dist/compose/parse.js +122 -0
  76. package/dist/compose/parse.js.map +1 -0
  77. package/dist/drift/db-conformance.d.ts +49 -0
  78. package/dist/drift/db-conformance.d.ts.map +1 -0
  79. package/dist/drift/db-conformance.js +65 -0
  80. package/dist/drift/db-conformance.js.map +1 -0
  81. package/dist/drift/index.d.ts +5 -0
  82. package/dist/drift/index.d.ts.map +1 -0
  83. package/dist/drift/index.js +26 -0
  84. package/dist/drift/index.js.map +1 -0
  85. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  86. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  87. package/dist/drift/raw-sql-indexes.js +113 -0
  88. package/dist/drift/raw-sql-indexes.js.map +1 -0
  89. package/dist/drift/raw-sql-tripwire.d.ts +150 -0
  90. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-tripwire.js +394 -0
  92. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  93. package/dist/drift/run.d.ts +128 -0
  94. package/dist/drift/run.d.ts.map +1 -0
  95. package/dist/drift/run.js +201 -0
  96. package/dist/drift/run.js.map +1 -0
  97. package/dist/index.d.ts +16 -0
  98. package/dist/index.d.ts.map +1 -0
  99. package/dist/index.js +33 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/lock/hash.d.ts +13 -0
  102. package/dist/lock/hash.d.ts.map +1 -0
  103. package/dist/lock/hash.js +19 -0
  104. package/dist/lock/hash.js.map +1 -0
  105. package/dist/lock/index.d.ts +5 -0
  106. package/dist/lock/index.d.ts.map +1 -0
  107. package/dist/lock/index.js +20 -0
  108. package/dist/lock/index.js.map +1 -0
  109. package/dist/lock/lock.d.ts +117 -0
  110. package/dist/lock/lock.d.ts.map +1 -0
  111. package/dist/lock/lock.js +140 -0
  112. package/dist/lock/lock.js.map +1 -0
  113. package/dist/lock/manifest.d.ts +60 -0
  114. package/dist/lock/manifest.d.ts.map +1 -0
  115. package/dist/lock/manifest.js +95 -0
  116. package/dist/lock/manifest.js.map +1 -0
  117. package/dist/lock/semver.d.ts +10 -0
  118. package/dist/lock/semver.d.ts.map +1 -0
  119. package/dist/lock/semver.js +13 -0
  120. package/dist/lock/semver.js.map +1 -0
  121. package/dist/seed/index.d.ts +4 -0
  122. package/dist/seed/index.d.ts.map +1 -0
  123. package/dist/seed/index.js +10 -0
  124. package/dist/seed/index.js.map +1 -0
  125. package/dist/seed/input.d.ts +52 -0
  126. package/dist/seed/input.d.ts.map +1 -0
  127. package/dist/seed/input.js +77 -0
  128. package/dist/seed/input.js.map +1 -0
  129. package/dist/seed/seed-platform.d.ts +28 -0
  130. package/dist/seed/seed-platform.d.ts.map +1 -0
  131. package/dist/seed/seed-platform.js +133 -0
  132. package/dist/seed/seed-platform.js.map +1 -0
  133. package/dist/seed/types.d.ts +277 -0
  134. package/dist/seed/types.d.ts.map +1 -0
  135. package/dist/seed/types.js +5 -0
  136. package/dist/seed/types.js.map +1 -0
  137. package/dist/sync/apply.d.ts +29 -0
  138. package/dist/sync/apply.d.ts.map +1 -0
  139. package/dist/sync/apply.js +37 -0
  140. package/dist/sync/apply.js.map +1 -0
  141. package/dist/sync/check.d.ts +56 -0
  142. package/dist/sync/check.d.ts.map +1 -0
  143. package/dist/sync/check.js +108 -0
  144. package/dist/sync/check.js.map +1 -0
  145. package/dist/sync/errors.d.ts +31 -0
  146. package/dist/sync/errors.d.ts.map +1 -0
  147. package/dist/sync/errors.js +23 -0
  148. package/dist/sync/errors.js.map +1 -0
  149. package/dist/sync/index.d.ts +9 -0
  150. package/dist/sync/index.d.ts.map +1 -0
  151. package/dist/sync/index.js +25 -0
  152. package/dist/sync/index.js.map +1 -0
  153. package/dist/sync/ledger.d.ts +65 -0
  154. package/dist/sync/ledger.d.ts.map +1 -0
  155. package/dist/sync/ledger.js +49 -0
  156. package/dist/sync/ledger.js.map +1 -0
  157. package/dist/sync/plan.d.ts +61 -0
  158. package/dist/sync/plan.d.ts.map +1 -0
  159. package/dist/sync/plan.js +79 -0
  160. package/dist/sync/plan.js.map +1 -0
  161. package/dist/sync/promote.d.ts +58 -0
  162. package/dist/sync/promote.d.ts.map +1 -0
  163. package/dist/sync/promote.js +93 -0
  164. package/dist/sync/promote.js.map +1 -0
  165. package/dist/sync/timestamps.d.ts +41 -0
  166. package/dist/sync/timestamps.d.ts.map +1 -0
  167. package/dist/sync/timestamps.js +68 -0
  168. package/dist/sync/timestamps.js.map +1 -0
  169. package/dist/sync/version.d.ts +28 -0
  170. package/dist/sync/version.d.ts.map +1 -0
  171. package/dist/sync/version.js +66 -0
  172. package/dist/sync/version.js.map +1 -0
  173. package/migrations/0001_initial/migration.sql +297 -0
  174. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  175. package/migrations/0003_add_credentials/migration.sql +20 -0
  176. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  177. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  178. package/migrations/0006_add_notifications/migration.sql +22 -0
  179. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  180. package/migrations/0008_add_jobs/migration.sql +110 -0
  181. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  182. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  183. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  184. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  185. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  186. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  187. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  188. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  189. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  190. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  191. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  192. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  193. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  194. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  195. package/migrations/0023_add_organizations/migration.sql +142 -0
  196. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  197. package/migrations/manifest.json +240 -0
  198. package/package.json +75 -4
  199. package/raw-sql-indexes.json +49 -0
  200. package/schema/ai.prisma +387 -0
  201. package/schema/base.prisma +11 -0
  202. package/schema/credentials.prisma +108 -0
  203. package/schema/db-backup.prisma +376 -0
  204. package/schema/identity.prisma +407 -0
  205. package/schema/jobs.prisma +731 -0
  206. package/schema/notifications.prisma +610 -0
  207. package/schema/settings.prisma +35 -0
  208. package/schema/storage.prisma +57 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,40 @@
1
+ # @marinoscar/platform-db
2
+
3
+ ## 0.1.0-next.3
4
+
5
+ ## 0.1.0-next.2
6
+
7
+ ### Minor Changes
8
+
9
+ - c91cf7b: Add the `@marinoscar/platform-db/seed` slice: `seedPlatform(prisma, input)` upserts the platform's roles, permissions, default grants, the `global` system settings row and the initial administrator's allowlist entry (never deleting, never overwriting an admin-edited value), with `platformSeedInputFrom` and `readSeedSnapshot` to build the input from the registries' committed catalogs.
10
+ - 9734a55: `platform db baseline`: adopt the package migration history in a database that already has its schema, without re-running a migration. Dry run by default; `--apply` maps the app's directories to the platform migrations (exact hash, comment-stripped hash, or a `--map` file), refuses on a failed `_prisma_migrations` row, a live schema difference no declared deviation explains, or a missing raw-SQL index, then writes `platform.lock` and marks the migrations that have no directory applied with `prisma migrate resolve --applied`. `--through` adopts a database that is behind. Adds `runBaseline`, `proposeMapping`, `planBaseline`, `renderReport` and `createBaselineDeps`.
11
+
12
+ ### Patch Changes
13
+
14
+ - 2235f8a: `platform.lock` and `manifest.json` accept semantic versions with a prerelease or build suffix (`0.1.0-next.1`), so `platform db sync` at a prerelease package version writes a lock `parseLock` reads back. `compareVersions` orders versions by semver precedence (a prerelease is below its release, numeric identifiers compare numerically), and `nextPlatformVersion` gives a prerelease package the release it leads to. Adds `SEMVER_PATTERN`.
15
+
16
+ ## 0.1.0-next.1
17
+
18
+ ### Minor Changes
19
+
20
+ - 31c6b2a: Platform history v1: the base's 22 migrations ship in `migrations/` (`0001_initial` to `0022_add_retention_created_at_indexes`, byte-identical to the app copies) with a filled `manifest.json` (an entry may list the other slices it `touches`), and the raw-SQL index list becomes the exported `RAW_SQL_INDEXES` with a tripwire (`assertRawSqlIndexes`) that fails on an unlisted partial or expression index.
21
+
22
+ ### Patch Changes
23
+
24
+ - 521f3d2: Schema comments name `@marinoscar/platform-api/core` as the home of the secret cipher (comments only; no model change).
25
+
26
+ ## 0.1.0-next.0
27
+
28
+ ### Minor Changes
29
+
30
+ - ebaabe2: Ship the base Prisma schema as slice fragments with `// @extensible` models and `extend model`, plus the `platform db compose [--check]` composer that generates an app's `prisma/schema/` folder.
31
+ - a66fef1: First pre-release of the platform packages: the six-package scaffold (build formats, boundary lint, pack check, TSDoc and generated API reference, single-instance peer dependencies) plus the first slices.
32
+
33
+ - `@marinoscar/platform-api/core`: the typed registry primitive (`defineRegistry`, `Registry`, `RegistryError`, `RegistryFreezeService`, `withTemporaryEntries`).
34
+ - `@marinoscar/platform-api/testing`: the conformance harness (`runPlatformConformance`, `conformanceSuites`) with the `cron-enqueue-only` suite.
35
+ - `@marinoscar/platform-cli/core`: the CLI command and env-spec fragment registries.
36
+ - `@marinoscar/platform-cli/telemetry`: the node span relay and the telemetry env-spec fragment.
37
+ - `@marinoscar/platform-infra`: `infraFile()`, the `platform-infra` command (`sync` materialises fragments into an app) and the `telemetry` slice (collector and GreptimeDB compose fragments, collector config and overlay, typed manifest).
38
+ - `@marinoscar/platform-contract`, `@marinoscar/platform-web` and `@marinoscar/platform-db` ship their package scaffold only; their slices follow in later releases.
39
+
40
+ - a630d75: Migration tooling: the `platform` bin gains `platform db sync` (byte-copy package migrations into the app's `prisma/migrations` under app-local timestamps and record them in `prisma/platform.lock`), `platform db check` (offline lock verification; `--database` also compares `_prisma_migrations` checksums), `platform db promote` (turn an app-generated migration into a package migration) and `platform db drift` (migration history vs schema through a shadow database, plus the raw-SQL index assertion). Adds the `PlatformLock` and manifest models, `planSync`, `applySync`, `checkLock`, `checkLedger`, `promote` and `raw-sql-indexes.json`.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 marinoscar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,383 @@
1
- # Temporary Holding Version
1
+ # @marinoscar/platform-db
2
+
3
+ The data layer of the platform: Prisma schema fragments (`schema/`), SQL migrations (`migrations/`) and seed functions that an app composes into its own schema and migration history. CommonJS, like the API that consumes it.
4
+
5
+ ## Purpose and scope
6
+
7
+ Schema fragments, migrations and seeds of the platform's data slices, and the **composer** that turns the fragments into the Prisma schema an app generates its client from.
8
+
9
+ What ships today: the schema fragments (`schema/`, 34 models and 12 enums in eight slices), `platform db compose`, and the migration tooling (`platform db sync|check|promote|drift`, the `platform.lock` and `manifest.json` formats, the raw-SQL index list). The package also ships platform history v1: the base's 22 migrations as `migrations/0001_initial` to `0022_add_retention_created_at_indexes`, with a filled manifest, the raw-SQL index list `RAW_SQL_INDEXES` and its tripwire, and the offline `runDbConformance()` suite. The platform seed is shipped too: `seedPlatform` (the [`seed` slice](src/seed/README.md), `@marinoscar/platform-db/seed`). The package does not run migrations against a database itself; the app's `prisma:*` scripts do.
10
+
11
+ Status: pre-release (version `0.0.0`). The `extend model` seam is `experimental` until the extension contract is frozen.
12
+
13
+ ## Install and peer dependencies
14
+
15
+ ```bash
16
+ npm install @marinoscar/platform-db
17
+ ```
18
+
19
+ Install these in the app; the package never bundles its own copy (a second copy breaks dependency injection, hooks or theme context).
20
+
21
+ | Package | Range |
22
+ |---|---|
23
+ | `@prisma/client` | `^7.8.0` |
24
+ | `prisma` | `^7.8.0` |
25
+
26
+ ## Quick start
27
+
28
+ In an app that already depends on the package (the reference app is `apps/api`):
29
+
30
+ ```bash
31
+ # once, and after pulling platform changes: the `platform` command runs the built package
32
+ npm run build:packages
33
+
34
+ cd apps/api
35
+ npm run db:compose # platform fragments + prisma/fragments/ -> prisma/schema/ (committed)
36
+ npm run prisma:generate
37
+ npm run db:compose:check # CI: exits 1 when prisma/schema/ differs from a fresh compose
38
+ ```
39
+
40
+ `apps/api/package.json` wires the two scripts as `"db:compose": "platform db compose"` and `"db:compose:check": "platform db compose --check"`, and `apps/api/prisma.config.ts` points Prisma at the folder:
41
+
42
+ ```ts
43
+ export default defineConfig({
44
+ schema: 'prisma/schema', // the generated FOLDER
45
+ datasource: { url: process.env.DATABASE_URL as string },
46
+ migrations: { path: 'prisma/migrations' }, // must be explicit with a schema folder
47
+ });
48
+ ```
49
+
50
+ To add an app model that points at a platform model, see the example in [Extension-point catalog](#extension-point-catalog).
51
+
52
+ **Migrations.** Wire the commands into the app's `package.json` and run them from the directory that holds `prisma/`:
53
+
54
+ ```json
55
+ {
56
+ "scripts": {
57
+ "db:sync": "platform db sync",
58
+ "db:check": "platform db check",
59
+ "db:drift": "node scripts/platform-env.js db drift",
60
+ "db:baseline": "node scripts/platform-env.js db baseline"
61
+ }
62
+ }
63
+ ```
64
+
65
+ ```bash
66
+ npm run db:sync # install package migrations the lock does not hold yet
67
+ npm run prisma:migrate # apply them, explicitly (the API never migrates on startup)
68
+ npm run db:check # prove the installed SQL is still byte-identical to the package's
69
+ ```
70
+
71
+ `db:drift`, `db:baseline` (and `platform db check --database`) read `DATABASE_URL`; the reference app's `apps/api/scripts/platform-env.js` builds it from `POSTGRES_*` the way `prisma-env.js` does.
72
+
73
+ ## Configuration
74
+
75
+ `platform db compose [--check]` reads `--platform-schema` (default: the `schema/` folder shipped in this package) and the app's `--fragments` folder, and writes `--out`. Paths are relative to `--root` (default: the current directory).
76
+
77
+ | Option | Type | Default | Meaning |
78
+ |---|---|---|---|
79
+ | `--check` | flag | off | Write nothing; exit 1 and print a diff when the generated folder differs from a fresh compose |
80
+ | `--root <dir>` | path | current directory | The app's directory |
81
+ | `--fragments <dir>` | path | `prisma/fragments` | The app's own fragments (a missing folder means none) |
82
+ | `--out <dir>` | path | `prisma/schema` | The generated folder Prisma reads |
83
+ | `--platform-schema <dir>` | path | the package's `schema/` | Override the platform fragments (tests, unusual layouts) |
84
+
85
+ Exit codes: 0 success, 1 `--check` found a stale folder, 2 a rejected fragment or a usage error.
86
+
87
+ The programmatic API takes the same three folders as `ComposeOptions` (`platformSchemaDir`, `appFragmentsDir`, `outDir`): `composeSchema()` reads and returns the files (no write), `writeComposedSchema()` also writes and removes stale `*.prisma` files, `checkComposedSchema()` compares.
88
+
89
+ **Migration commands.** The package is tooling and data, with no `forRoot()` or module option. The commands take flags:
90
+
91
+ | Command | Flags |
92
+ |---|---|
93
+ | `platform db sync` | `--check` (same as `check`), `--dry-run`, `--timestamp <iso>` (the clock for the new directory names), `--root <dir>`, `--package-dir <dir>` |
94
+ | `platform db check` | `--database` (also compare `_prisma_migrations`; needs `DATABASE_URL`), `--root`, `--package-dir` |
95
+ | `platform db promote <localDir>` | `--id <slug>` (required), `--since <version>`, `--slice <slice>`, `--requires <slices>`, `--root`, `--package-dir` |
96
+ | `platform db drift` | `--schema <path>` (default `prisma/schema`, else `prisma/schema.prisma`), `--shadow-database-url <url>`, `--root` |
97
+
98
+ `--root` is the directory holding `prisma/` (default: the current directory). `--package-dir` is the package that holds `migrations/` (default: the installed one). Exit codes: `0` success, `1` a failed check or a refusal, `2` a usage error or a missing `DATABASE_URL`.
99
+
100
+ `SHADOW_DATABASE_URL`, when set, names the empty database `db drift` replays the history into; otherwise it creates and drops `<database>_drift_shadow_<pid>`, which needs a role that may create databases. The app's `prisma.config.ts` must pass it through as `datasource.shadowDatabaseUrl` (Prisma refuses `migrate diff --from-migrations` without one).
101
+
102
+ ## Extension-point catalog
103
+
104
+ The one seam of the data layer is the `extend model` block, written in the app's fragment folder (`ComposeOptions.appFragmentsDir`). The row below names the option that locates it.
105
+
106
+ | Name | Kind | Signature | When to use | Stability | Example |
107
+ |---|---|---|---|---|---|
108
+ | `ComposeOptions.appFragmentsDir` | option | `extend model <Model> { <back-relation field> }` in a `*.prisma` file of the folder | An app model points at a platform model (`User`, `Job`, `StorageObject`) and Prisma needs the back-relation field on the platform side | experimental | [example](../../apps/api/prisma/fragments/README.md) |
109
+
110
+ Stability stays `experimental` until the extension contract is frozen (issue #727).
111
+
112
+ **`extend model`**
113
+
114
+ ```prisma
115
+ // apps/<app>/prisma/fragments/workouts.prisma
116
+ model Workout {
117
+ id String @id @default(uuid()) @db.Uuid
118
+ userId String @map("user_id") @db.Uuid
119
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
120
+
121
+ @@map("workouts")
122
+ }
123
+
124
+ extend model User {
125
+ workouts Workout[]
126
+ }
127
+ ```
128
+
129
+ Run `npm run db:compose`, then `include: { workouts: true }` type-checks on the generated client. The compiled fixture is [`test/fixtures/app-with-domain/`](test/fixtures/app-with-domain/fragments/workouts.prisma): it extends `User`, `StorageObject` and `Job`, and `test/compose/app-with-domain.spec.ts` runs `prisma validate`, `prisma generate` and `tsc` against it.
130
+
131
+ Rules:
132
+
133
+ - Only a model its owner marked `// @extensible` can be extended: `User`, `Job` and `StorageObject` today. Everything else is closed; opening one more is a minor-version change reached through a seam request, never an app edit.
134
+ - An `extend` block holds back-relation fields only: no scalar field (it would add a column), no relation with `fields: [...]` (it would add a foreign key column), no `@@` attribute.
135
+ - The slice or app that owns the foreign key writes the back-relation; the composer merges what is written and generates nothing.
136
+ - Fragments are `prisma format` shaped: a block header is `<kind> <Name> {` on one line at column 0, and the block ends with `}` alone at column 0.
137
+ - An app fragment named `base.prisma` replaces the package's `base.prisma` (the generator and datasource), which is how an app sets the generator `output` or `previewFeatures`. The composer warns when it does.
138
+
139
+ The migration tooling adds no row to the catalog. How an app extends the migration history, which is a convention rather than a code seam:
140
+
141
+ - **The app's own migrations live after the installed ones.** `platform db sync` names every installed directory after the newest directory already in `prisma/migrations`, so an app-authored migration and an installed one never reorder. The app keeps authoring with `prisma migrate dev`; those directories are not in `platform.lock`.
142
+ - **App-owned raw-SQL indexes** go in `platform.lock` under `rawSqlIndexes` (`name` and `pg_indexes.indexdef`); `platform db drift` asserts them next to the package's own.
143
+ - **A comment-only difference** between an installed file and its package origin is recorded in the lock entry as `localSha256` plus `note`; any further edit is still caught.
144
+ - **`platform db promote` is platform-internal.** It is how a maintainer turns a migration generated in the base app into a package migration; an app that only consumes the package never runs it.
145
+
146
+ ## Data
147
+
148
+ **Fragments** (`schema/`, hand-edited by the platform; one file per slice, enums travel with their model):
149
+
150
+ | Fragment | Models |
151
+ |---|---|
152
+ | `base.prisma` | `generator client`, `datasource db` |
153
+ | `identity.prisma` | `User` (`@extensible`), `UserIdentity`, `Role`, `Permission`, `RolePermission`, `UserRole`, `RefreshToken`, `PersonalAccessToken`, `DeviceCode`, `AllowedEmail`, `AuditEvent`, `Organization`, `Membership`, `Invite` |
154
+ | `settings.prisma` | `SystemSettings`, `UserSettings` |
155
+ | `storage.prisma` | `StorageObject` (`@extensible`), `StorageObjectChunk` |
156
+ | `credentials.prisma` | `Credential`, `UserCredential` |
157
+ | `notifications.prisma` | `Notification`, `NotificationDelivery`, `PushSubscription`, `NotificationBroadcast` |
158
+ | `jobs.prisma` | `Job` (`@extensible`), `JobStatsRollup`, `WorkerNode`, `NodeCredential`, `JobNodeSecret` |
159
+ | `db-backup.prisma` | `DatabaseBackupRun` |
160
+ | `ai.prisma` | `AiModel`, `UserAiKey`, `AiRun`, `AiUsageEvent` |
161
+
162
+ A slice declares the back-relations that point **into** another slice as `extend model` blocks in its own fragment (the 17 `User` fields that leave identity, and `Job.backupRun` in `db-backup.prisma`). Every block comment of the original schema is kept verbatim: they are the design documentation.
163
+
164
+ **Composition.** Package fragments load first, app fragments second, each alphabetically. `extend` blocks are appended to the target model before its first `@@` line under a `// composed from <origin>:<file>` comment. The output is `platform.<slice>.prisma` per package fragment and `app.<fragment>.prisma` per app fragment (a fragment of only `extend` blocks produces no file), each starting with `// GENERATED by platform db compose — do not edit` and `// source: <origin>:<file>`. The folder is committed and `--check` guards it.
165
+
166
+ **Schema-neutral.** Composing the shipped fragments reproduces the previous single `schema.prisma` exactly in content: `prisma migrate diff` from the old file to the generated folder, and from a database migrated by the 22 existing migrations to the folder, both report no difference.
167
+
168
+ **Raw-SQL indexes.** `jobs_active_dedup_uniq_idx`, `database_backup_runs_active_uniq_idx` and the other raw-SQL indexes live only in migration SQL, because Prisma cannot express a partial unique index. Never add an `@@unique` for them in a fragment; the comments in `jobs.prisma` and `db-backup.prisma` say why. [Raw-SQL indexes](#raw-sql-indexes) lists them, and a tripwire fails the build when a fragment redeclares one.
169
+
170
+ **Organizations.** The identity fragment owns `Organization`, `Membership` and `Invite` (tables `organizations`, `memberships`, `org_invites`) and the nullable `org_id` on `refresh_tokens`, `personal_access_tokens` and `device_codes` (migration `0023_add_organizations`). The migration backfills the default organization (slug `default`), one active membership per existing user and the default `org_id` on every existing credential row. The columns stay nullable (the expand step). Exactly one organization is the default, enforced by the raw-SQL index `organizations_default_uniq_idx`. These are identity tables read across organizations at login: no RLS on them.
171
+
172
+ **System and org roles.** Migration `0024_split_system_org_roles` (#723) adds the `RoleScope` enum (`system`, `org`), `roles.scope` and `permissions.scope` (default `system`), the required `memberships.role_id` (the member's org role, `onDelete: Restrict`) and the nullable `org_invites.role_id` (NULL means the default org role). Its data step creates `org_admin`, scopes `contributor`, `viewer` and the org permissions to `org`, moves `admin`'s org-permission grants to `org_admin`, sets each membership's role from the user's global roles (`admin` to `org_admin`, otherwise `contributor` over `viewer`, otherwise `viewer`) and deletes the `user_roles` rows of org roles; `user_roles` keeps its shape. `seedPlatform` writes the scope of every role and permission entry that carries one.
173
+
174
+ **Seeds** (`@marinoscar/platform-db/seed`, stability `experimental`; details in the [slice README](src/seed/README.md)). `seedPlatform(prisma, input, log?)` upserts the platform's roles, permissions, default role grants, the `global` `system_settings` row and the initial administrator's `allowed_emails` row, then creates the default organization when none is flagged default, in that order, and returns a summary. Idempotent: every write is an upsert on a natural unique, so a second run changes nothing, which is what `appctl deploy update` and the CI `smoke` job rely on. **Never deletes and never overwrites an admin-edited value:** a permission removed from the registry stays as a row until a migration removes it (expand/contract), and the settings row and the allowlist row are created with `update: {}`. `prisma` is the structural type `SeedPrisma` (the delegates `role`, `permission`, `rolePermission`, `systemSettings`, `allowedEmail`, `organization`), so the package never imports or bundles a generated client.
175
+
176
+ **Building the input** (`experimental`). `platformSeedInputFrom(snapshot, env)` builds the `PlatformSeedInput` from the registries' plain-data snapshots, and `readSeedSnapshot(catalogDir)` loads them from the two committed catalogs of an app's `prisma/catalog/` (`permissions.json`, `system-settings-defaults.json`). Seeds read generated catalogs, never `src/`: the production image carries `prisma/` but not `src/`. An app adds a permission or a setting by registering it and regenerating the catalogs, never by editing a platform file.
177
+
178
+ **The app's own seed** (the app's code, not the package's). The reference app's `prisma/seed.ts` runs `seedPlatform` and then `seedApp(prisma)` from [`prisma/seed-app.ts`](../../apps/api/prisma/seed-app.ts), the documented place for an app's own seed rows. Both are idempotent, and `seed.ts` stays Nest-free and runnable with `ts-node --transpile-only`.
179
+
180
+ **Public vs private.** An app may point at any model and add back-relations to the three `@extensible` ones. It never edits a platform fragment or a column of a platform table.
181
+
182
+ **Migrations.** `migrations/manifest.json` holds platform history v1 (below), and the reference app's `prisma/platform.lock` maps each entry to the directory the app already has. The install model ([ADR 0002](../../docs/adr/0002-database-packaging-and-rls.md) D3):
183
+
184
+ - **Package history.** `migrations/NNNN_slug/migration.sql`, one linear, immutable history. `migrations/manifest.json` lists it: `[{ "id": "0001_initial", "dir": "0001_initial", "sha256": "…", "since": "1.0.0", "slice": "identity", "touches": ["settings", "storage"], "requires": [] }]`. `slice` is the first owner of the tables the migration creates or changes; `touches` (optional) lists the other slices whose tables it also changes. The origin id of an entry is `platform:` plus its `id`. The whole history is installed in order; slice opt-out is not supported in v1, and `requires` is checked as an ordering sanity check.
185
+ - **Install.** `platform db sync` byte-copies each migration missing from the lock into `prisma/migrations/<YYYYMMDDHHMMSS>_<slug>/migration.sql` and appends a lock entry. The timestamp of the i-th migration of a run is `max(now, newest local timestamp + 1 second) + i seconds` (UTC), so it sorts after everything already there. A second run installs nothing. It never rewrites or renames an existing directory.
186
+ - **`prisma/platform.lock`.** JSON, committed, keys sorted:
187
+ ```json
188
+ {
189
+ "lockVersion": 1,
190
+ "migrations": [
191
+ { "localDir": "20260124223146_initial", "originId": "platform:0001_initial", "sha256": "…", "since": "1.0.0" }
192
+ ],
193
+ "platformVersion": "1.0.0"
194
+ }
195
+ ```
196
+ `sha256` is the SHA-256 of the package file's raw bytes. It is also what Prisma stores in `_prisma_migrations.checksum` for a byte copy, which `apps/api/test/prisma/platform-sync.db.spec.ts` proves on a real database. Optional keys: `localSha256` and `note` (a comment-only divergence), `deviations`, `rawSqlIndexes`. A reader refuses a `lockVersion` newer than it knows. `platformVersion` and `since` are semantic versions, a prerelease included (`0.1.0-next.1`, which `platform db sync` writes when the installed package is a prerelease); versions are ordered by semver precedence, so `0.1.0-next.9` < `0.1.0-next.10` < `0.1.0`. Prisma's own `migration_lock.toml` is separate and untouched.
197
+ - **Raw bytes.** Hashes are over the bytes, never normalised: a changed comment, trailing newline or line ending is a different migration. The repository marks `**/migration.sql` as `-text` in `.gitattributes`.
198
+ - **`raw-sql-indexes.json`.** The partial and expression indexes that exist only in migration SQL, listed under [Raw-SQL indexes](#raw-sql-indexes) and exported as `RAW_SQL_INDEXES`.
199
+ - **Concurrent index builds.** A big-table index change is `CREATE INDEX CONCURRENTLY IF NOT EXISTS` as the only statement of its own migration. Prisma runs a migration inside a transaction unless it contains only statements that cannot, and `CONCURRENTLY` cannot run in one.
200
+
201
+ ### Platform history v1
202
+
203
+ The base's migrations, relocated byte for byte. The package ids are the platform's own numbering; the reference app keeps its original directory names (a rename would make `prisma migrate deploy` report every migration unknown and missing on an existing database), and its `platform.lock` maps each id to its directory with `since` `1.0.0`. `platform db check` proves the two copies are identical.
204
+
205
+ | Id | Reference app directory | Slice |
206
+ |---|---|---|
207
+ | `0001_initial` | `20260124223146_initial` | identity (touches settings, storage) |
208
+ | `0002_add_personal_access_tokens` | `20260329151231_add_personal_access_tokens` | identity |
209
+ | `0003_add_credentials` | `20260830211041_add_credentials` | credentials |
210
+ | `0004_add_notification_deliveries` | `20260831010356_add_notification_deliveries` | notifications |
211
+ | `0005_drop_stale_uuid_defaults` | `20260831014110_drop_stale_uuid_defaults` | identity (touches settings, storage) |
212
+ | `0006_add_notifications` | `20260831030721_add_notifications` | notifications |
213
+ | `0007_add_push_subscriptions` | `20260905182958_add_push_subscriptions` | notifications |
214
+ | `0008_add_jobs` | `20260906120000_add_jobs` | jobs |
215
+ | `0009_add_worker_nodes` | `20260906190000_add_worker_nodes` | jobs |
216
+ | `0010_add_database_backup_runs` | `20260907120000_add_database_backup_runs` | db-backup |
217
+ | `0011_add_notification_broadcasts` | `20260907130000_add_notification_broadcasts` | notifications |
218
+ | `0012_add_backup_run_job_link` | `20260907140000_add_backup_run_job_link` | db-backup (touches jobs) |
219
+ | `0013_add_job_node_secrets` | `20260907150000_add_job_node_secrets` | jobs |
220
+ | `0014_add_backup_run_pg_dump_version` | `20260907160000_add_backup_run_pg_dump_version` | db-backup |
221
+ | `0015_add_job_claim_token` | `20260908120000_add_job_claim_token` | jobs |
222
+ | `0016_add_ai_platform` | `20260926034919_add_ai_platform` | ai |
223
+ | `0017_revoke_viewer_ai_use` | `20260927000000_revoke_viewer_ai_use` | ai (touches identity) |
224
+ | `0018_add_user_credentials` | `20260927120000_add_user_credentials` | credentials |
225
+ | `0019_add_device_session_credential_link` | `20260927130000_add_device_session_credential_link` | identity |
226
+ | `0020_add_worker_node_vitals` | `20260928100000_add_worker_node_vitals` | jobs |
227
+ | `0021_add_job_trace_context` | `20260930120000_add_job_trace_context` | jobs |
228
+ | `0022_add_retention_created_at_indexes` | `20261006120000_add_retention_created_at_indexes` | notifications (touches ai) |
229
+
230
+ The history is frozen. A change to a package-owned table is a new migration appended with `platform db promote`, never an edit. Comments inside a `migration.sql` are part of its checksum, so a clean-up that strips comments must exclude `**/migration.sql`.
231
+
232
+ ### Raw-SQL indexes
233
+
234
+ Prisma's schema language cannot express a partial index or an expression index, and `prisma migrate diff` ignores them in both directions, so they exist only in migration SQL. That is intentional schema drift: never "fix" it with `@@unique` or `@@index`, and never replace the index with a `findFirst` before the insert.
235
+
236
+ | Index | Table | Unique | Created in | Why | Design |
237
+ |---|---|---|---|---|---|
238
+ | `jobs_active_dedup_uniq_idx` | `jobs` | yes | `0008_add_jobs` | at most one pending or running job per `dedup_key` | [job-queue](../../docs/specs/job-queue.md) |
239
+ | `jobs_attempts_gt1_idx` | `jobs` | no | `0008_add_jobs` | retried jobs, for the queue insights report | [job-queue](../../docs/specs/job-queue.md) |
240
+ | `jobs_succeeded_duration_idx` | `jobs` | no | `0008_add_jobs` | finished succeeded jobs, for the duration percentiles | [job-queue](../../docs/specs/job-queue.md) |
241
+ | `database_backup_runs_active_uniq_idx` | `database_backup_runs` | yes | `0010_add_database_backup_runs`, re-created in `0012_add_backup_run_job_link` | at most one pending or running backup (a constant-expression key) | [database-backup](../../docs/specs/database-backup.md) |
242
+ | `organizations_default_uniq_idx` | `organizations` | yes | `0023_add_organizations` | exactly one default organization (a constant-expression key over `is_default`) | [platform-packages](../../docs/specs/platform-packages.md#tenancy-and-access-model) |
243
+
244
+ `raw-sql-indexes.json` is the one list (`name`, `table`, `unique`, `definition`, `reason`, `doc`, `createdIn`), exported as `RAW_SQL_INDEXES`. `platform db drift` asserts each against `pg_indexes` by name and definition, and `assertRawSqlIndexes` is the tripwire that travels with the package. It scans every manifest migration (ignoring comments, following `DROP INDEX` and `ALTER INDEX ... RENAME`) for a `CREATE [UNIQUE] INDEX` with a `WHERE` clause or an expression key, and fails when
245
+
246
+ - a migration creates one that is not in `RAW_SQL_INDEXES`,
247
+ - a listed one is not created, or its table, uniqueness or `createdIn` disagrees,
248
+ - a schema fragment declares `@@unique`, `@@index` or `@unique` under a listed index's name or on its table and key columns.
249
+
250
+ An app's own raw-SQL indexes go in its `platform.lock` under `rawSqlIndexes`; the drift test asserts them too.
251
+
252
+ The exported functions (`planSync`, `applySync`, `checkLock`, `checkLedger`, `promote`, `readLock`, `readManifest`, `serializeLock`, `RAW_SQL_INDEXES`, `assertRawSqlIndexes`, `runDbConformance`) are `experimental` and documented in the API reference (`npm run docs:packages`).
253
+
254
+ ## Permissions and settings
255
+
256
+ The data layer declares no permission or setting of its own; the API slices do. It **seeds** them: `seedPlatform` writes the roles, the permissions and the default grants an app's permission registry rendered into `prisma/catalog/permissions.json`, and the `global` system settings row from the settings namespaces' defaults in `prisma/catalog/system-settings-defaults.json` (stability `experimental`). A permission or a settings key is added in the registry plus a catalog regeneration (`npm run catalog:permissions`, `npm run catalog:settings` in the reference app), never in this package. Defaults are written once: the row is never overwritten, so a changed default reaches an existing deployment only through its own migration or the settings API.
257
+
258
+ ## UI
259
+
260
+ None. The package renders nothing.
261
+
262
+ ## Infra
263
+
264
+ None. The package ships no deployment configuration. The commands that touch a database (`db drift`, `db check --database`, `db baseline`) read `DATABASE_URL` (and optionally `SHADOW_DATABASE_URL`) from the environment of the process; the app's scripts build the first from its `POSTGRES_*` variables, and the package adds no variable of its own. The one variable the seed uses is `INITIAL_ADMIN_EMAIL` (the initial administrator), which `platformSeedInputFrom` reads only from the `env` object it is handed. CI runs `db:check`, `db:check:database` and `db:drift` in the `smoke` job after `prisma:migrate`.
265
+
266
+ ## Observability
267
+
268
+ None. The package emits nothing at run time.
269
+
270
+ ## Security notes
271
+
272
+ The composer reads and writes schema text only: it opens no database connection and reads no environment variable. A fragment cannot add a column to a platform table (the `EXTEND_SCALAR_FIELD` and `EXTEND_OWNING_RELATION` rejections), so an app cannot weaken a platform constraint through composition. No secret belongs in a fragment: secrets are stored encrypted in the `credentials`, `user_credentials` and `user_ai_keys` tables, never as a column that holds plaintext. Raw-SQL partial unique indexes stay in migration SQL, never as `@@unique` (see the repository's invariants).
273
+
274
+ Raw-SQL partial unique indexes stay in migration SQL, never as `@@unique` (see the repository's invariants), and `platform db drift` asserts them against `pg_indexes` rather than filtering Prisma's diff. The tooling reads and writes only migration files, the lock and the manifest. It holds no credential: `db drift` and `check --database` use the `DATABASE_URL` the caller supplies, and `drift` creates and drops only its own throwaway shadow database. An installed migration is never edited: `platform.lock` proves it, and Prisma does not (`migrate deploy` and `migrate status` stay silent about an applied file that changed afterwards).
275
+
276
+ ## Conformance suite
277
+
278
+ `runDbConformance({ appRoot })` registers the offline `db` suite in the app's own test run (Jest, or Vitest with `globals: true`; or pass `testApi`). It needs no database:
279
+
280
+ | Test | Fails when |
281
+ |---|---|
282
+ | `raw-sql-indexes` | the raw-SQL index tripwire above is tripped |
283
+ | `platform.lock` | an installed migration differs from the lock or the package, a package migration is not installed, or a locked directory is missing (the same check as `platform db check`) |
284
+
285
+ ```ts
286
+ // apps/api/test/prisma/platform-db-conformance.spec.ts
287
+ import { runDbConformance } from '@marinoscar/platform-db';
288
+ runDbConformance({ appRoot: join(__dirname, '..', '..') });
289
+ ```
290
+
291
+ It sits beside, not inside, `runPlatformConformance()` of `@marinoscar/platform-api/testing`: that harness scans TypeScript source roots, and this suite reads SQL and Prisma files. The real-database half (`platform db check --database` and `platform db drift`) runs in the app's `smoke` job, because it needs Postgres.
292
+
293
+ ## Upgrade notes
294
+
295
+ After every version bump of `@marinoscar/platform-db`, run `npm run db:sync`, review the new directories under `prisma/migrations/`, commit them with the updated `platform.lock`, then `npm run prisma:migrate`. No version has been published yet, so there is nothing older to migrate from.
296
+
297
+ The first adoption of platform history v1 by an app that already has these tables is a **baseline**, not a sync: the database must not re-run the 22 migrations. The reference app is already baselined (its directories are the installed copies and `platform.lock` maps them); a fork or another app follows [the baseline runbook](../../docs/runbooks/database-baseline.md) with `platform db baseline` ([ADR 0002](../../docs/adr/0002-database-packaging-and-rls.md) D4). **Baseline before the first deploy** of an app version that depends on this package, never from `appctl deploy update`.
298
+
299
+ `platform db baseline` is a dry run unless `--apply` is given, and a dry run writes nothing and runs no `prisma migrate resolve`:
300
+
301
+ | Step | What it does |
302
+ |---|---|
303
+ | B1 map | Matches each platform migration to one of the app's directories by identical bytes (a directory rename is irrelevant), else identical after stripping comments and whitespace (the lock records `localSha256` and a `note`), else the `--map <file.json>` (`{ "platform:0019_...": "<localDir>" }`). Reports unmatched migrations and app-only directories |
304
+ | B2 ledger | Every mapped directory must be a finished, non-rolled-back row of `_prisma_migrations` with the local file's checksum. A failed or rolled-back row is checked first and stops the run |
305
+ | B3 diff | Replays the package history up to `--through` in a shadow database and diffs it against the **live** database. A statement a `deviations[].expectDiff` entry of `platform.lock` declares is allowed; any other refuses |
306
+ | B4 indexes | Asserts every raw-SQL index of the package (up to `--through`) and of the lock's `rawSqlIndexes` in `pg_indexes`, name and definition |
307
+ | B5 act | `--apply` only. Installs each migration that has no directory (a byte copy placed right after its package predecessor, so a fresh database applies the history in package order), runs `prisma migrate resolve --applied` for those at or below `--through`, and writes `platform.lock` last |
308
+ | B6 verify | `prisma migrate status`, `platform db check` and the ledger comparison |
309
+
310
+ `--through <NNNN>` names the platform migration the database equals (default: the newest). Below the newest is partial adoption: the rest is installed, and `prisma migrate deploy` applies it. `--force-remap` allows `--apply` over a lock that already has entries. `--shadow-database-url` supplies the empty database the replay needs (default: a throwaway one is created next to the live one and dropped). There is no `--force`. It never creates, drops or alters a database object: the only write to the database is `migrate resolve --applied`, through the app's `scripts/prisma-env.js`. Exit code 0 when clean, 1 on a refusal or a failed verification, 2 on a usage error.
311
+
312
+ A migration that changes a package-owned table is authored in the base app and promoted into the package; see [Authoring a platform migration](../../docs/DEVELOPMENT.md#authoring-a-platform-migration). Only one pull request labelled `pp:migration` may be open at a time; a second one waits, rebases, deletes its local directory and re-runs `prisma migrate dev --create-only` and `platform db promote`, so its directory gets a newer timestamp.
313
+
314
+ ## Troubleshooting
315
+
316
+ Build and import problems common to every platform package are in [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages). Composer errors print `file:line: CODE: message`.
317
+
318
+ | Symptom | Cause | Fix |
319
+ |---|---|---|
320
+ | `platform: @marinoscar/platform-db is not built` | The `platform` command runs `dist/` | `npm run build:packages` from the repository root |
321
+ | `db:compose:check` fails in CI | A fragment changed without re-composing, or a generated file was edited by hand | `npm run db:compose --workspace=api` and commit the result |
322
+ | `Seed catalog .../permissions.json cannot be read` | `readSeedSnapshot` was pointed at a folder without the committed catalogs | Run the app's catalog scripts and commit `prisma/catalog/` |
323
+ | A new permission is not granted after `prisma:seed` | The catalog is stale, so the registry's grant never reached the seed (the log prints `⊘ Skipped grant with no matching row`) | Regenerate the catalogs and re-run the seed |
324
+ | `NOT_EXTENSIBLE` | The model is not marked `// @extensible` by its owner | Use a side table keyed by the platform id, or file a seam request |
325
+ | `UNKNOWN_MODEL` | No fragment declares the model | Check the spelling; the model must exist in a platform or app fragment |
326
+ | `FIELD_COLLISION` | The field name already exists on the model or in an earlier `extend` | Rename the back-relation field |
327
+ | `EXTEND_SCALAR_FIELD`, `EXTEND_OWNING_RELATION`, `EXTEND_BLOCK_ATTRIBUTE` | The `extend` block would change the platform's table | Keep the column or index on your own model; the block holds back-relation fields only |
328
+ | `EXTEND_UNKNOWN_TYPE` | The field's type is no model | Declare the model in a fragment |
329
+ | `DUPLICATE_MODEL` | A model or enum is declared in two fragments | Declare it once; add relations to a platform model with `extend model` |
330
+ | `DUPLICATE_BASE` | A second `generator` of the same name or a second `datasource` | Provide a `base.prisma` in the app's fragments instead (it replaces the package's) |
331
+ | `MALFORMED` | A header or footer is not `prisma format` shaped | Put `<kind> <Name> {` on one line at column 0 and end the block with `}` alone at column 0 |
332
+ | `UNLISTED_RAW_INDEX` (tripwire) | A migration creates a partial or expression index that `raw-sql-indexes.json` does not list | Add it to `raw-sql-indexes.json` with a reason, its table and a design document |
333
+ | `LISTED_INDEX_NOT_FOUND`, `LISTED_INDEX_MISMATCH` (tripwire) | A listed index is not left by the migrations, is no longer partial, or its table, uniqueness or `createdIn` is wrong | Restore the migration, or correct the list entry |
334
+ | `FRAGMENT_DECLARES_RAW_INDEX` (tripwire) | A fragment has `@@unique`, `@@index` or `@unique` under a raw-SQL index's name or on its key columns | Remove it: Prisma would build a full index, and the drift is intentional |
335
+ | `Could not find Prisma Schema` | `prisma.config.ts` has no `schema` | Set `schema: 'prisma/schema'` |
336
+ | `No migration found in prisma/migrations` | `migrations.path` missing: with a schema folder the default becomes `<schema folder>/migrations` | Set `migrations: { path: 'prisma/migrations' }` |
337
+
338
+ Build and import problems common to every platform package are in [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages). Each `platform db check` problem names the migration and has one fix:
339
+
340
+ | Code | Meaning | Fix |
341
+ |---|---|---|
342
+ | `LOCAL_MODIFIED` | An installed `migration.sql` no longer hashes to the lock | Restore the file from Git. Never edit an installed migration; add a new one. If it differs from the package only in comments, record `localSha256` and `note` in the lock entry |
343
+ | `PACKAGE_MODIFIED` | The lock's hash differs from the manifest's for that migration: a released package migration was rewritten | Restore the package file and manifest entry; fix the mistake in a new migration |
344
+ | `PACKAGE_FILE_MODIFIED` | The package's `migration.sql` differs from its manifest hash, or is missing | Restore the file, or reinstall the package |
345
+ | `NOT_INSTALLED` | A package migration is not in the lock | Run `npm run db:sync` |
346
+ | `LOCAL_DIR_MISSING` | A directory the lock names does not exist | Restore it from Git; do not rename installed directories |
347
+ | `NOT_IN_PACKAGE` | The lock names a migration the manifest no longer has | A package must never drop a released migration; reinstall the matching version |
348
+ | `LOCAL_OUT_OF_ORDER` | Installed directories do not sort in package order | Restore the original directory names; a fresh database would apply them in another order |
349
+ | `LEDGER_CHECKSUM_MISMATCH` (`--database`) | A file was edited after the database applied it | Restore the file; the database keeps the original checksum |
350
+ | `LEDGER_UNFINISHED` (`--database`) | A row of `_prisma_migrations` never finished | `prisma migrate resolve --rolled-back <dir>` or `--applied <dir>`, after checking the database |
351
+
352
+ `platform db sync` refuses with `LOCK_GAP` (the lock is not an in-order prefix of the package history: restore `platform.lock`), `REQUIRES_VIOLATION` (a manifest entry requires a slice no earlier entry provides: a package bug) or `PACKAGE_FILE_MISMATCH` (a package file does not match its manifest hash; nothing is copied). `platform db promote` refuses with `PROMOTE_NOT_SYNCED` (run `db:sync` first), `PROMOTE_ORDER` (the directory sorts before the last installed platform migration: rebase and regenerate it) and `PROMOTE_CONFLICT` (the slug or directory is already recorded with different bytes).
353
+
354
+ `platform db baseline` refuses with a code, and prints the report first ([the runbook](../../docs/runbooks/database-baseline.md) has the fix for each):
355
+
356
+ | Code | Meaning | Fix |
357
+ |---|---|---|
358
+ | `LEDGER_FAILED_ROW` | `_prisma_migrations` has a row that never finished or was rolled back, with no later successful run | Resolve it with `prisma migrate resolve --rolled-back` or `--applied` after checking the database (runbook section 8) |
359
+ | `LEDGER_ROW_MISSING`, `LEDGER_CHECKSUM_MISMATCH` | A mapped directory is not recorded as applied, or its file was edited after it was | Lower `--through`, or restore the file from Git |
360
+ | `DIFF_BLOCKING` | The live database differs from the package history up to `--through` in a statement no deviation declares | Write a forward migration, declare it under `deviations` in `platform.lock` (the statement as printed), or lower `--through` |
361
+ | `INDEX_MISSING`, `INDEX_DEFINITION_DIFFERS` | A raw-SQL index is missing or lost its `WHERE` clause (Prisma's diff cannot see this) | Re-create it from the definition printed, in a forward migration |
362
+ | `LOCK_NOT_EMPTY` | `platform.lock` already has entries | `--force-remap`, after reading the dry run |
363
+ | `PLACEMENT_IMPOSSIBLE` | The directories cannot sort in package order | Rename an app directory the database has not applied, or re-map |
364
+ | `MAP_INVALID` | `--map` is not valid, or names a directory another migration already matches exactly | Fix the file |
365
+ | `THROUGH_UNKNOWN`, `PACKAGE_FILE_MISMATCH` | `--through` names no migration, or a package file does not match its manifest hash | Use `22`, `0022` or `platform:0022_slug`; reinstall the package |
366
+ | `RESOLVE_FAILED` | `prisma migrate resolve --applied` failed; the directory created for that step was removed and no lock was written | Read Prisma's message (`P3008` means the directory is already recorded); fix and re-run, the migrations already resolved are mapped by hash |
367
+
368
+ `permission denied to create database` means the role cannot create the throwaway shadow database: pass `--shadow-database-url`. `P3005` on `migrate deploy` means the database was never managed by Prisma Migrate: the baseline records every migration up to `--through` with `migrate resolve --applied`, which creates the ledger.
369
+
370
+ `platform db drift` prints `SCHEMA_DRIFT` with the SQL that is in the schema but in no migration (add a migration), `INDEX_MISSING` or `INDEX_DEFINITION_DIFFERS` for a raw-SQL index that was dropped or re-created without its `WHERE` clause. `Error: You must set datasource.shadowDatabaseUrl` means `prisma.config.ts` does not pass `process.env.SHADOW_DATABASE_URL` through.
371
+
372
+ ## Links
373
+
374
+ - [Platform packages spec](../../docs/specs/platform-packages.md): the extension contract and the package documentation standard
375
+ - [ADR 0002](../../docs/adr/0002-database-packaging-and-rls.md): the fragment layout, the `extend model` syntax and the rule table (D1, D2)
376
+
377
+ - [ADR 0002](../../docs/adr/0002-database-packaging-and-rls.md): why migrations are installed with app-local timestamps and a lock (D3)
378
+ - [Authoring a platform migration](../../docs/DEVELOPMENT.md#authoring-a-platform-migration): `migrate dev --create-only`, `promote`, and the one-open-`pp:migration`-PR rule
379
+ - [`seed` slice README](src/seed/README.md): `seedPlatform`, input building, the never-delete rule and the app seed hook
380
+ - [Package documentation standard and checks](../../docs/PACKAGES.md): how this README, the TSDoc and the catalog are checked
381
+ - [DEVELOPMENT.md § Making Database Changes](../../docs/DEVELOPMENT.md#making-database-changes): the schema editing workflow
382
+ - [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages): build, test and lint commands
2
383
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ // `platform db compose [--check]`: the router of the platform tools (see
3
+ // src/bin/platform.ts). This shim is committed so npm can link the bin at
4
+ // install time, before the package is built; it runs the compiled dist/, so in
5
+ // this repository `npm run build:packages` comes first (same pattern as
6
+ // packages/platform-infra/bin/platform-infra.mjs).
7
+ 'use strict';
8
+
9
+ let main;
10
+ try {
11
+ ({ main } = require('../dist/bin/platform.js'));
12
+ } catch (e) {
13
+ if (e && e.code === 'MODULE_NOT_FOUND' && String(e.message).includes('dist/bin/platform.js')) {
14
+ process.stderr.write('platform: @marinoscar/platform-db is not built. Run "npm run build:packages" from the repository root.\n');
15
+ process.exit(1);
16
+ }
17
+ throw e;
18
+ }
19
+
20
+ main(process.argv.slice(2)).then(
21
+ (code) => {
22
+ process.exitCode = code;
23
+ },
24
+ (e) => {
25
+ process.stderr.write(`${e && e.stack ? e.stack : String(e)}\n`);
26
+ process.exitCode = 1;
27
+ },
28
+ );
@@ -0,0 +1,32 @@
1
+ import type { BaselineDeps } from './run.js';
2
+ /**
3
+ * Inputs of {@link createBaselineDeps}.
4
+ *
5
+ * @stability experimental
6
+ */
7
+ export interface BaselineDepsOptions {
8
+ /** The app's directory: where `prisma.config.ts` and `scripts/prisma-env.js` live; the Prisma CLI runs here. */
9
+ root: string;
10
+ /** Connection string of the live database (the app's `DATABASE_URL`). */
11
+ databaseUrl: string;
12
+ /** The environment the Prisma CLI inherits. */
13
+ env: NodeJS.ProcessEnv;
14
+ /** A pre-created empty shadow database for the replay; when omitted a throwaway one is created next to the live one and dropped. */
15
+ shadowDatabaseUrl?: string | undefined;
16
+ /** The script that builds `DATABASE_URL` and runs Prisma (default: `<root>/scripts/prisma-env.js`, else the `prisma` package of the app). */
17
+ prismaScript?: string | undefined;
18
+ /** Logs one action or finding. */
19
+ log: (line: string) => void;
20
+ /** The clock. */
21
+ now: () => Date;
22
+ }
23
+ /**
24
+ * Builds the real {@link BaselineDeps}: reads through `pg`, and runs every Prisma
25
+ * CLI call through the app's `scripts/prisma-env.js` (never a bare `npx prisma`).
26
+ *
27
+ * @param options - See {@link BaselineDepsOptions}.
28
+ * @returns The dependencies for `runBaseline`.
29
+ * @stability experimental
30
+ */
31
+ export declare function createBaselineDeps(options: BaselineDepsOptions): BaselineDeps;
32
+ //# sourceMappingURL=deps.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deps.d.ts","sourceRoot":"","sources":["../../src/baseline/deps.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAgB,MAAM,UAAU,CAAC;AAE3D;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,gHAAgH;IAChH,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,WAAW,EAAE,MAAM,CAAC;IACpB,+CAA+C;IAC/C,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,oIAAoI;IACpI,iBAAiB,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACvC,6IAA6I;IAC7I,YAAY,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAClC,kCAAkC;IAClC,GAAG,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAC5B,iBAAiB;IACjB,GAAG,EAAE,MAAM,IAAI,CAAC;CACjB;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAuD7E"}
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createBaselineDeps = createBaselineDeps;
4
+ const node_child_process_1 = require("node:child_process");
5
+ const node_fs_1 = require("node:fs");
6
+ const node_path_1 = require("node:path");
7
+ const index_js_1 = require("../drift/index.js");
8
+ /**
9
+ * Builds the real {@link BaselineDeps}: reads through `pg`, and runs every Prisma
10
+ * CLI call through the app's `scripts/prisma-env.js` (never a bare `npx prisma`).
11
+ *
12
+ * @param options - See {@link BaselineDepsOptions}.
13
+ * @returns The dependencies for `runBaseline`.
14
+ * @stability experimental
15
+ */
16
+ function createBaselineDeps(options) {
17
+ const script = options.prismaScript ?? (0, node_path_1.join)(options.root, 'scripts', 'prisma-env.js');
18
+ function runPrisma(args, extraEnv = {}) {
19
+ const entry = (0, node_fs_1.existsSync)(script) ? script : (0, index_js_1.prismaCli)(options.root);
20
+ const result = (0, node_child_process_1.spawnSync)(process.execPath, [entry, ...args], {
21
+ cwd: options.root,
22
+ env: { ...options.env, DATABASE_URL: options.databaseUrl, ...extraEnv },
23
+ encoding: 'utf8',
24
+ maxBuffer: 64 * 1024 * 1024,
25
+ });
26
+ if (result.error)
27
+ throw result.error;
28
+ return { status: result.status ?? 1, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
29
+ }
30
+ return {
31
+ log: options.log,
32
+ now: options.now,
33
+ async readLedger() {
34
+ const Client = (0, index_js_1.loadPg)(options.root);
35
+ const client = new Client({ connectionString: options.databaseUrl });
36
+ await client.connect();
37
+ try {
38
+ const present = await client.query("SELECT to_regclass('public._prisma_migrations') IS NOT NULL AS present");
39
+ if (!present.rows[0]?.present)
40
+ return undefined;
41
+ const { rows } = await client.query('SELECT migration_name, checksum, finished_at, rolled_back_at FROM _prisma_migrations ORDER BY started_at, migration_name');
42
+ return rows.map((row) => ({
43
+ migrationName: String(row.migration_name),
44
+ checksum: String(row.checksum),
45
+ finishedAt: row.finished_at ? new Date(row.finished_at) : null,
46
+ rolledBackAt: row.rolled_back_at ? new Date(row.rolled_back_at) : null,
47
+ }));
48
+ }
49
+ finally {
50
+ await client.end();
51
+ }
52
+ },
53
+ readIndexes: () => (0, index_js_1.readIndexRows)(options.databaseUrl, options.root),
54
+ diffReplayToLive: (replayMigrationsDir) => (0, index_js_1.withShadowDatabase)({ cwd: options.root, databaseUrl: options.databaseUrl, shadowDatabaseUrl: options.shadowDatabaseUrl }, async (shadowUrl) => {
55
+ const result = runPrisma(['migrate', 'diff', '--from-migrations', replayMigrationsDir, '--to-config-datasource', '--script'], { SHADOW_DATABASE_URL: shadowUrl });
56
+ if (result.status !== 0) {
57
+ throw new Error(`prisma migrate diff failed (exit ${result.status}): ${(result.stderr || result.stdout).trim()}`);
58
+ }
59
+ return (0, index_js_1.stripBanner)(result.stdout);
60
+ }),
61
+ prisma: async (args) => runPrisma(args),
62
+ };
63
+ }
64
+ //# sourceMappingURL=deps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deps.js","sourceRoot":"","sources":["../../src/baseline/deps.ts"],"names":[],"mappings":";;AAqCA,gDAuDC;AA5FD,2DAA+C;AAC/C,qCAAqC;AACrC,yCAAiC;AACjC,gDAAsG;AA0BtG;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAAC,OAA4B;IAC7D,MAAM,MAAM,GAAG,OAAO,CAAC,YAAY,IAAI,IAAA,gBAAI,EAAC,OAAO,CAAC,IAAI,EAAE,SAAS,EAAE,eAAe,CAAC,CAAC;IAEtF,SAAS,SAAS,CAAC,IAAuB,EAAE,WAA8B,EAAE;QAC1E,MAAM,KAAK,GAAG,IAAA,oBAAU,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAA,oBAAS,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACpE,MAAM,MAAM,GAAG,IAAA,8BAAS,EAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,GAAG,IAAI,CAAC,EAAE;YAC3D,GAAG,EAAE,OAAO,CAAC,IAAI;YACjB,GAAG,EAAE,EAAE,GAAG,OAAO,CAAC,GAAG,EAAE,YAAY,EAAE,OAAO,CAAC,WAAW,EAAE,GAAG,QAAQ,EAAE;YACvE,QAAQ,EAAE,MAAM;YAChB,SAAS,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI;SAC5B,CAAC,CAAC;QACH,IAAI,MAAM,CAAC,KAAK;YAAE,MAAM,MAAM,CAAC,KAAK,CAAC;QACrC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,IAAI,EAAE,EAAE,CAAC;IAClG,CAAC;IAED,OAAO;QACL,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,KAAK,CAAC,UAAU;YACd,MAAM,MAAM,GAAG,IAAA,iBAAM,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC;YACpC,MAAM,MAAM,GAAG,IAAI,MAAM,CAAC,EAAE,gBAAgB,EAAE,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;YACrE,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;YACvB,IAAI,CAAC;gBACH,MAAM,OAAO,GAAG,MAAM,MAAM,CAAC,KAAK,CAAC,wEAAwE,CAAC,CAAC;gBAC7G,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,OAAO;oBAAE,OAAO,SAAS,CAAC;gBAChD,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,MAAM,CAAC,KAAK,CACjC,0HAA0H,CAC3H,CAAC;gBACF,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;oBACxB,aAAa,EAAE,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC;oBACzC,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC;oBAC9B,UAAU,EAAE,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI;oBAC9D,YAAY,EAAE,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,IAAI;iBACvE,CAAC,CAAC,CAAC;YACN,CAAC;oBAAS,CAAC;gBACT,MAAM,MAAM,CAAC,GAAG,EAAE,CAAC;YACrB,CAAC;QACH,CAAC;QACD,WAAW,EAAE,GAAG,EAAE,CAAC,IAAA,wBAAa,EAAC,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,IAAI,CAAC;QACnE,gBAAgB,EAAE,CAAC,mBAAmB,EAAE,EAAE,CACxC,IAAA,6BAAkB,EAChB,EAAE,GAAG,EAAE,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,CAAC,WAAW,EAAE,iBAAiB,EAAE,OAAO,CAAC,iBAAiB,EAAE,EACrG,KAAK,EAAE,SAAS,EAAE,EAAE;YAClB,MAAM,MAAM,GAAG,SAAS,CACtB,CAAC,SAAS,EAAE,MAAM,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,UAAU,CAAC,EACnG,EAAE,mBAAmB,EAAE,SAAS,EAAE,CACnC,CAAC;YACF,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,oCAAoC,MAAM,CAAC,MAAM,MAAM,CAAC,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;YACpH,CAAC;YACD,OAAO,IAAA,sBAAW,EAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QACpC,CAAC,CACF;QACH,MAAM,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,IAAI,CAAC;KACxC,CAAC;AACJ,CAAC"}