Skip to content

Commit c99a446

Browse files
authored
docs(den-db): document and verify Den database upgrades (#7670)
Signed-off-by: Jalil <reachjalil@gmail.com>
1 parent 3dd9ba5 commit c99a446

2 files changed

Lines changed: 84 additions & 53 deletions

File tree

‎ee/packages/den-db/README.md‎

Lines changed: 47 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -9,46 +9,55 @@
99
- Always generate new migrations with Drizzle from this package.
1010
- Do not create migrations from `den-api`, `den-controller`, or other apps.
1111

12-
## Commands
13-
14-
Generate a migration after editing the schema:
15-
16-
```bash
17-
pnpm --dir ee/packages/den-db db:generate
18-
```
19-
20-
Apply schema directly to a development database:
21-
22-
```bash
23-
pnpm --dir ee/packages/den-db db:push
24-
```
25-
26-
Run Drizzle migrations against a configured database:
27-
28-
```bash
29-
pnpm --dir ee/packages/den-db db:migrate
12+
## Install or upgrade Den
13+
14+
| Database and starting state | What to run | What happens |
15+
| --- | --- | --- |
16+
| Local MySQL | Run `pnpm dev:web-local`. To inspect first, set a loopback `DATABASE_URL` and run `pnpm --dir ee/packages/den-db db:migrate:local --check`. | On first startup, the runner replays from the historical foundation. On upgrade, it checks the schema and journal before applying pending SQL. It runs repairs and verifies the final schema and receipts before services start. Stop other connections before applying. See [local startup safety](#local-startup-safety). |
17+
| Hosted PlanetScale | The [Den DB Migrate workflow](../../../.github/workflows/den-db-migrate.yml) runs on selected pushes to `dev`, on a schedule, or by manual dispatch. | On the existing production branch it opens a DDL window for pending migrations, runs `db:migrate`, and restores safe migrations. Check the workflow result for confirmation that safe migrations were re-enabled. |
18+
| Self-hosted Den, empty database | Run the release image's migration job before starting Den. It executes `node /app/ee/packages/den-db/dist/scripts/bootstrap.js`. | Bootstrap installs the image's current-schema snapshot and records the bundled migration history as its baseline. The historical chain starts by altering existing tables. |
19+
| Self-hosted Den, existing database | Run the same migration job from the **new** release before rolling out its services. For a pending 0097, follow the [0097 upgrade preconditions](#production-0097-upgrade-preconditions) first. | Bootstrap checks recorded history and applies pending migrations. An existing schema without a journal or with an unknown history needs deliberate recovery. Inspect an interrupted migration before retrying. |
20+
21+
Hosted `db:migrate` applies journaled SQL, runs schema repairs, then reconciles
22+
default permission sets. The workflow also runs reconciliation separately so
23+
permission catalog changes take effect even when there is no pending migration.
24+
25+
The self-hosted job runs schema repairs and attempts permission reconciliation
26+
on fresh installs as well as upgrades. Reconciliation fills missing default
27+
Member and Admin permission rows and is idempotent. Bootstrap logs a
28+
reconciliation failure and continues. If it reports one, correct the cause and
29+
rerun `pnpm --dir ee/packages/den-db db:reconcile-permissions` with the same
30+
database configuration from a source checkout. The local migration runner
31+
handles schema and receipts only.
32+
33+
## Development commands
34+
35+
- Generate SQL after a schema edit with `pnpm --dir ee/packages/den-db db:generate`.
36+
- Apply the guarded local upgrade directly with `pnpm --dir ee/packages/den-db db:migrate:local` and a loopback `DATABASE_URL`.
37+
- Use `pnpm --dir ee/packages/den-db db:push` only on a disposable development database. Direct schema pushes do not record the migration history used by upgrades.
38+
- To run self-hosted bootstrap from a source checkout, build the workspace dependencies with `pnpm --filter '@openwork-ee/den-db^...' --if-present run build`, then run `pnpm --dir ee/packages/den-db db:bootstrap` against the intended database.
39+
40+
## Verify installs and upgrades locally
41+
42+
The [MySQL fixture](test/migration-preserved-tables.mysql.test.ts) uses Linux
43+
MySQL 8.4 with case-sensitive table names (`lower_case_table_names=0`).
44+
Set `OPENWORK_MIGRATION_TEST_MYSQL_URL` to a disposable loopback MySQL URL
45+
whose database name begins with `exp_`. The fixture account needs permission
46+
to create and drop temporary databases on that server. The test skips if the
47+
variable is absent.
48+
49+
Run from the repository root with workspace dependencies installed.
50+
51+
```sh
52+
pnpm --filter '@openwork-ee/den-db...' --if-present run build
53+
pnpm --dir ee/packages/den-db exec node --conditions=development --import tsx --test test/migration-preserved-tables.mysql.test.ts
3054
```
3155

32-
Install or upgrade a production database, including empty first installs:
33-
34-
```bash
35-
pnpm --dir ee/packages/den-db db:bootstrap
36-
```
37-
38-
Containerized production installs run the precompiled artifact directly:
39-
40-
```bash
41-
node /app/ee/packages/den-db/dist/scripts/bootstrap.js
42-
```
43-
44-
`db:migrate`, `db:push` and `bootstrap.js` finish by reconciling default
45-
permission sets: catalog permissions that are new since a Member or Admin set
46-
was created get a row (`source = 'reconcile'`). It is idempotent and needs no
47-
migration file, so the Den DB Migrate workflow also runs it on its own:
48-
49-
```bash
50-
pnpm --dir ee/packages/den-db db:reconcile-permissions
51-
```
56+
Historical replay preserves the legacy dashboard and access-grant tables.
57+
A fresh install from the packaged snapshot omits both. The fixture checks
58+
both fresh layouts. For upgrades it seeds a dashboard and its access grant
59+
at migration 0147, runs the local and packaged upgrade paths on separate
60+
databases, and checks the rows and ordered migration receipts again at restart.
5261

5362
## Production 0097 upgrade preconditions
5463

‎ee/packages/den-db/test/migration-preserved-tables.mysql.test.ts‎

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,34 @@ test("preserved-table startup on disposable MySQL", { skip: !databaseUrl, timeou
4848
async function receipts(executor: Executor) {
4949
return executor.query(`SELECT hash, created_at FROM \`${journalTable}\` ORDER BY id`)
5050
}
51+
async function seedDashboard(executor: Executor) {
52+
await executor.query("INSERT INTO dashboard (id, organization_id, name, elements_json, created_by_org_membership_id) VALUES ('preserve', 'fixture', 'original', JSON_ARRAY(), 'fixture')")
53+
await executor.query("INSERT INTO dashboard_access_grant (id, organization_id, dashboard_id, role, created_by_org_membership_id) VALUES ('preserve', 'fixture', 'preserve', 'viewer', 'fixture')")
54+
}
55+
async function assertDashboardPreserved(executor: Executor) {
56+
assert.equal((await executor.query("SELECT name FROM dashboard WHERE id='preserve'"))[0]?.name, "original")
57+
assert.equal((await executor.query("SELECT role FROM dashboard_access_grant WHERE id='preserve'"))[0]?.role, "viewer")
58+
}
59+
async function verifySeededUpgrade(executor: Executor, upgrade: () => Promise<void>) {
60+
await replay(executor, 147)
61+
await seedDashboard(executor)
62+
await upgrade()
63+
const upgraded = await receipts(executor)
64+
assert.equal(historyPrefix(plan, upgraded), plan.length)
65+
await assertDashboardPreserved(executor)
66+
await upgrade()
67+
await migrateLocalDatabase(executor, plan, true)
68+
assert.deepEqual(await receipts(executor), upgraded)
69+
await assertDashboardPreserved(executor)
70+
}
71+
async function runBootstrap(url: string) {
72+
try {
73+
await run(process.execPath, [new URL("../dist/scripts/bootstrap.js", import.meta.url).pathname], {
74+
env: { ...process.env, DATABASE_URL: url, DEN_DB_ENCRYPTION_KEY: "disposable-migration-test-key-1234567890", DEN_DB_PERMISSION_RECONCILIATION: "0" },
75+
timeout: 90_000,
76+
})
77+
} catch { assert.fail("Compiled bootstrap failed (driver output withheld); build den-db and its workspace dependencies before this test") }
78+
}
5179
try {
5280
const [server] = await admin.query<mysql.RowDataPacket[]>("SELECT VERSION() AS version, @@version_compile_os AS os, @@lower_case_table_names AS case_mode")
5381
assert.match(String(server[0]?.version), /^8\.4\./)
@@ -63,20 +91,19 @@ test("preserved-table startup on disposable MySQL", { skip: !databaseUrl, timeou
6391
const { shape } = await inspectSchema(executor)
6492
assert.ok(shape.has("table:dashboard"))
6593
assert.ok(shape.has("table:dashboard_access_grant"))
66-
await executor.query("INSERT INTO dashboard (id, organization_id, name, elements_json, created_by_org_membership_id) VALUES ('preserve', 'fixture', 'original', JSON_ARRAY(), 'fixture')")
67-
await executor.query("INSERT INTO dashboard_access_grant (id, organization_id, dashboard_id, role, created_by_org_membership_id) VALUES ('preserve', 'fixture', 'preserve', 'viewer', 'fixture')")
94+
await seedDashboard(executor)
6895
await migrateLocalDatabase(executor, plan, true)
6996
assert.deepEqual(await receipts(executor), before)
70-
assert.equal((await executor.query("SELECT name FROM dashboard WHERE id='preserve'"))[0]?.name, "original")
71-
assert.equal((await executor.query("SELECT role FROM dashboard_access_grant WHERE id='preserve'"))[0]?.role, "viewer")
97+
await assertDashboardPreserved(executor)
7298
t.diagnostic(`fresh replay + checked restart: ${before.length} exact receipts; both preserved rows unchanged; interruption marker empty`)
7399
}))
74100

