database-migration.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 { eq, inArray, 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 sessionUsageMigration from "@opencode-ai/core/database/migration/20260510033149_session_usage"
  12. import normalizeStoragePathsMigration from "@opencode-ai/core/database/migration/20260601010001_normalize_storage_paths"
  13. import sessionMessageProjectionOrderMigration from "@opencode-ai/core/database/migration/20260603040000_session_message_projection_order"
  14. import eventSourcedSessionInputMigration from "@opencode-ai/core/database/migration/20260604172448_event_sourced_session_input"
  15. import { ProjectV2 } from "@opencode-ai/core/project"
  16. import { ProjectTable } from "@opencode-ai/core/project/sql"
  17. import { AbsolutePath } from "@opencode-ai/core/schema"
  18. import { SessionSchema } from "@opencode-ai/core/session/schema"
  19. import { SessionTable } from "@opencode-ai/core/session/sql"
  20. import sessionMetadataMigration from "@opencode-ai/core/database/migration/20260511173437_session-metadata"
  21. import type { SqlClient as SqlClientService } from "effect/unstable/sql/SqlClient"
  22. import { Database } from "@opencode-ai/core/database/database"
  23. import { tmpdir } from "./fixture/tmpdir"
  24. const run = <A, E>(effect: Effect.Effect<A, E, SqlClientService>) =>
  25. Effect.runPromise(
  26. effect.pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Effect.scoped),
  27. )
  28. const makeDb = EffectDrizzleSqlite.makeWithDefaults()
  29. describe("DatabaseMigration", () => {
  30. test("serializes concurrent embedded initialization for one database path", async () => {
  31. await using tmp = await tmpdir()
  32. const filename = path.join(tmp.path, "embedded.sqlite")
  33. const layers = [Database.layerFromPath(filename), Database.layerFromPath(filename)]
  34. await Effect.runPromise(
  35. Effect.all(
  36. layers.map((layer) => Effect.scoped(Layer.build(layer))),
  37. { concurrency: "unbounded" },
  38. ),
  39. )
  40. })
  41. if (process.platform === "linux") {
  42. test("declared schema has no ungenerated migrations", async () => {
  43. const result = await $`bun ${fileURLToPath(new URL("../script/migration.ts", import.meta.url))} --check`
  44. .quiet()
  45. .nothrow()
  46. expect(result.exitCode, result.stderr.toString()).toBe(0)
  47. expect(result.stdout.toString()).toContain("No schema changes, nothing to migrate")
  48. }, 30_000)
  49. }
  50. test("applies tracked migrations to an empty database", async () => {
  51. await run(
  52. Effect.gen(function* () {
  53. const db = yield* makeDb
  54. yield* DatabaseMigration.apply(db)
  55. expect(yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'`)).toEqual({
  56. name: "session",
  57. })
  58. expect(
  59. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_input'`),
  60. ).toEqual({ name: "session_input" })
  61. expect(
  62. yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_context_epoch'`),
  63. ).toEqual({ name: "session_context_epoch" })
  64. expect(yield* db.get(sql`SELECT count(*) as count FROM migration`)).toEqual({ count: migrations.length })
  65. expect(
  66. yield* db.all(
  67. sql`SELECT name FROM sqlite_master WHERE type = 'index' AND name IN ('event_aggregate_seq_idx', 'event_aggregate_type_seq_idx', 'session_input_session_pending_seq_idx', 'session_input_session_pending_delivery_seq_idx', 'session_input_session_admitted_seq_idx', 'session_input_session_promoted_seq_idx', 'session_message_session_idx', 'session_message_session_type_idx', 'session_message_session_seq_idx', 'session_message_session_type_seq_idx', 'session_message_session_time_created_id_idx') ORDER BY name`,
  68. ),
  69. ).toEqual([
  70. { name: "event_aggregate_seq_idx" },
  71. { name: "event_aggregate_type_seq_idx" },
  72. { name: "session_input_session_admitted_seq_idx" },
  73. { name: "session_input_session_pending_delivery_seq_idx" },
  74. { name: "session_input_session_promoted_seq_idx" },
  75. { name: "session_message_session_seq_idx" },
  76. { name: "session_message_session_time_created_id_idx" },
  77. { name: "session_message_session_type_seq_idx" },
  78. ])
  79. }),
  80. )
  81. })
  82. test("resets beta history and rebuilds event-sourced Session input storage", async () => {
  83. await run(
  84. Effect.gen(function* () {
  85. const db = yield* makeDb
  86. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, workspace_id text)`)
  87. yield* db.run(sql`CREATE TABLE workspace (id text PRIMARY KEY)`)
  88. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY)`)
  89. yield* db.run(sql`CREATE TABLE part (id text PRIMARY KEY)`)
  90. yield* db.run(sql`CREATE TABLE event_sequence (aggregate_id text PRIMARY KEY, seq integer NOT NULL)`)
  91. yield* db.run(
  92. sql`CREATE TABLE event (id text PRIMARY KEY, aggregate_id text NOT NULL, seq integer NOT NULL, type text NOT NULL, data text NOT NULL)`,
  93. )
  94. yield* db.run(sql`CREATE INDEX event_aggregate_seq_idx ON event (aggregate_id, seq)`)
  95. yield* db.run(sql`CREATE INDEX event_aggregate_type_seq_idx ON event (aggregate_id, type, seq)`)
  96. yield* db.run(
  97. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, seq integer NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  98. )
  99. yield* db.run(sql`CREATE INDEX session_message_session_seq_idx ON session_message (session_id, seq)`)
  100. yield* db.run(
  101. sql`CREATE TABLE session_input (seq integer PRIMARY KEY AUTOINCREMENT, id text NOT NULL UNIQUE, session_id text NOT NULL, prompt text NOT NULL, delivery text NOT NULL, promoted_seq integer, time_created integer NOT NULL)`,
  102. )
  103. yield* db.run(
  104. sql`CREATE INDEX session_input_session_pending_delivery_seq_idx ON session_input (session_id, promoted_seq, delivery, seq)`,
  105. )
  106. yield* db.run(sql`INSERT INTO session (id, workspace_id) VALUES ('session', 'wrk_old')`)
  107. yield* db.run(sql`INSERT INTO workspace (id) VALUES ('wrk_old')`)
  108. yield* db.run(sql`INSERT INTO message (id) VALUES ('message')`)
  109. yield* db.run(sql`INSERT INTO part (id) VALUES ('part')`)
  110. yield* db.run(sql`INSERT INTO event_sequence (aggregate_id, seq) VALUES ('session', 0)`)
  111. yield* db.run(
  112. sql`INSERT INTO event (id, aggregate_id, seq, type, data) VALUES ('evt_old', 'session', 0, 'old.1', '{}')`,
  113. )
  114. yield* db.run(
  115. sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('msg_old', 'session', 'user', 0, 1, 1, '{}')`,
  116. )
  117. yield* db.run(
  118. sql`INSERT INTO session_input (id, session_id, prompt, delivery, time_created) VALUES ('msg_pending', 'session', '{}', 'steer', 1)`,
  119. )
  120. yield* DatabaseMigration.applyOnly(db, [eventSourcedSessionInputMigration])
  121. expect(yield* db.all(sql`SELECT id, workspace_id FROM session`)).toEqual([
  122. { id: "session", workspace_id: null },
  123. ])
  124. expect(yield* db.all(sql`SELECT id FROM workspace`)).toEqual([])
  125. expect(yield* db.all(sql`SELECT id FROM message`)).toEqual([{ id: "message" }])
  126. expect(yield* db.all(sql`SELECT id FROM part`)).toEqual([{ id: "part" }])
  127. expect(yield* db.all(sql`SELECT id FROM event`)).toEqual([])
  128. expect(yield* db.all(sql`SELECT aggregate_id FROM event_sequence`)).toEqual([])
  129. expect(yield* db.all(sql`SELECT id FROM session_message`)).toEqual([])
  130. expect(yield* db.all(sql`SELECT id FROM session_input`)).toEqual([])
  131. expect(
  132. (yield* db.all<{ name: string }>(sql`PRAGMA table_info(session_input)`)).map((column) => column.name),
  133. ).toEqual(["id", "session_id", "prompt", "delivery", "admitted_seq", "promoted_seq", "time_created"])
  134. expect(
  135. (yield* db.all<{ name: string; unique: number }>(sql`PRAGMA index_list(session_message)`)).find(
  136. (index) => index.name === "session_message_session_seq_idx",
  137. ),
  138. ).toMatchObject({ unique: 1 })
  139. expect(
  140. (yield* db.all<{ name: string; unique: number }>(sql`PRAGMA index_list(event)`)).find(
  141. (index) => index.name === "event_aggregate_seq_idx",
  142. ),
  143. ).toMatchObject({ unique: 1 })
  144. expect(
  145. (yield* db.all<{ name: string; unique: number }>(sql`PRAGMA index_list(session_input)`)).filter((index) =>
  146. ["session_input_session_admitted_seq_idx", "session_input_session_promoted_seq_idx"].includes(index.name),
  147. ),
  148. ).toEqual([
  149. expect.objectContaining({ name: "session_input_session_promoted_seq_idx", unique: 1 }),
  150. expect.objectContaining({ name: "session_input_session_admitted_seq_idx", unique: 1 }),
  151. ])
  152. }),
  153. )
  154. })
  155. test("resets incompatible projected Session messages before adding sequence order", async () => {
  156. await run(
  157. Effect.gen(function* () {
  158. const db = yield* makeDb
  159. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY)`)
  160. yield* db.run(
  161. sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  162. )
  163. yield* db.run(
  164. sql`CREATE TABLE part (id text PRIMARY KEY, message_id text NOT NULL, session_id text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  165. )
  166. yield* db.run(sql`CREATE TABLE event (id text PRIMARY KEY, seq integer NOT NULL)`)
  167. yield* db.run(
  168. sql`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`,
  169. )
  170. yield* db.run(
  171. sql`CREATE INDEX session_message_session_time_created_id_idx ON session_message (session_id, time_created, id)`,
  172. )
  173. yield* db.run(
  174. sql`CREATE INDEX session_message_session_type_time_created_id_idx ON session_message (session_id, type, time_created, id)`,
  175. )
  176. yield* db.run(sql`INSERT INTO session (id) VALUES ('session')`)
  177. yield* db.run(
  178. sql`INSERT INTO message (id, session_id, time_created, time_updated, data) VALUES ('legacy_message', 'session', 1, 1, '{"role":"user"}')`,
  179. )
  180. yield* db.run(
  181. sql`INSERT INTO part (id, message_id, session_id, time_created, time_updated, data) VALUES ('legacy_part', 'legacy_message', 'session', 1, 1, '{"type":"text","text":"hello"}')`,
  182. )
  183. yield* db.run(
  184. sql`INSERT INTO session_message (id, session_id, type, time_created, time_updated, data) VALUES ('stale_projection', 'session', 'user', 1, 1, '{}')`,
  185. )
  186. yield* DatabaseMigration.applyOnly(db, [sessionMessageProjectionOrderMigration])
  187. expect(yield* db.all(sql`SELECT id, session_id, data FROM message`)).toEqual([
  188. { id: "legacy_message", session_id: "session", data: '{"role":"user"}' },
  189. ])
  190. expect(yield* db.all(sql`SELECT id, message_id, session_id, data FROM part`)).toEqual([
  191. {
  192. id: "legacy_part",
  193. message_id: "legacy_message",
  194. session_id: "session",
  195. data: '{"type":"text","text":"hello"}',
  196. },
  197. ])
  198. expect(yield* db.all(sql`SELECT id FROM session_message`)).toEqual([])
  199. yield* db.run(
  200. sql`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES ('fresh_projection', 'session', 'user', 7, 2, 2, '{}')`,
  201. )
  202. expect(yield* db.get(sql`SELECT id, seq FROM session_message`)).toEqual({ id: "fresh_projection", seq: 7 })
  203. }),
  204. )
  205. })
  206. test("runs session usage backfill in order with schema changes", async () => {
  207. await run(
  208. Effect.gen(function* () {
  209. const db = yield* makeDb
  210. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, time_updated integer NOT NULL)`)
  211. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, data text NOT NULL)`)
  212. yield* db.run(sql`INSERT INTO session (id, time_updated) VALUES ('session_1', 1)`)
  213. yield* db.run(
  214. sql`INSERT INTO message (id, session_id, data) VALUES ('message_1', 'session_1', '{"role":"assistant","cost":1.25,"tokens":{"input":2,"output":3,"reasoning":4,"cache":{"read":5,"write":6}}}')`,
  215. )
  216. yield* DatabaseMigration.applyOnly(db, [sessionUsageMigration])
  217. expect(
  218. yield* db.get(
  219. sql`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = 'session_1'`,
  220. ),
  221. ).toEqual({
  222. cost: 1.25,
  223. tokens_input: 2,
  224. tokens_output: 3,
  225. tokens_reasoning: 4,
  226. tokens_cache_read: 5,
  227. tokens_cache_write: 6,
  228. })
  229. }),
  230. )
  231. })
  232. test("normalizes Windows storage paths and leaves POSIX paths untouched", async () => {
  233. await run(
  234. Effect.gen(function* () {
  235. const db = yield* makeDb
  236. yield* db.run(sql`CREATE TABLE project (id text PRIMARY KEY, worktree text NOT NULL, sandboxes text NOT NULL)`)
  237. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, directory text NOT NULL, path text)`)
  238. // Windows-shaped rows (drive + backslash) must be normalized.
  239. yield* db.run(
  240. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"win"}, ${"C:\\Repo\\Thing"}, ${JSON.stringify([
  241. "C:\\Repo\\Thing\\sandbox",
  242. ])})`,
  243. )
  244. yield* db.run(
  245. sql`INSERT INTO session (id, directory, path) VALUES (${"win"}, ${"C:\\Repo\\Thing\\packages\\api"}, ${"packages\\api"})`,
  246. )
  247. // UNC worktrees and their sandboxes must normalize too (not just drive paths).
  248. yield* db.run(
  249. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"unc"}, ${"\\\\server\\share"}, ${JSON.stringify([
  250. "\\\\server\\share\\sandbox",
  251. ])})`,
  252. )
  253. // The "/" worktree sentinel and POSIX paths (including a pathological
  254. // backslash in a POSIX filename) must survive byte-for-byte.
  255. yield* db.run(sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"global"}, ${"/"}, ${"[]"})`)
  256. yield* db.run(
  257. sql`INSERT INTO session (id, directory, path) VALUES (${"posix"}, ${"/home/me/we\\ird"}, ${"src\\weird"})`,
  258. )
  259. yield* DatabaseMigration.applyOnly(db, [normalizeStoragePathsMigration])
  260. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'win'`)).toEqual({
  261. worktree: "C:/Repo/Thing",
  262. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  263. })
  264. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'win'`)).toEqual({
  265. directory: "C:/Repo/Thing/packages/api",
  266. path: "packages/api",
  267. })
  268. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'unc'`)).toEqual({
  269. worktree: "//server/share",
  270. sandboxes: JSON.stringify(["//server/share/sandbox"]),
  271. })
  272. expect(yield* db.get(sql`SELECT worktree FROM project WHERE id = 'global'`)).toEqual({ worktree: "/" })
  273. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'posix'`)).toEqual({
  274. directory: "/home/me/we\\ird",
  275. path: "src\\weird",
  276. })
  277. }),
  278. )
  279. })
  280. test("maps native Windows paths through database columns", async () => {
  281. if (process.platform !== "win32") return
  282. await run(
  283. Effect.gen(function* () {
  284. const db = yield* makeDb
  285. yield* DatabaseMigration.apply(db)
  286. const projectID = ProjectV2.ID.make("codec_project")
  287. const worktree = AbsolutePath.make("C:\\Repo\\Thing")
  288. const sandbox = AbsolutePath.make("C:\\Repo\\Thing\\sandbox")
  289. const directory = "C:\\Repo\\Thing\\packages\\api"
  290. const sessionID = SessionSchema.ID.make("ses_codec")
  291. expect(() =>
  292. Effect.runSync(
  293. db
  294. .insert(ProjectTable)
  295. .values({
  296. id: ProjectV2.ID.make("invalid_path"),
  297. worktree: AbsolutePath.make("not-absolute"),
  298. sandboxes: [],
  299. time_created: 1,
  300. time_updated: 1,
  301. })
  302. .run(),
  303. ),
  304. ).toThrow()
  305. yield* db
  306. .insert(ProjectTable)
  307. .values({
  308. id: projectID,
  309. worktree,
  310. sandboxes: [sandbox],
  311. time_created: 1,
  312. time_updated: 1,
  313. })
  314. .run()
  315. yield* db
  316. .insert(SessionTable)
  317. .values({
  318. id: sessionID,
  319. project_id: projectID,
  320. slug: "codec",
  321. directory,
  322. path: "packages\\api",
  323. title: "Codec",
  324. version: "test",
  325. time_created: 1,
  326. time_updated: 1,
  327. })
  328. .run()
  329. expect(
  330. yield* db.get<{ worktree: string; sandboxes: string }>(
  331. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  332. ),
  333. ).toEqual({
  334. worktree: "C:/Repo/Thing",
  335. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  336. })
  337. expect(
  338. yield* db.get<{ directory: string; path: string }>(
  339. sql`SELECT directory, path FROM session WHERE id = ${sessionID}`,
  340. ),
  341. ).toEqual({
  342. directory: "C:/Repo/Thing/packages/api",
  343. path: "packages/api",
  344. })
  345. const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.worktree, worktree)).get()
  346. const session = yield* db.select().from(SessionTable).where(eq(SessionTable.directory, directory)).get()
  347. expect(project?.worktree).toBe(worktree)
  348. expect(project?.sandboxes).toEqual([sandbox])
  349. expect(session?.directory).toBe(directory)
  350. expect(session?.path).toBe("packages/api")
  351. expect((yield* db.select().from(SessionTable).where(eq(SessionTable.path, "packages\\api")).get())?.id).toBe(
  352. sessionID,
  353. )
  354. const moved = AbsolutePath.make("D:\\Moved\\Thing")
  355. const updated = yield* db
  356. .update(ProjectTable)
  357. .set({ worktree: moved, sandboxes: [moved] })
  358. .where(eq(ProjectTable.id, projectID))
  359. .returning()
  360. .get()
  361. expect(updated?.worktree).toBe(moved)
  362. expect(updated?.sandboxes).toEqual([moved])
  363. expect(
  364. yield* db.get<{ worktree: string; sandboxes: string }>(
  365. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  366. ),
  367. ).toEqual({ worktree: "D:/Moved/Thing", sandboxes: JSON.stringify(["D:/Moved/Thing"]) })
  368. expect(
  369. (yield* db
  370. .select()
  371. .from(ProjectTable)
  372. .where(inArray(ProjectTable.worktree, [moved]))
  373. .get())?.id,
  374. ).toBe(projectID)
  375. yield* db.run(sql`UPDATE project SET worktree = ${"not-absolute"} WHERE id = ${projectID}`)
  376. expect(() =>
  377. Effect.runSync(db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get()),
  378. ).toThrow()
  379. }),
  380. )
  381. })
  382. test("imports existing drizzle migration state", async () => {
  383. await run(
  384. Effect.gen(function* () {
  385. const db = yield* makeDb
  386. yield* db.run(
  387. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  388. )
  389. yield* db.run(sql`
  390. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  391. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  392. `)
  393. yield* DatabaseMigration.applyOnly(db, [])
  394. expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" })
  395. }),
  396. )
  397. })
  398. test("does not replay a migrated session metadata column", async () => {
  399. await run(
  400. Effect.gen(function* () {
  401. const db = yield* makeDb
  402. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  403. yield* db.run(
  404. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  405. )
  406. yield* db.run(sql`
  407. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  408. VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()})
  409. `)
  410. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  411. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }])
  412. }),
  413. )
  414. })
  415. test("accepts the temporary replacement session metadata migration id", async () => {
  416. await run(
  417. Effect.gen(function* () {
  418. const db = yield* makeDb
  419. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  420. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  421. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`)
  422. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  423. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([
  424. { id: "20260511173437_session-metadata" },
  425. { id: "20260530232709_lovely_romulus" },
  426. ])
  427. }),
  428. )
  429. })
  430. test("skips drizzle import when migration table already has state", async () => {
  431. await run(
  432. Effect.gen(function* () {
  433. const db = yield* makeDb
  434. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  435. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  436. yield* db.run(
  437. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  438. )
  439. yield* db.run(sql`
  440. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  441. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  442. `)
  443. yield* DatabaseMigration.applyOnly(db, [])
  444. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }])
  445. }),
  446. )
  447. })
  448. })