database-migration.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { describe, expect, test } from "bun:test"
  2. import { $ } from "bun"
  3. import { fileURLToPath } from "url"
  4. import path from "path"
  5. import { SqliteClient } from "@effect/sql-sqlite-bun"
  6. import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite"
  7. import { Effect, Layer } from "effect"
  8. import { sql } from "drizzle-orm"
  9. import { DatabaseMigration } from "@opencode-ai/core/database/migration"
  10. import { migrations } from "@opencode-ai/core/database/migration.gen"
  11. import { Database } from "@opencode-ai/core/database/database"
  12. import { tmpdir } from "./fixture/tmpdir"
  13. import type { SqlClient } from "effect/unstable/sql/SqlClient"
  14. import { importLegacyCredentials } from "@opencode-ai/core/database/migration/20260805200742_import_legacy_credentials"
  15. const run = <A, E>(effect: Effect.Effect<A, E, SqlClient>) =>
  16. Effect.runPromise(
  17. effect.pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Effect.scoped),
  18. )
  19. const makeDb = EffectDrizzleSqlite.makeWithDefaults()
  20. describe("DatabaseMigration", () => {
  21. test("serializes concurrent embedded initialization for one database path", async () => {
  22. await using tmp = await tmpdir()
  23. const filename = path.join(tmp.path, "embedded.sqlite")
  24. await Effect.runPromise(
  25. Effect.all(
  26. [Database.layer({ path: filename }), Database.layer({ path: filename })].map((layer) =>
  27. Effect.scoped(Layer.build(layer)),
  28. ),
  29. { concurrency: "unbounded" },
  30. ),
  31. )
  32. })
  33. if (process.platform === "linux") {
  34. test("declared schema has no ungenerated migrations", async () => {
  35. const result = await $`bun ${fileURLToPath(new URL("../script/migration.ts", import.meta.url))} --check`
  36. .quiet()
  37. .nothrow()
  38. expect(result.exitCode, result.stderr.toString()).toBe(0)
  39. expect(result.stdout.toString()).toContain("No schema changes, nothing to migrate")
  40. }, 30_000)
  41. }
  42. test("bootstraps the current schema and records the migration registry", async () => {
  43. await run(
  44. Effect.gen(function* () {
  45. const db = yield* makeDb
  46. yield* DatabaseMigration.apply(db)
  47. expect(yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_v2'`)).toEqual(
  48. {
  49. name: "session_v2",
  50. },
  51. )
  52. expect(
  53. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_pending'`),
  54. ).toEqual({ name: "session_pending" })
  55. expect(yield* db.get(sql`SELECT count(*) AS count FROM migration`)).toEqual({ count: migrations.length })
  56. }),
  57. )
  58. })
  59. test("rejects a non-empty database without a session table", async () => {
  60. await expect(
  61. run(
  62. Effect.gen(function* () {
  63. const db = yield* makeDb
  64. yield* db.run(sql`CREATE TABLE unrelated (id text PRIMARY KEY)`)
  65. yield* DatabaseMigration.apply(db)
  66. }),
  67. ),
  68. ).rejects.toThrow("Database is not empty and has no session table")
  69. })
  70. test("applies generic migrations once and records their order", async () => {
  71. await run(
  72. Effect.gen(function* () {
  73. const db = yield* makeDb
  74. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY)`)
  75. const input = [
  76. {
  77. id: "first",
  78. up: (tx: Parameters<Parameters<typeof db.transaction>[0]>[0]) =>
  79. tx.run(sql`CREATE TABLE applied (id text PRIMARY KEY)`),
  80. },
  81. {
  82. id: "second",
  83. up: (tx: Parameters<Parameters<typeof db.transaction>[0]>[0]) =>
  84. tx.run(sql`INSERT INTO applied (id) VALUES ('second')`),
  85. },
  86. ]
  87. yield* DatabaseMigration.applyOnly(db, input)
  88. yield* DatabaseMigration.applyOnly(db, input)
  89. expect(yield* db.all(sql`SELECT id FROM applied`)).toEqual([{ id: "second" }])
  90. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY time_completed, id`)).toEqual([
  91. { id: "first" },
  92. { id: "second" },
  93. ])
  94. }),
  95. )
  96. })
  97. test("imports legacy JSON credentials without changing the source file or existing credentials", async () => {
  98. await using tmp = await tmpdir()
  99. const source = path.join(tmp.path, "auth.json")
  100. const content = JSON.stringify({
  101. openai: { type: "oauth", refresh: "refresh", access: "access", expires: 123, accountId: "account" },
  102. anthropic: { type: "api", key: "legacy-key", metadata: { region: "us" } },
  103. "https://example.com/": { type: "wellknown", key: "TOKEN", token: "wellknown-key" },
  104. invalid: { type: "unknown" },
  105. })
  106. await Bun.write(source, content)
  107. await run(
  108. Effect.gen(function* () {
  109. const db = yield* makeDb
  110. yield* DatabaseMigration.apply(db)
  111. const now = Date.now()
  112. yield* db.run(sql`
  113. INSERT INTO credential (id, integration_id, label, value, time_created, time_updated)
  114. VALUES ('existing', 'anthropic', 'Existing', ${JSON.stringify({ type: "key", key: "current-key" })}, ${now}, ${now})
  115. `)
  116. yield* db.transaction((tx) => importLegacyCredentials(tx, source))
  117. expect(yield* db.all(sql`SELECT integration_id, label, value FROM credential ORDER BY integration_id`)).toEqual(
  118. [
  119. {
  120. integration_id: "anthropic",
  121. label: "Existing",
  122. value: JSON.stringify({ type: "key", key: "current-key" }),
  123. },
  124. {
  125. integration_id: "https://example.com",
  126. label: "default",
  127. value: JSON.stringify({ type: "key", key: "wellknown-key" }),
  128. },
  129. {
  130. integration_id: "openai",
  131. label: "default",
  132. value: JSON.stringify({
  133. type: "oauth",
  134. methodID: "chatgpt-browser",
  135. refresh: "refresh",
  136. access: "access",
  137. expires: 123,
  138. metadata: { accountID: "account" },
  139. }),
  140. },
  141. ],
  142. )
  143. expect(yield* db.get(sql`SELECT value FROM kv WHERE key = 'wellknown:sources'`)).toEqual({
  144. value: JSON.stringify(["https://example.com"]),
  145. })
  146. }),
  147. )
  148. expect(await Bun.file(source).text()).toBe(content)
  149. })
  150. test("rolls back a failed migration without recording it", async () => {
  151. await run(
  152. Effect.gen(function* () {
  153. const db = yield* makeDb
  154. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY)`)
  155. const migration = {
  156. id: "failing",
  157. up: (tx: Parameters<Parameters<typeof db.transaction>[0]>[0]) =>
  158. Effect.gen(function* () {
  159. yield* tx.run(sql`CREATE TABLE rolled_back (id text PRIMARY KEY)`)
  160. yield* Effect.fail(new Error("stop"))
  161. }),
  162. }
  163. expect((yield* Effect.exit(DatabaseMigration.applyOnly(db, [migration])))._tag).toBe("Failure")
  164. expect(
  165. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'rolled_back'`),
  166. ).toBeUndefined()
  167. expect(yield* db.get(sql`SELECT id FROM migration WHERE id = 'failing'`)).toBeUndefined()
  168. }),
  169. )
  170. })
  171. test("suspends foreign keys outside migrations that rebuild referenced tables", async () => {
  172. await run(
  173. Effect.gen(function* () {
  174. const db = yield* makeDb
  175. yield* db.run(sql`PRAGMA foreign_keys = ON`)
  176. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, title text NOT NULL)`)
  177. yield* db.run(
  178. sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL REFERENCES session(id) ON DELETE CASCADE)`,
  179. )
  180. yield* db.run(sql`INSERT INTO session VALUES ('session', 'title')`)
  181. yield* db.run(sql`INSERT INTO message VALUES ('message', 'session')`)
  182. yield* DatabaseMigration.applyOnly(db, [
  183. {
  184. id: "rebuild",
  185. foreignKeys: false,
  186. up: (tx) =>
  187. Effect.gen(function* () {
  188. yield* tx.run(sql`CREATE TABLE next_session (id text PRIMARY KEY, title text)`)
  189. yield* tx.run(sql`INSERT INTO next_session SELECT * FROM session`)
  190. yield* tx.run(sql`DROP TABLE session`)
  191. yield* tx.run(sql`ALTER TABLE next_session RENAME TO session`)
  192. }),
  193. },
  194. ])
  195. expect(yield* db.get(sql`SELECT id FROM message`)).toEqual({ id: "message" })
  196. expect(yield* db.get<{ foreign_keys: number }>(sql`PRAGMA foreign_keys`)).toEqual({ foreign_keys: 1 })
  197. }),
  198. )
  199. })
  200. test("imports an existing Drizzle migration journal once", async () => {
  201. await run(
  202. Effect.gen(function* () {
  203. const db = yield* makeDb
  204. yield* db.run(
  205. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  206. )
  207. yield* db.run(sql`
  208. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  209. VALUES ('hash', 1, 'legacy', ${new Date().toISOString()})
  210. `)
  211. yield* DatabaseMigration.applyOnly(db, [])
  212. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "legacy" }])
  213. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  214. yield* db.run(sql`UPDATE __drizzle_migrations SET name = 'ignored'`)
  215. yield* DatabaseMigration.applyOnly(db, [])
  216. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }, { id: "legacy" }])
  217. }),
  218. )
  219. })
  220. })