75-
await t.test("a recorded 0147 replay upgrades and remains checked-startup compatible", async () => database(async (executor) => {
76-
await replay(executor, 147)
77-
await migrateLocalDatabase(executor, plan)
78-
await migrateLocalDatabase(executor, plan, true)
79-
assert.equal(historyPrefix(plan, await receipts(executor)), plan.length)
101+
await t.test("a seeded 0147 database survives the local upgrade and restart", async () => database(async (executor) => {
102+
await verifySeededUpgrade(executor, () => migrateLocalDatabase(executor, plan))
103+
}))
104+
105+
await t.test("a seeded 0147 database survives packaged bootstrap and restart", async () => database(async (executor, url) => {
106+
await verifySeededUpgrade(executor, () => runBootstrap(url))
80107
}))
81108

82109
await t.test("fresh replay cannot silently switch to bootstrap if both preserved tables disappear before final verification", async () => database(async (_quarantine, quarantineUrl) => database(async (executor) => {
@@ -97,12 +124,7 @@ test("preserved-table startup on disposable MySQL", { skip: !databaseUrl, timeou
97124
})))
98125

99126
await t.test("the authentic compiled current-schema bootstrap without either table still checks", async () => database(async (executor, url) => {
100-
try {
101-
await run(process.execPath, [new URL("../dist/scripts/bootstrap.js", import.meta.url).pathname], {
102-
env: { ...process.env, DATABASE_URL: url, DEN_DB_ENCRYPTION_KEY: "disposable-migration-test-key-1234567890", DEN_DB_PERMISSION_RECONCILIATION: "0" },
103-
timeout: 90_000,
104-
})
105-
} catch { assert.fail("Compiled bootstrap failed (driver output withheld); build den-db before this test") }
127+
await runBootstrap(url)
106128
const { shape } = await inspectSchema(executor)
107129
assert.equal(shape.has("table:dashboard"), false)
108130
assert.equal(shape.has("table:dashboard_access_grant"), false)

0 commit comments

Comments
 (0)