database-migration.test.ts 26 KB

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