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

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 (244) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/LICENSE +21 -0
  3. package/README.md +525 -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 +66 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +36 -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 +127 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +89 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +117 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +358 -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 +311 -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/app-objects.d.ts +107 -0
  78. package/dist/drift/app-objects.d.ts.map +1 -0
  79. package/dist/drift/app-objects.js +193 -0
  80. package/dist/drift/app-objects.js.map +1 -0
  81. package/dist/drift/db-conformance.d.ts +52 -0
  82. package/dist/drift/db-conformance.d.ts.map +1 -0
  83. package/dist/drift/db-conformance.js +89 -0
  84. package/dist/drift/db-conformance.js.map +1 -0
  85. package/dist/drift/index.d.ts +8 -0
  86. package/dist/drift/index.d.ts.map +1 -0
  87. package/dist/drift/index.js +43 -0
  88. package/dist/drift/index.js.map +1 -0
  89. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  90. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-indexes.js +113 -0
  92. package/dist/drift/raw-sql-indexes.js.map +1 -0
  93. package/dist/drift/raw-sql-tripwire.d.ts +191 -0
  94. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  95. package/dist/drift/raw-sql-tripwire.js +422 -0
  96. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  97. package/dist/drift/rls-policies.d.ts +226 -0
  98. package/dist/drift/rls-policies.d.ts.map +1 -0
  99. package/dist/drift/rls-policies.js +317 -0
  100. package/dist/drift/rls-policies.js.map +1 -0
  101. package/dist/drift/run.d.ts +152 -0
  102. package/dist/drift/run.d.ts.map +1 -0
  103. package/dist/drift/run.js +252 -0
  104. package/dist/drift/run.js.map +1 -0
  105. package/dist/drift/sql-expression.d.ts +27 -0
  106. package/dist/drift/sql-expression.d.ts.map +1 -0
  107. package/dist/drift/sql-expression.js +64 -0
  108. package/dist/drift/sql-expression.js.map +1 -0
  109. package/dist/index.d.ts +16 -0
  110. package/dist/index.d.ts.map +1 -0
  111. package/dist/index.js +33 -0
  112. package/dist/index.js.map +1 -0
  113. package/dist/lock/hash.d.ts +13 -0
  114. package/dist/lock/hash.d.ts.map +1 -0
  115. package/dist/lock/hash.js +19 -0
  116. package/dist/lock/hash.js.map +1 -0
  117. package/dist/lock/index.d.ts +5 -0
  118. package/dist/lock/index.d.ts.map +1 -0
  119. package/dist/lock/index.js +20 -0
  120. package/dist/lock/index.js.map +1 -0
  121. package/dist/lock/lock.d.ts +154 -0
  122. package/dist/lock/lock.d.ts.map +1 -0
  123. package/dist/lock/lock.js +151 -0
  124. package/dist/lock/lock.js.map +1 -0
  125. package/dist/lock/manifest.d.ts +68 -0
  126. package/dist/lock/manifest.d.ts.map +1 -0
  127. package/dist/lock/manifest.js +96 -0
  128. package/dist/lock/manifest.js.map +1 -0
  129. package/dist/lock/semver.d.ts +10 -0
  130. package/dist/lock/semver.d.ts.map +1 -0
  131. package/dist/lock/semver.js +13 -0
  132. package/dist/lock/semver.js.map +1 -0
  133. package/dist/seed/index.d.ts +5 -0
  134. package/dist/seed/index.d.ts.map +1 -0
  135. package/dist/seed/index.js +16 -0
  136. package/dist/seed/index.js.map +1 -0
  137. package/dist/seed/input.d.ts +52 -0
  138. package/dist/seed/input.d.ts.map +1 -0
  139. package/dist/seed/input.js +77 -0
  140. package/dist/seed/input.js.map +1 -0
  141. package/dist/seed/seed-platform.d.ts +41 -0
  142. package/dist/seed/seed-platform.d.ts.map +1 -0
  143. package/dist/seed/seed-platform.js +165 -0
  144. package/dist/seed/seed-platform.js.map +1 -0
  145. package/dist/seed/steps.d.ts +172 -0
  146. package/dist/seed/steps.d.ts.map +1 -0
  147. package/dist/seed/steps.js +136 -0
  148. package/dist/seed/steps.js.map +1 -0
  149. package/dist/seed/types.d.ts +287 -0
  150. package/dist/seed/types.d.ts.map +1 -0
  151. package/dist/seed/types.js +5 -0
  152. package/dist/seed/types.js.map +1 -0
  153. package/dist/sync/app-migrations.d.ts +52 -0
  154. package/dist/sync/app-migrations.d.ts.map +1 -0
  155. package/dist/sync/app-migrations.js +62 -0
  156. package/dist/sync/app-migrations.js.map +1 -0
  157. package/dist/sync/apply.d.ts +29 -0
  158. package/dist/sync/apply.d.ts.map +1 -0
  159. package/dist/sync/apply.js +38 -0
  160. package/dist/sync/apply.js.map +1 -0
  161. package/dist/sync/check.d.ts +59 -0
  162. package/dist/sync/check.d.ts.map +1 -0
  163. package/dist/sync/check.js +115 -0
  164. package/dist/sync/check.js.map +1 -0
  165. package/dist/sync/errors.d.ts +32 -0
  166. package/dist/sync/errors.d.ts.map +1 -0
  167. package/dist/sync/errors.js +23 -0
  168. package/dist/sync/errors.js.map +1 -0
  169. package/dist/sync/index.d.ts +10 -0
  170. package/dist/sync/index.d.ts.map +1 -0
  171. package/dist/sync/index.js +27 -0
  172. package/dist/sync/index.js.map +1 -0
  173. package/dist/sync/ledger.d.ts +65 -0
  174. package/dist/sync/ledger.d.ts.map +1 -0
  175. package/dist/sync/ledger.js +49 -0
  176. package/dist/sync/ledger.js.map +1 -0
  177. package/dist/sync/plan.d.ts +63 -0
  178. package/dist/sync/plan.d.ts.map +1 -0
  179. package/dist/sync/plan.js +86 -0
  180. package/dist/sync/plan.js.map +1 -0
  181. package/dist/sync/promote.d.ts +62 -0
  182. package/dist/sync/promote.d.ts.map +1 -0
  183. package/dist/sync/promote.js +95 -0
  184. package/dist/sync/promote.js.map +1 -0
  185. package/dist/sync/timestamps.d.ts +41 -0
  186. package/dist/sync/timestamps.d.ts.map +1 -0
  187. package/dist/sync/timestamps.js +68 -0
  188. package/dist/sync/timestamps.js.map +1 -0
  189. package/dist/sync/version.d.ts +28 -0
  190. package/dist/sync/version.d.ts.map +1 -0
  191. package/dist/sync/version.js +66 -0
  192. package/dist/sync/version.js.map +1 -0
  193. package/migrations/0001_initial/migration.sql +297 -0
  194. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  195. package/migrations/0003_add_credentials/migration.sql +20 -0
  196. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  197. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  198. package/migrations/0006_add_notifications/migration.sql +22 -0
  199. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  200. package/migrations/0008_add_jobs/migration.sql +110 -0
  201. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  202. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  203. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  204. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  205. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  206. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  207. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  208. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  209. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  210. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  211. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  212. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  213. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  214. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  215. package/migrations/0023_add_organizations/migration.sql +142 -0
  216. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  217. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  218. package/migrations/0026_add_groups/migration.sql +165 -0
  219. package/migrations/0027_add_grants/migration.sql +117 -0
  220. package/migrations/0028_add_org_settings/migration.sql +49 -0
  221. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  222. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  223. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  224. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  225. package/migrations/0033_add_android_app/migration.sql +60 -0
  226. package/migrations/0034_open_job_reason/migration.sql +16 -0
  227. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  228. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  229. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  230. package/migrations/manifest.json +379 -0
  231. package/package.json +78 -4
  232. package/raw-sql-indexes.json +94 -0
  233. package/rls-policies.json +74 -0
  234. package/schema/ai.prisma +444 -0
  235. package/schema/android-app.prisma +47 -0
  236. package/schema/base.prisma +11 -0
  237. package/schema/credentials.prisma +170 -0
  238. package/schema/db-backup.prisma +376 -0
  239. package/schema/identity.prisma +439 -0
  240. package/schema/jobs.prisma +760 -0
  241. package/schema/notifications.prisma +649 -0
  242. package/schema/settings.prisma +60 -0
  243. package/schema/sharing.prisma +223 -0
  244. package/schema/storage.prisma +84 -0
