database-migration.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. import { describe, expect, test } from "bun:test"
  2. import { $ } from "bun"
  3. import { fileURLToPath } from "url"
  4. import { SqliteClient } from "@effect/sql-sqlite-bun"
  5. import { EffectDrizzleSqlite } from "@opencode-ai/effect-drizzle-sqlite"
  6. import { Effect } from "effect"
  7. import { eq, inArray, sql } from "drizzle-orm"
  8. import { DatabaseMigration } from "@opencode-ai/core/database/migration"
  9. import sessionUsageMigration from "@opencode-ai/core/database/migration/20260510033149_session_usage"
  10. import normalizeStoragePathsMigration from "@opencode-ai/core/database/migration/20260601010001_normalize_storage_paths"
  11. import { ProjectV2 } from "@opencode-ai/core/project"
  12. import { ProjectTable } from "@opencode-ai/core/project/sql"
  13. import { AbsolutePath } from "@opencode-ai/core/schema"
  14. import { SessionSchema } from "@opencode-ai/core/session/schema"
  15. import { SessionTable } from "@opencode-ai/core/session/sql"
  16. import sessionMetadataMigration from "@opencode-ai/core/database/migration/20260511173437_session-metadata"
  17. import type { SqlClient as SqlClientService } from "effect/unstable/sql/SqlClient"
  18. const run = <A, E>(effect: Effect.Effect<A, E, SqlClientService>) =>
  19. Effect.runPromise(
  20. effect.pipe(Effect.provide(SqliteClient.layer({ filename: ":memory:", disableWAL: true })), Effect.scoped),
  21. )
  22. const makeDb = EffectDrizzleSqlite.makeWithDefaults()
  23. describe("DatabaseMigration", () => {
  24. if (process.platform === "linux") {
  25. test("declared schema has no ungenerated migrations", async () => {
  26. const result = await $`bun ${fileURLToPath(new URL("../script/migration.ts", import.meta.url))} --check`
  27. .quiet()
  28. .nothrow()
  29. expect(result.exitCode, result.stderr.toString()).toBe(0)
  30. expect(result.stdout.toString()).toContain("No schema changes, nothing to migrate")
  31. }, 30_000)
  32. }
  33. test("applies tracked migrations to an empty database", async () => {
  34. await run(
  35. Effect.gen(function* () {
  36. const db = yield* makeDb
  37. yield* DatabaseMigration.apply(db)
  38. expect(yield* db.get(sql`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session'`)).toEqual({
  39. name: "session",
  40. })
  41. expect(yield* db.get(sql`SELECT count(*) as count FROM migration`)).toEqual({ count: 22 })
  42. }),
  43. )
  44. })
  45. test("runs session usage backfill in order with schema changes", async () => {
  46. await run(
  47. Effect.gen(function* () {
  48. const db = yield* makeDb
  49. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, time_updated integer NOT NULL)`)
  50. yield* db.run(sql`CREATE TABLE message (id text PRIMARY KEY, session_id text NOT NULL, data text NOT NULL)`)
  51. yield* db.run(sql`INSERT INTO session (id, time_updated) VALUES ('session_1', 1)`)
  52. yield* db.run(
  53. 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}}}')`,
  54. )
  55. yield* DatabaseMigration.applyOnly(db, [sessionUsageMigration])
  56. expect(
  57. yield* db.get(
  58. sql`SELECT cost, tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = 'session_1'`,
  59. ),
  60. ).toEqual({
  61. cost: 1.25,
  62. tokens_input: 2,
  63. tokens_output: 3,
  64. tokens_reasoning: 4,
  65. tokens_cache_read: 5,
  66. tokens_cache_write: 6,
  67. })
  68. }),
  69. )
  70. })
  71. test("normalizes Windows storage paths and leaves POSIX paths untouched", async () => {
  72. await run(
  73. Effect.gen(function* () {
  74. const db = yield* makeDb
  75. yield* db.run(sql`CREATE TABLE project (id text PRIMARY KEY, worktree text NOT NULL, sandboxes text NOT NULL)`)
  76. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, directory text NOT NULL, path text)`)
  77. // Windows-shaped rows (drive + backslash) must be normalized.
  78. yield* db.run(
  79. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"win"}, ${"C:\\Repo\\Thing"}, ${JSON.stringify([
  80. "C:\\Repo\\Thing\\sandbox",
  81. ])})`,
  82. )
  83. yield* db.run(
  84. sql`INSERT INTO session (id, directory, path) VALUES (${"win"}, ${"C:\\Repo\\Thing\\packages\\api"}, ${"packages\\api"})`,
  85. )
  86. // UNC worktrees and their sandboxes must normalize too (not just drive paths).
  87. yield* db.run(
  88. sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"unc"}, ${"\\\\server\\share"}, ${JSON.stringify([
  89. "\\\\server\\share\\sandbox",
  90. ])})`,
  91. )
  92. // The "/" worktree sentinel and POSIX paths (including a pathological
  93. // backslash in a POSIX filename) must survive byte-for-byte.
  94. yield* db.run(sql`INSERT INTO project (id, worktree, sandboxes) VALUES (${"global"}, ${"/"}, ${"[]"})`)
  95. yield* db.run(
  96. sql`INSERT INTO session (id, directory, path) VALUES (${"posix"}, ${"/home/me/we\\ird"}, ${"src\\weird"})`,
  97. )
  98. yield* DatabaseMigration.applyOnly(db, [normalizeStoragePathsMigration])
  99. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'win'`)).toEqual({
  100. worktree: "C:/Repo/Thing",
  101. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  102. })
  103. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'win'`)).toEqual({
  104. directory: "C:/Repo/Thing/packages/api",
  105. path: "packages/api",
  106. })
  107. expect(yield* db.get(sql`SELECT worktree, sandboxes FROM project WHERE id = 'unc'`)).toEqual({
  108. worktree: "//server/share",
  109. sandboxes: JSON.stringify(["//server/share/sandbox"]),
  110. })
  111. expect(yield* db.get(sql`SELECT worktree FROM project WHERE id = 'global'`)).toEqual({ worktree: "/" })
  112. expect(yield* db.get(sql`SELECT directory, path FROM session WHERE id = 'posix'`)).toEqual({
  113. directory: "/home/me/we\\ird",
  114. path: "src\\weird",
  115. })
  116. }),
  117. )
  118. })
  119. test("maps native Windows paths through database columns", async () => {
  120. if (process.platform !== "win32") return
  121. await run(
  122. Effect.gen(function* () {
  123. const db = yield* makeDb
  124. yield* DatabaseMigration.apply(db)
  125. const projectID = ProjectV2.ID.make("codec_project")
  126. const worktree = AbsolutePath.make("C:\\Repo\\Thing")
  127. const sandbox = AbsolutePath.make("C:\\Repo\\Thing\\sandbox")
  128. const directory = "C:\\Repo\\Thing\\packages\\api"
  129. const sessionID = SessionSchema.ID.make("ses_codec")
  130. expect(() =>
  131. Effect.runSync(
  132. db
  133. .insert(ProjectTable)
  134. .values({
  135. id: ProjectV2.ID.make("invalid_path"),
  136. worktree: AbsolutePath.make("not-absolute"),
  137. sandboxes: [],
  138. time_created: 1,
  139. time_updated: 1,
  140. })
  141. .run(),
  142. ),
  143. ).toThrow()
  144. yield* db
  145. .insert(ProjectTable)
  146. .values({
  147. id: projectID,
  148. worktree,
  149. sandboxes: [sandbox],
  150. time_created: 1,
  151. time_updated: 1,
  152. })
  153. .run()
  154. yield* db
  155. .insert(SessionTable)
  156. .values({
  157. id: sessionID,
  158. project_id: projectID,
  159. slug: "codec",
  160. directory,
  161. path: "packages\\api",
  162. title: "Codec",
  163. version: "test",
  164. time_created: 1,
  165. time_updated: 1,
  166. })
  167. .run()
  168. expect(yield* db.get<{ worktree: string; sandboxes: string }>(sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`)).toEqual({
  169. worktree: "C:/Repo/Thing",
  170. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  171. })
  172. expect(yield* db.get<{ directory: string; path: string }>(sql`SELECT directory, path FROM session WHERE id = ${sessionID}`)).toEqual({
  173. directory: "C:/Repo/Thing/packages/api",
  174. path: "packages/api",
  175. })
  176. const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.worktree, worktree)).get()
  177. const session = yield* db.select().from(SessionTable).where(eq(SessionTable.directory, directory)).get()
  178. expect(project?.worktree).toBe(worktree)
  179. expect(project?.sandboxes).toEqual([sandbox])
  180. expect(session?.directory).toBe(directory)
  181. expect(session?.path).toBe("packages/api")
  182. expect((yield* db.select().from(SessionTable).where(eq(SessionTable.path, "packages\\api")).get())?.id).toBe(
  183. sessionID,
  184. )
  185. const moved = AbsolutePath.make("D:\\Moved\\Thing")
  186. const updated = yield* db
  187. .update(ProjectTable)
  188. .set({ worktree: moved, sandboxes: [moved] })
  189. .where(eq(ProjectTable.id, projectID))
  190. .returning()
  191. .get()
  192. expect(updated?.worktree).toBe(moved)
  193. expect(updated?.sandboxes).toEqual([moved])
  194. expect(
  195. yield* db.get<{ worktree: string; sandboxes: string }>(sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`),
  196. ).toEqual({ worktree: "D:/Moved/Thing", sandboxes: JSON.stringify(["D:/Moved/Thing"]) })
  197. expect((yield* db.select().from(ProjectTable).where(inArray(ProjectTable.worktree, [moved])).get())?.id).toBe(
  198. projectID,
  199. )
  200. yield* db.run(sql`UPDATE project SET worktree = ${"not-absolute"} WHERE id = ${projectID}`)
  201. expect(() => Effect.runSync(db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get())).toThrow()
  202. }),
  203. )
  204. })
  205. test("imports existing drizzle migration state", async () => {
  206. await run(
  207. Effect.gen(function* () {
  208. const db = yield* makeDb
  209. yield* db.run(
  210. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  211. )
  212. yield* db.run(sql`
  213. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  214. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  215. `)
  216. yield* DatabaseMigration.applyOnly(db, [])
  217. expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" })
  218. }),
  219. )
  220. })
  221. test("does not replay a migrated session metadata column", async () => {
  222. await run(
  223. Effect.gen(function* () {
  224. const db = yield* makeDb
  225. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  226. yield* db.run(
  227. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  228. )
  229. yield* db.run(sql`
  230. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  231. VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()})
  232. `)
  233. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  234. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }])
  235. }),
  236. )
  237. })
  238. test("accepts the temporary replacement session metadata migration id", async () => {
  239. await run(
  240. Effect.gen(function* () {
  241. const db = yield* makeDb
  242. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  243. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  244. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`)
  245. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  246. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([
  247. { id: "20260511173437_session-metadata" },
  248. { id: "20260530232709_lovely_romulus" },
  249. ])
  250. }),
  251. )
  252. })
  253. test("skips drizzle import when migration table already has state", async () => {
  254. await run(
  255. Effect.gen(function* () {
  256. const db = yield* makeDb
  257. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  258. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  259. yield* db.run(
  260. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  261. )
  262. yield* db.run(sql`
  263. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  264. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  265. `)
  266. yield* DatabaseMigration.applyOnly(db, [])
  267. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }])
  268. }),
  269. )
  270. })
  271. })