package/README.md CHANGED
@@ -1,3 +1,526 @@
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/`, 41 models and 12 enums in nine slices), `platform db compose`, and the migration tooling (`platform db sync|check|promote|drift|policies`, 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 (the current channel and how to install it: the [release runbook](../../docs/runbooks/release-platform-packages.md)). 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 | Required |
22
+ |---|---|---|
23
+ | `zod` | `^4.4.3` | yes (`lock`, and so `sync`, `drift`, `baseline` and the `platform db` CLI) |
24
+ | `prisma` | `^7.8.0` | optional: the `drift` slice and the CLI resolve its `build/index.js` at run time |
25
+ | `pg` | `^8.23.0` | optional: the `drift` slice loads it by name |
26
+
27
+ `@prisma/client` is not a peer of this package: the seed takes the app's client as a structural type ([the rule](../../docs/PACKAGES.md#peer-dependencies-per-slice)). The app has it anyway.
28
+
29
+ ## Quick start
30
+
31
+ In an app that already depends on the package (the reference app is `apps/api`):
32
+
33
+ ```bash
34
+ # once, and after pulling platform changes: the `platform` command runs the built package
35
+ npm run build:packages
36
+
37
+ cd apps/api
38
+ npm run db:compose # platform fragments + prisma/fragments/ -> prisma/schema/ (committed)
39
+ npm run prisma:generate
40
+ npm run db:compose:check # CI: exits 1 when prisma/schema/ differs from a fresh compose
41
+ ```
42
+
43
+ `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:
44
+
45
+ ```ts
46
+ export default defineConfig({
47
+ schema: 'prisma/schema', // the generated FOLDER
48
+ datasource: { url: process.env.DATABASE_URL as string },
49
+ migrations: { path: 'prisma/migrations' }, // must be explicit with a schema folder
50
+ });
51
+ ```
52
+
53
+ To add an app model that points at a platform model, see the example in [Extension-point catalog](#extension-point-catalog).
54
+
55
+ **Migrations.** Wire the commands into the app's `package.json` and run them from the directory that holds `prisma/`:
56
+
57
+ ```json
58
+ {
59
+ "scripts": {
60
+ "db:sync": "platform db sync",
61
+ "db:check": "platform db check",
62
+ "db:drift": "node scripts/platform-env.js db drift",
63
+ "db:baseline": "node scripts/platform-env.js db baseline"
64
+ }
65
+ }
66
+ ```
67
+
68
+ ```bash
69
+ npm run db:sync # install package migrations the lock does not hold yet
70
+ npm run prisma:migrate # apply them, explicitly (the API never migrates on startup)
71
+ npm run db:check # prove the installed SQL is still byte-identical to the package's
72
+ ```
73
+
74
+ `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.
75
+
76
+ ## Configuration
77
+
78
+ `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).
79
+
80
+ | Option | Type | Default | Meaning |
81
+ |---|---|---|---|
82
+ | `--check` | flag | off | Write nothing; exit 1 and print a diff when the generated folder differs from a fresh compose |
83
+ | `--root <dir>` | path | current directory | The app's directory |
84
+ | `--fragments <dir>` | path | `prisma/fragments` | The app's own fragments (a missing folder means none) |
85
+ | `--out <dir>` | path | `prisma/schema` | The generated folder Prisma reads |
86
+ | `--platform-schema <dir>` | path | the package's `schema/` | Override the platform fragments (tests, unusual layouts) |
87
+
88
+ Exit codes: 0 success, 1 `--check` found a stale folder, 2 a rejected fragment or a usage error.
89
+
90
+ 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.
91
+
92
+ **Migration commands.** The package is tooling and data, with no `forRoot()` or module option. The commands take flags:
93
+
94
+ | Command | Flags |
95
+ |---|---|
96
+ | `platform db sync` | `--check` (same as `check`), `--dry-run`, `--timestamp <iso>` (the clock for the new directory names), `--root <dir>`, `--package-dir <dir>` |
97
+ | `platform db check` | `--database` (also compare `_prisma_migrations`; needs `DATABASE_URL`), `--root`, `--package-dir` |
98
+ | `platform db promote <localDir>` | `--id <slug>` (required), `--since <version>`, `--slice <slice>`, `--requires <slices>`, `--root`, `--package-dir` |
99
+ | `platform db drift` | `--schema <path>` (default `prisma/schema`, else `prisma/schema.prisma`), `--shadow-database-url <url>`, `--root` |
100
+ | `platform db policies` | `--root`, `--package-dir`: prints the row-level-security policies the app's migrations leave, as `platform.lock` `rlsPolicies` entries with their expression hashes |
101
+
102
+ `--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`.
103
+
104
+ `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).
105
+
106
+ ## Extension-point catalog
107
+
108
+ The extension ladder and a recipe per extension: [docs/EXTENDING.md](../../docs/EXTENDING.md).
109
+
110
+ 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.
111
+
112
+ | Name | Kind | Signature | When to use | Stability | Example |
113
+ |---|---|---|---|---|---|
114
+ | `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`, `Organization`, `Role`, `Notification`, `Grant`, ... see the table below) and Prisma needs the back-relation field on the platform side | experimental | [example](../../apps/api/test/examples/db/coach-notes.prisma) |
115
+
116
+ Stability stays `experimental` until the extension contract is frozen (issue #727).
117
+
118
+ **`extend model`**
119
+
120
+ ```prisma
121
+ // apps/<app>/prisma/fragments/workouts.prisma
122
+ model Workout {
123
+ id String @id @default(uuid()) @db.Uuid
124
+ userId String @map("user_id") @db.Uuid
125
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
126
+
127
+ @@map("workouts")
128
+ }
129
+
130
+ extend model User {
131
+ workouts Workout[]
132
+ }
133
+ ```
134
+
135
+ 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.
136
+
137
+ Rules:
138
+
139
+ - Only a model its owner marked `// @extensible` can be extended (the table below). Everything else is closed; opening one more is a minor-version change reached through a seam request, never an app edit. Marking a model adds no column, key or index: the generated SQL of every existing table is unchanged and no migration is needed for a back-relation.
140
+ - 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.
141
+ - The slice or app that owns the foreign key writes the back-relation; the composer merges what is written and generates nothing.
142
+ - 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.
143
+ - 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.
144
+
145
+ **Which models are extensible, and what an app may hang on each**
146
+
147
+ | Model | Table | Ownership | An app may relate | Never |
148
+ |---|---|---|---|---|
149
+ | `User` | `users` | system | its own per-user rows (a plain key on `id`); app fields that fit a document go in [`metadata`](#app-metadata-on-users-and-organizations) with no table at all | a column; the credential and token tables |
150
+ | `Organization` | `organizations` | system | its own per-organization rows; org-owned app tables point here with a `Cascade` key on `org_id` | |
151
+ | `Role` | `roles` | system | per-role app data (a plain key on `id`) | `role_permissions`: `seedPlatform` owns the grants |
152
+ | `Group` | `groups` | org (row-level security) | app rows of a group: a composite key `(group_id, org_id)` -> `groups (id, org_id)` | a plain key on `id` alone |
153
+ | `Grant` | `grants` | org (row-level security) | an annotation of a grant: a composite key `(grant_id, org_id)` -> `grants (id, org_id)` | a plain key on `id` alone; an `@@unique` over the two partial unique indexes' columns |
154
+ | `AiRun` | `ai_runs` | org (row-level security) | an annotation of a run: a composite key `(ai_run_id, org_id)` -> `ai_runs (id, org_id)` | a copy of `request` (it holds the full prompt) |
155
+ | `StorageObject` | `storage_objects` | org (row-level security) | app rows about a file: a composite key `(object_id, org_id)` | |
156
+ | `Notification` | `notifications` | user | follow-up rows keyed by a notification (a plain key on `id`, `onDelete: Cascade` so the inbox purge keeps working) | |
157
+ | `NotificationDelivery` | `notification_deliveries` | user, optional | app annotations of a delivery receipt | |
158
+ | `Credential` | `credentials` | system | **non-secret bookkeeping only** (which feature uses it, when it was rotated) | the `secret` column: read plaintext through `CredentialsService`, never copy ciphertext or plaintext into an app table |
159
+ | `Job` | `jobs` | system, no row-level security | app rows tied to a job | `subject_type` / `subject_id` stay polymorphic, not keys |
160
+ | `Permission` | `permissions` | closed | nothing | **Deliberately closed.** A permission is a string the registry owns: `seedPlatform` upserts the rows by `name`, never deletes one, and a retired permission leaves through an expand/contract migration. A key from an app table would block that and tie app data to a row id no registry declares. An app refers to a permission by name in code |
161
+
162
+ `ai_runs` and `grants` carry an `(id, org_id)` unique key (migration `0036_add_app_metadata`) so an org-owned app table can link with a composite key, as `groups` and `storage_objects` already allowed: a plain foreign key on `id` would let a row of one organization point at another's, because a foreign-key check runs without row-level security. The worked example is [`coach-notes.prisma`](../../apps/api/test/examples/db/coach-notes.prisma) and its [migration](../../apps/api/test/examples/db/coach-notes.migration.sql): a table with keys to `notifications` and `grants`, a partial unique index and a policy, with `extend model` blocks on `Notification`, `Grant` and `Organization`, composed against the real platform fragments by [`app-schema-objects.spec.ts`](../../apps/api/test/examples/db/app-schema-objects.spec.ts) and run against Postgres by [`app-extension.db.spec.ts`](../../apps/api/test/examples/db/app-extension.db.spec.ts).
163
+
164
+ 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:
165
+
166
+ - **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`. [App migrations and the installed history](#app-migrations-and-the-installed-history) says what `sync` and `check` refuse.
167
+ - **App-owned raw-SQL indexes** go in `platform.lock` under `rawSqlIndexes` (`name` and `pg_indexes.indexdef`); `platform db drift` asserts them against the database next to the package's own, and `runDbConformance` asserts them offline against the migration SQL ([App schema objects, offline](#app-schema-objects-offline)).
168
+ - **App-owned row-level-security policies** go in `platform.lock` under `rlsPolicies` (`name`, `table` and, optionally, the hashes of the `USING` and `WITH CHECK` expressions that `platform db policies` prints); `platform db drift` asserts them against the database next to the package's own, and `runDbConformance` offline ([App tables with row-level security](#app-tables-with-row-level-security)).
169
+ - **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.
170
+ - **`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.
171
+
172
+ ## Data
173
+
174
+ **Fragments** (`schema/`, hand-edited by the platform; one file per slice, enums travel with their model):
175
+
176
+ | Fragment | Models |
177
+ |---|---|
178
+ | `base.prisma` | `generator client`, `datasource db` |
179
+ | `identity.prisma` | `User` (`@extensible`), `UserIdentity`, `Role`, `Permission`, `RolePermission`, `UserRole`, `RefreshToken`, `PersonalAccessToken`, `DeviceCode`, `AllowedEmail`, `AuditEvent`, `Organization`, `Membership`, `Invite` |
180
+ | `settings.prisma` | `SystemSettings`, `UserSettings`, `OrgSettings` |
181
+ | `storage.prisma` | `StorageObject` (`@extensible`), `StorageObjectChunk` |
182
+ | `credentials.prisma` | `Credential`, `UserCredential` |
183
+ | `notifications.prisma` | `Notification`, `NotificationDelivery`, `PushSubscription`, `NotificationBroadcast` |
184
+ | `jobs.prisma` | `Job` (`@extensible`), `JobStatsRollup`, `WorkerNode`, `NodeCredential`, `JobNodeSecret` |
185
+ | `db-backup.prisma` | `DatabaseBackupRun` |
186
+ | `ai.prisma` | `AiModel`, `UserAiKey`, `AiRun`, `AiUsageEvent` |
187
+ | `sharing.prisma` | `Group` (`@extensible`), `GroupMember`, `GroupInvite` |
188
+ | `android-app.prisma` | `AndroidAppRelease` (#746: the hosted Android APKs; `sizeBytes` BigInt; at most one current release through the raw-SQL index `android_app_releases_one_current_uniq_idx`) |
189
+
190
+ 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.
191
+
192
+ **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.
193
+
194
+ **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.
195
+
196
+ **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.
197
+
198
+ **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.
199
+
200
+ **Tenant tables (`0025_org_scoped_rls`).** `org_id` (with a foreign key to `organizations`) is on `storage_objects`, `storage_object_chunks`, `ai_runs` (NOT NULL, `Restrict`), `ai_usage_events` (nullable, `SetNull`: a deployment-wide event and the history of a deleted organization keep no organization) and `audit_events` (nullable, `SetNull`, no policy). The four tables other than `audit_events` `ENABLE` and `FORCE ROW LEVEL SECURITY` with one policy each ([below](#row-level-security-policies)); `storage_object_chunks` links to its object with the composite `(object_id, org_id)`, because a foreign-key check bypasses row-level security. The migration backfills every existing row to the default organization (system audit actions and catalogue-sync usage keep NULL) inside a transaction that raises `app.rls_bypass`.
201
+
202
+ **Groups (`0026_add_groups`, #728).** The `sharing` fragment owns `Group`, `GroupMember` and `GroupInvite` (tables `groups`, `group_members`, `group_invites`) and, from `0026_add_groups` to `0037_open_sharing_vocabularies`, the enum `GroupRole` (`admin`, `editor`, `viewer`; since `0037` the `role` columns are text, see below). A group is a set of users inside one organization, never a tenant. All three carry a NOT NULL `org_id` (foreign key `Cascade`), `ENABLE` and `FORCE ROW LEVEL SECURITY` and a `<table>_org_isolation` policy; a member and an invite reach their group through the composite `(group_id, org_id)` -> `groups (id, org_id)` (the target of `@@unique([id, orgId])`). `group_invites_pending_uniq_idx` is the one raw-SQL index. `Group` is `// @extensible`, so an app table owned by a group adds its back-relation with `extend model Group`. New tables, so no backfill.
203
+
204
+ **Grants (`0027_add_grants`, #729).** The `sharing` fragment also owns `Grant` (table `grants`) and, until `0037_open_sharing_vocabularies`, the enum `GrantGranteeKind` (`user`, `group`, `link`; since `0037` `grantee_kind` is text). A grant shares one record of an app's registered resource type, named polymorphically by `(resource_type, resource_id)` with no foreign key (the platform cannot know app tables; apps delete a record's grants in the same transaction and the `sharing.grants.prune` job catches the rest), with a role, an optional `expires_at` and a soft `revoked_at`. `org_id` is NOT NULL under a forced `grants_org_isolation` policy, and a group grantee reaches its group through the composite key `(grantee_group_id, org_id)`, so a grant cannot name another organization's group. The raw-SQL partial unique indexes `grants_active_user_uniq_idx` and `grants_active_group_uniq_idx` allow one active grant per resource and grantee, and the `CHECK` constraint `grants_grantee_consistency_check` keeps the grantee columns consistent with `grantee_kind` (a link grant has neither grantee and a `link_token_hash`). The link columns (`link_token_hash`, unique; `link_token_ciphertext`; `link_label`) are created now for #730.
205
+
206
+ **Open sharing vocabularies (`0037_open_sharing_vocabularies`, #967).** `group_members.role`, `group_invites.role` and `grants.grantee_kind` become `TEXT` (every stored value kept, both enums dropped, no CHECK on the roles: a row outlives the registry that wrote it), so an app adds a group role (`registerGroupRole`) or a persisted grantee kind (`registerGranteeKind({ persisted: true })`) with no migration. `grants` gains the nullable `grantee_ref` (the reference of an app kind, as the kind normalised it). `grants_grantee_consistency_check` is relaxed to the three built-in row shapes (each now also with `grantee_ref` NULL) OR a row of any other kind with a `grantee_ref` and none of `grantee_user_id`, `grantee_group_id`, `link_token_hash`; the new partial unique index `grants_active_ref_uniq_idx` allows one ACTIVE grant per `(resource_type, resource_id, grantee_kind, grantee_ref)` for those kinds (`RAW_SQL_INDEXES`). The two older partial indexes are rebuilt with a text predicate (`'user'::text`), which is why their `definition` in `raw-sql-indexes.json` changed. The migration runs in the `app.rls_bypass` transaction (RLS org tables).
207
+
208
+ **Organization settings (`0028_add_org_settings`, #733).** The `settings` fragment owns `OrgSettings` (table `org_settings`): one row per organization (`org_id` unique, foreign key to `organizations`, `Cascade`; `updated_by_user_id` `SetNull`) holding that organization's overrides of the org-overridable system settings namespaces, with a `version` of its own. NOT NULL `org_id`, `ENABLE` and `FORCE ROW LEVEL SECURITY` and the `org_settings_org_isolation` policy. A new table, so no backfill; `system_settings` and `user_settings` are unchanged.
209
+
210
+ **Jobs carry their organization (`0030_add_jobs_org_id`, `0031_add_jobs_org_id_status_index`, #734).** The `jobs` fragment's `Job` gains `orgId` (`jobs.org_id`): nullable, no default (a metadata-only `ADD COLUMN`), foreign key to `organizations` `ON DELETE SET NULL` (added `NOT VALID`, then validated), so deleting an organization keeps its job history. `NULL` is a deployment-wide (system) job, and every earlier row is one. The `(org_id, status)` index `jobs_org_id_status_idx` is built `CONCURRENTLY` in `0031`, the only statement of that migration (`jobs` is a big table). Deliberately no row-level security on `jobs` (the claim is one cross-organization statement), and `jobs_active_dedup_uniq_idx` is unchanged.
211
+
212
+ **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.
213
+
214
+ **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.
215
+
216
+ **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.
217
+
218
+ **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`.
219
+
220
+ **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.
221
+
222
+ **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):
223
+
224
+ - **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.
225
+ - **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.
226
+ - **`prisma/platform.lock`.** JSON, committed, keys sorted:
227
+ ```json
228
+ {
229
+ "lockVersion": 1,
230
+ "migrations": [
231
+ { "localDir": "20260124223146_initial", "originId": "platform:0001_initial", "sha256": "…", "since": "1.0.0" }
232
+ ],
233
+ "platformVersion": "1.0.0"
234
+ }
235
+ ```
236
+ `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.
237
+ - **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`.
238
+ - **`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`.
239
+ - **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.
240
+
241
+ ### Platform history v1
242
+
243
+ 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.
244
+
245
+ | Id | Reference app directory | Slice |
246
+ |---|---|---|
247
+ | `0001_initial` | `20260124223146_initial` | identity (touches settings, storage) |
248
+ | `0002_add_personal_access_tokens` | `20260329151231_add_personal_access_tokens` | identity |
249
+ | `0003_add_credentials` | `20260830211041_add_credentials` | credentials |
250
+ | `0004_add_notification_deliveries` | `20260831010356_add_notification_deliveries` | notifications |
251
+ | `0005_drop_stale_uuid_defaults` | `20260831014110_drop_stale_uuid_defaults` | identity (touches settings, storage) |
252
+ | `0006_add_notifications` | `20260831030721_add_notifications` | notifications |
253
+ | `0007_add_push_subscriptions` | `20260905182958_add_push_subscriptions` | notifications |
254
+ | `0008_add_jobs` | `20260906120000_add_jobs` | jobs |
255
+ | `0009_add_worker_nodes` | `20260906190000_add_worker_nodes` | jobs |
256
+ | `0010_add_database_backup_runs` | `20260907120000_add_database_backup_runs` | db-backup |
257
+ | `0011_add_notification_broadcasts` | `20260907130000_add_notification_broadcasts` | notifications |
258
+ | `0012_add_backup_run_job_link` | `20260907140000_add_backup_run_job_link` | db-backup (touches jobs) |
259
+ | `0013_add_job_node_secrets` | `20260907150000_add_job_node_secrets` | jobs |
260
+ | `0014_add_backup_run_pg_dump_version` | `20260907160000_add_backup_run_pg_dump_version` | db-backup |
261
+ | `0015_add_job_claim_token` | `20260908120000_add_job_claim_token` | jobs |
262
+ | `0016_add_ai_platform` | `20260926034919_add_ai_platform` | ai |
263
+ | `0017_revoke_viewer_ai_use` | `20260927000000_revoke_viewer_ai_use` | ai (touches identity) |
264
+ | `0018_add_user_credentials` | `20260927120000_add_user_credentials` | credentials |
265
+ | `0019_add_device_session_credential_link` | `20260927130000_add_device_session_credential_link` | identity |
266
+ | `0020_add_worker_node_vitals` | `20260928100000_add_worker_node_vitals` | jobs |
267
+ | `0021_add_job_trace_context` | `20260930120000_add_job_trace_context` | jobs |
268
+ | `0022_add_retention_created_at_indexes` | `20261006120000_add_retention_created_at_indexes` | notifications (touches ai) |
269
+
270
+ 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`.
271
+
272
+ ### Raw-SQL indexes
273
+
274
+ 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.
275
+
276
+ | Index | Table | Unique | Created in | Why | Design |
277
+ |---|---|---|---|---|---|
278
+ | `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) |
279
+ | `jobs_attempts_gt1_idx` | `jobs` | no | `0008_add_jobs` | retried jobs, for the queue insights report | [job-queue](../../docs/specs/job-queue.md) |
280
+ | `jobs_succeeded_duration_idx` | `jobs` | no | `0008_add_jobs` | finished succeeded jobs, for the duration percentiles | [job-queue](../../docs/specs/job-queue.md) |
281
+ | `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) |
282
+ | `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) |
283
+ | `group_invites_pending_uniq_idx` | `group_invites` | yes | `0026_add_groups` | at most one PENDING invite per group and address; a declined, revoked or accepted one does not block a re-invite | [platform-packages](../../docs/specs/platform-packages.md#tenancy-and-access-model) |
284
+ | `grants_active_user_uniq_idx` | `grants` | yes | `0027_add_grants` | at most one ACTIVE (unrevoked) grant per resource and user; the grants API upserts on it | [platform-packages](../../docs/specs/platform-packages.md#tenancy-and-access-model) |
285
+ | `grants_active_group_uniq_idx` | `grants` | yes | `0027_add_grants` | at most one ACTIVE grant per resource and group | [platform-packages](../../docs/specs/platform-packages.md#tenancy-and-access-model) |
286
+
287
+ `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
288
+
289
+ - a migration creates one that is not in `RAW_SQL_INDEXES`,
290
+ - a listed one is not created, or its table, uniqueness or `createdIn` disagrees,
291
+ - a schema fragment declares `@@unique`, `@@index` or `@unique` under a listed index's name or on its table and key columns.
292
+
293
+ An app's own raw-SQL indexes go in its `platform.lock` under `rawSqlIndexes`, as `{ "name", "definition" }` with the definition exactly as `pg_indexes.indexdef` prints it; the drift test asserts them too ([example lock entry](#app-tables-with-row-level-security)).
294
+
295
+ ### Row-level security policies
296
+
297
+ Prisma's schema language cannot express a policy either, and `prisma migrate diff` does not see one, so the tenant-isolation policies of `0025_org_scoped_rls`, `0026_add_groups`, `0027_add_grants` and `0028_add_org_settings` exist only in migration SQL, like the raw-SQL indexes. They are intentional drift too: never remove one to "fix" a diff.
298
+
299
+ | Policy | Table | Created in |
300
+ |---|---|---|
301
+ | `storage_objects_org_isolation` | `storage_objects` | `0025_org_scoped_rls` |
302
+ | `storage_object_chunks_org_isolation` | `storage_object_chunks` | `0025_org_scoped_rls` |
303
+ | `ai_runs_org_isolation` | `ai_runs` | `0025_org_scoped_rls` |
304
+ | `ai_usage_events_org_isolation` | `ai_usage_events` | `0025_org_scoped_rls` |
305
+ | `groups_org_isolation` | `groups` | `0026_add_groups` |
306
+ | `group_members_org_isolation` | `group_members` | `0026_add_groups` |
307
+ | `group_invites_org_isolation` | `group_invites` | `0026_add_groups` |
308
+ | `grants_org_isolation` | `grants` | `0027_add_grants` |
309
+ | `org_settings_org_isolation` | `org_settings` | `0028_add_org_settings` |
310
+
311
+ `rls-policies.json` is the one list (`name`, `table`, `reason`, `doc`, `createdIn`), exported as `RLS_POLICIES` beside `RAW_SQL_INDEXES`. `platform db drift` reads `pg_policies` and `pg_class` and reports `POLICY_MISSING` (a listed policy is not in the database), `POLICY_UNLISTED` (the database has one nobody listed), `RLS_NOT_ENABLED`, `RLS_NOT_FORCED` (the table does not `FORCE` it, so the owner, which is the application role, bypasses the policy) and `RLS_FORCED_WITHOUT_POLICY` (everything would be denied). `assertRlsPolicies` is the offline tripwire (`runDbConformance` runs it as `rls-policies`): it scans the manifest migrations and fails on `UNLISTED_POLICY`, `LISTED_POLICY_NOT_FOUND`, `LISTED_POLICY_MISMATCH` (`createdIn` disagrees) and a policy whose table the migrations never `ENABLE` / `FORCE`. The policy text and the settings it reads (`app.org_id`, `app.user_id`, `app.rls_bypass`, always `set_config(..., true)`) are specified in [SECURITY-ARCHITECTURE.md §18](../../docs/SECURITY-ARCHITECTURE.md#18-tenant-isolation-rls); the clients that set them are `PrismaService.forOrg` / `runInOrg` and `PrismaSystemService` in the reference app, built on the row-level-security helpers of `@marinoscar/platform-api/core` ([core README](../platform-api/src/core/README.md)).
312
+
313
+ A migration that enables row-level security carries `"rls": true` in the manifest (`platform db promote --rls`), and, because it changes what a connection can see, a partial `platform db baseline` that stops before it does so deliberately: a baseline through or past it needs `--allow-rls`, which is the operator's statement that the application role is already `NOSUPERUSER NOBYPASSRLS` (error `RLS_OPT_IN_REQUIRED` otherwise). `--touches <slices>` on promote records the other slices' tables a migration changes (`0025` touches `ai` and `identity` from the `storage` slice), so a baseline of a subset of slices can tell.
314
+
315
+ ### App schema objects, offline
316
+
317
+ `platform db drift` asserts an app's own `rawSqlIndexes` and `rlsPolicies` (from `platform.lock`) against a live database. The same lists are also checked **offline**, against the migration SQL, by `runDbConformance` (test `app-schema-objects`, function `checkAppSchemaObjects` / `assertAppSchemaObjects`), so a typo or a forgotten migration fails the app's unit tests instead of the `smoke` job. It scans the app's whole `prisma/migrations` history in directory order (installed platform migrations included, so a later app migration that drops or rewrites something is seen) and fails when
318
+
319
+ - a listed index or policy is created by no migration, or dropped by a later one (`APP_INDEX_NOT_FOUND`, `APP_POLICY_NOT_FOUND`),
320
+ - a listed index's `definition` states another table, uniqueness or key columns than the migrations leave (`APP_INDEX_MISMATCH`),
321
+ - a listed policy carries `usingSha256` or `checkSha256` and the migrations leave a different expression (`APP_POLICY_EXPRESSION_MISMATCH`): a policy weakened by a later `ALTER POLICY` or re-created with another body is caught without a database. The hash is the SHA-256 of the expression after `normaliseSqlExpression` (whitespace collapsed, case folded outside quotes, spaces inside parentheses and around commas dropped); `platform db policies` prints it. Both hashes are optional, so an existing lock entry keeps working,
322
+ - a listed policy's table does not both `ENABLE` and `FORCE ROW LEVEL SECURITY` (`APP_POLICY_TABLE_NOT_ENABLED`, `APP_POLICY_TABLE_NOT_FORCED`),
323
+ - the migrations leave a partial or expression index, or a policy, that neither the package's lists nor the lock lists (`UNLISTED_APP_RAW_INDEX`, `UNLISTED_APP_POLICY`): the lock is the app's allow-list, as `raw-sql-indexes.json` and `rls-policies.json` are the package's.
324
+
325
+ The package's own entries are never judged here (the package tripwires do that) and need nothing in the lock. An app upgrading to this check lists any index or policy it already has in its lock first; `platform db policies` prints the policy entries.
326
+
327
+ ### App migrations and the installed history
328
+
329
+ `platform db sync` and `platform db check` (and the `app-migrations` conformance test) compare the app-authored directories of `prisma/migrations` (those no `platform.lock` entry names) with the installed platform history, and refuse:
330
+
331
+ - **`APP_MIGRATION_ID_COLLISION`**: an app directory named exactly like a package migration (`0036_add_app_metadata`). The history could not tell the two apart.
332
+ - **`APP_MIGRATION_OUT_OF_ORDER`**: an app directory that sorts before the last installed platform migration but was not there at the last `sync`. `sync` installs a platform migration under a timestamp later than everything in the history, so an app migration that existed then sorts before it by design (an app's `add_notes` between two platform migrations is normal). One that appears afterwards with an older timestamp (a branch started before the sync, merged after) would run, on a fresh database, before platform migrations other databases applied first. The lock remembers the app directories present at the last sync in `appMigrations` (`sync` and `promote` write it); a lock without the field skips this rule until its next sync.
333
+
334
+ `sync` throws `APP_MIGRATION_COLLISION` and installs nothing while either exists. The fix is a rename of a migration that was never applied (a timestamp after the last installed one), or, for one that was applied, `platform db sync` once it is the only reason the check fails.
335
+
336
+ ### App tables with row-level security
337
+
338
+ An app table that carries `org_id` is isolated the way the platform's `org` tables are, and the app declares it in two places that `platform db drift` reads: the migration that creates the policy, and `rlsPolicies` in `platform.lock`. Prisma cannot express the policy, so it is intentional drift in the app too: never "fix" it with a schema change.
339
+
340
+ 1. **The model.** In the app's fragment, a NOT NULL `orgId` with a `Cascade` relation to `Organization`, and the back-relation as `extend model Organization { workouts Workout[] }` (`Organization` is `// @extensible`). A link to another org-owned table is a composite foreign key that includes `org_id` (`@relation(fields: [parentId, orgId], references: [id, orgId])`, with `@@unique([id, orgId])` on the parent), because a foreign-key check runs without row-level security.
341
+ 2. **The migration.** `prisma migrate dev --create-only`, then append the three statements to the generated SQL. The policy is the platform's own (copy it unchanged, only the names differ):
342
+
343
+ ```sql
344
+ ALTER TABLE "workouts" ENABLE ROW LEVEL SECURITY;
345
+ ALTER TABLE "workouts" FORCE ROW LEVEL SECURITY;
346
+ CREATE POLICY "workouts_org_isolation" ON "workouts"
347
+ USING ("org_id" = NULLIF(current_setting('app.org_id', true), '')::uuid
348
+ OR current_setting('app.rls_bypass', true) = 'on')
349
+ WITH CHECK ("org_id" = NULLIF(current_setting('app.org_id', true), '')::uuid
350
+ OR current_setting('app.rls_bypass', true) = 'on');
351
+ ```
352
+
353
+ A migration that reads or writes rows of an org table (a backfill, a data fix) wraps its statements, because under `FORCE` an unscoped statement silently affects zero rows:
354
+
355
+ ```sql
356
+ BEGIN;
357
+ SELECT set_config('app.rls_bypass', 'on', true);
358
+ -- the backfill, the policy statements above
359
+ COMMIT;
360
+ ```
361
+
362
+ The setting is always `set_config(..., true)` (transaction-local), never a session-level `SET`. Creating a new, empty table needs no bypass; the wrapper is harmless there.
363
+ 3. **The lock.** List the policy in the app's `prisma/platform.lock` (the file is JSON; `rlsPolicies` and `rawSqlIndexes` are optional keys, and `platform db sync` and `baseline` carry them through unchanged):
364
+
365
+ ```json
366
+ {
367
+ "lockVersion": 1,
368
+ "platformVersion": "0.1.0",
369
+ "migrations": [],
370
+ "rawSqlIndexes": [
371
+ { "name": "workouts_active_uniq_idx", "definition": "CREATE UNIQUE INDEX workouts_active_uniq_idx ON public.workouts USING btree (org_id, slug) WHERE (archived_at IS NULL)" }
372
+ ],
373
+ "rlsPolicies": [
374
+ { "name": "workouts_org_isolation", "table": "workouts" }
375
+ ]
376
+ }
377
+ ```
378
+
379
+ An entry is exactly `name` and `table` (the lock refuses another key). It is the app's statement that the policy is intentional.
380
+ 4. **Check it.** `platform db drift` diffs the replayed migrations against the schema in a shadow database, then asserts in the migrated database it is given (`DATABASE_URL`) each listed policy in `pg_policies` and that its table has row-level security enabled **and** forced. It reports `POLICY_MISSING`, `RLS_NOT_ENABLED` and `RLS_NOT_FORCED` for a listed policy that is not (fully) in place, `POLICY_UNLISTED` for a policy in the database that neither list names, and `RLS_FORCED_WITHOUT_POLICY` for a forced table no listed policy protects. Today the check is against a live database only; `runDbConformance` and `assertRlsPolicies` still read the package's list, not the lock's.
381
+
382
+ The application role must be an ordinary role that owns the tables (`NOSUPERUSER NOBYPASSRLS`); a superuser ignores every policy. The runtime clients (`PrismaService.forOrg` / `runInOrg`) and the model-ownership registration an `org` model needs are in the reference app's [ownership README](../../apps/api/src/prisma/ownership/README.md); the step-by-step recipe is [EXTENDING.md](../../docs/EXTENDING.md#add-an-rls-protected-app-table).
383
+
384
+ 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`).
385
+
386
+ ### App metadata on users and organizations
387
+
388
+ `users.metadata` and `organizations.metadata` (migration `0036_add_app_metadata`) are `JSONB NOT NULL DEFAULT '{}'` documents the **app** fills, one top-level key per namespace it registers (`registerUserMetadataSchema`, `registerOrganizationMetadataSchema` of `@marinoscar/platform-api/identity`). They are the sanctioned place for a per-user or per-organization app field, so an app does not add a column to a package-owned table or a side table for a handful of settings. Neither table has row-level security.
389
+
390
+ - Not a secret store: the API refuses secret-named fields and keys, and nothing encrypts the document (it travels in backups and exports).
391
+ - 16 KiB per row, enforced by the writer; a CHECK (`users_metadata_size_check`, `organizations_metadata_size_check`: a JSON object, at most 32 KiB of `jsonb` text) backs it whoever writes.
392
+ - Never returned by a platform route. Details and the recipe: the [identity README](../platform-api/src/identity/README.md#app-metadata-on-users-and-organizations).
393
+
394
+ ## Permissions and settings
395
+
396
+ 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.
397
+
398
+ ## UI
399
+
400
+ None. The package renders nothing.
401
+
402
+ ## Infra
403
+
404
+ 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`.
405
+
406
+ ## Observability
407
+
408
+ None. The package emits nothing at run time.
409
+
410
+ ## Security notes
411
+
412
+ 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).
413
+
414
+ **Row-level security is only as strong as the role.** A superuser or `BYPASSRLS` role ignores every policy (`FORCE` included), so the policies protect nothing for an app that connects as one; the reference app's Doctor check `db.rls_role` fails in that case. A migration that backfills an RLS table runs as system work in an explicit transaction that sets `app.rls_bypass` (`BEGIN; SELECT set_config('app.rls_bypass', 'on', true); ... COMMIT;`), or the statement silently changes zero rows. 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).
415
+
416
+ ## Conformance suite
417
+
418
+ `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:
419
+
420
+ | Test | Fails when |
421
+ |---|---|
422
+ | `raw-sql-indexes` | the raw-SQL index tripwire above is tripped |
423
+ | `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`) |
424
+ | `rls-policies` | the policy tripwire above is tripped |
425
+ | `app-schema-objects` | a raw-SQL index or policy listed in the lock is created by no migration (or dropped later), a listed policy's expression hash differs from the SQL, or an unlisted partial or expression index or policy exists ([App schema objects, offline](#app-schema-objects-offline)) |
426
+ | `app-migrations` | an app-authored migration directory is named like a package migration or would reorder the installed history ([App migrations and the installed history](#app-migrations-and-the-installed-history)) |
427
+
428
+ ```ts
429
+ // apps/api/test/prisma/platform-db-conformance.spec.ts
430
+ import { runDbConformance } from '@marinoscar/platform-db';
431
+ runDbConformance({ appRoot: join(__dirname, '..', '..') });
432
+ ```
433
+
434
+ 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.
435
+
436
+ ## Upgrade notes
437
+
438
+ 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.
439
+
440
+ 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`.
441
+
442
+ `platform db baseline` is a dry run unless `--apply` is given, and a dry run writes nothing and runs no `prisma migrate resolve`:
443
+
444
+ | Step | What it does |
445
+ |---|---|
446
+ | 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 |
447
+ | 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 |
448
+ | 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 |
449
+ | 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 |
450
+ | 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 |
451
+ | B6 verify | `prisma migrate status`, `platform db check` and the ledger comparison |
452
+
453
+ `--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.
454
+
455
+ 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.
456
+
457
+ ## Troubleshooting
458
+
459
+ 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`.
460
+
461
+ | Symptom | Cause | Fix |
462
+ |---|---|---|
463
+ | `platform: @marinoscar/platform-db is not built` | The `platform` command runs `dist/` | `npm run build:packages` from the repository root |
464
+ | `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 |
465
+ | `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/` |
466
+ | 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 |
467
+ | `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 |
468
+ | `UNKNOWN_MODEL` | No fragment declares the model | Check the spelling; the model must exist in a platform or app fragment |
469
+ | `FIELD_COLLISION` | The field name already exists on the model or in an earlier `extend` | Rename the back-relation field |
470
+ | `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 |
471
+ | `EXTEND_UNKNOWN_TYPE` | The field's type is no model | Declare the model in a fragment |
472
+ | `DUPLICATE_MODEL` | A model or enum is declared in two fragments | Declare it once; add relations to a platform model with `extend model` |
473
+ | `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) |
474
+ | `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 |
475
+ | `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 |
476
+ | `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 |
477
+ | `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 |
478
+ | `Could not find Prisma Schema` | `prisma.config.ts` has no `schema` | Set `schema: 'prisma/schema'` |
479
+ | `No migration found in prisma/migrations` | `migrations.path` missing: with a schema folder the default becomes `<schema folder>/migrations` | Set `migrations: { path: 'prisma/migrations' }` |
480
+
481
+ 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:
482
+
483
+ | Code | Meaning | Fix |
484
+ |---|---|---|
485
+ | `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 |
486
+ | `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 |
487
+ | `PACKAGE_FILE_MODIFIED` | The package's `migration.sql` differs from its manifest hash, or is missing | Restore the file, or reinstall the package |
488
+ | `NOT_INSTALLED` | A package migration is not in the lock | Run `npm run db:sync` |
489
+ | `LOCAL_DIR_MISSING` | A directory the lock names does not exist | Restore it from Git; do not rename installed directories |
490
+ | `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 |
491
+ | `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 |
492
+ | `LEDGER_CHECKSUM_MISMATCH` (`--database`) | A file was edited after the database applied it | Restore the file; the database keeps the original checksum |
493
+ | `LEDGER_UNFINISHED` (`--database`) | A row of `_prisma_migrations` never finished | `prisma migrate resolve --rolled-back <dir>` or `--applied <dir>`, after checking the database |
494
+
495
+ `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).
496
+
497
+ `platform db baseline` refuses with a code, and prints the report first ([the runbook](../../docs/runbooks/database-baseline.md) has the fix for each):
498
+
499
+ | Code | Meaning | Fix |
500
+ |---|---|---|
501
+ | `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) |
502
+ | `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 |
503
+ | `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` |
504
+ | `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 |
505
+ | `LOCK_NOT_EMPTY` | `platform.lock` already has entries | `--force-remap`, after reading the dry run |
506
+ | `PLACEMENT_IMPOSSIBLE` | The directories cannot sort in package order | Rename an app directory the database has not applied, or re-map |
507
+ | `MAP_INVALID` | `--map` is not valid, or names a directory another migration already matches exactly | Fix the file |
508
+ | `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 |
509
+ | `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 |
510
+
511
+ `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.
512
+
513
+ `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.
514
+
515
+ ## Links
516
+
517
+ - [Platform packages spec](../../docs/specs/platform-packages.md): the extension contract and the package documentation standard
518
+ - [ADR 0002](../../docs/adr/0002-database-packaging-and-rls.md): the fragment layout, the `extend model` syntax and the rule table (D1, D2)
519
+
520
+ - [ADR 0002](../../docs/adr/0002-database-packaging-and-rls.md): why migrations are installed with app-local timestamps and a lock (D3)
521
+ - [Authoring a platform migration](../../docs/DEVELOPMENT.md#authoring-a-platform-migration): `migrate dev --create-only`, `promote`, and the one-open-`pp:migration`-PR rule
522
+ - [`seed` slice README](src/seed/README.md): `seedPlatform`, input building, the never-delete rule and the app seed hook
523
+ - [Package documentation standard and checks](../../docs/PACKAGES.md): how this README, the TSDoc and the catalog are checked
524
+ - [DEVELOPMENT.md § Making Database Changes](../../docs/DEVELOPMENT.md#making-database-changes): the schema editing workflow
525
+ - [DEVELOPMENT.md § Platform packages](../../docs/DEVELOPMENT.md#platform-packages): build, test and lint commands
2
526
 
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
+ );