database-migration.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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: 25 })
  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(
  169. yield* db.get<{ worktree: string; sandboxes: string }>(
  170. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  171. ),
  172. ).toEqual({
  173. worktree: "C:/Repo/Thing",
  174. sandboxes: JSON.stringify(["C:/Repo/Thing/sandbox"]),
  175. })
  176. expect(
  177. yield* db.get<{ directory: string; path: string }>(
  178. sql`SELECT directory, path FROM session WHERE id = ${sessionID}`,
  179. ),
  180. ).toEqual({
  181. directory: "C:/Repo/Thing/packages/api",
  182. path: "packages/api",
  183. })
  184. const project = yield* db.select().from(ProjectTable).where(eq(ProjectTable.worktree, worktree)).get()
  185. const session = yield* db.select().from(SessionTable).where(eq(SessionTable.directory, directory)).get()
  186. expect(project?.worktree).toBe(worktree)
  187. expect(project?.sandboxes).toEqual([sandbox])
  188. expect(session?.directory).toBe(directory)
  189. expect(session?.path).toBe("packages/api")
  190. expect((yield* db.select().from(SessionTable).where(eq(SessionTable.path, "packages\\api")).get())?.id).toBe(
  191. sessionID,
  192. )
  193. const moved = AbsolutePath.make("D:\\Moved\\Thing")
  194. const updated = yield* db
  195. .update(ProjectTable)
  196. .set({ worktree: moved, sandboxes: [moved] })
  197. .where(eq(ProjectTable.id, projectID))
  198. .returning()
  199. .get()
  200. expect(updated?.worktree).toBe(moved)
  201. expect(updated?.sandboxes).toEqual([moved])
  202. expect(
  203. yield* db.get<{ worktree: string; sandboxes: string }>(
  204. sql`SELECT worktree, sandboxes FROM project WHERE id = ${projectID}`,
  205. ),
  206. ).toEqual({ worktree: "D:/Moved/Thing", sandboxes: JSON.stringify(["D:/Moved/Thing"]) })
  207. expect(
  208. (yield* db
  209. .select()
  210. .from(ProjectTable)
  211. .where(inArray(ProjectTable.worktree, [moved]))
  212. .get())?.id,
  213. ).toBe(projectID)
  214. yield* db.run(sql`UPDATE project SET worktree = ${"not-absolute"} WHERE id = ${projectID}`)
  215. expect(() =>
  216. Effect.runSync(db.select().from(ProjectTable).where(eq(ProjectTable.id, projectID)).get()),
  217. ).toThrow()
  218. }),
  219. )
  220. })
  221. test("imports existing drizzle migration state", async () => {
  222. await run(
  223. Effect.gen(function* () {
  224. const db = yield* makeDb
  225. yield* db.run(
  226. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  227. )
  228. yield* db.run(sql`
  229. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  230. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  231. `)
  232. yield* DatabaseMigration.applyOnly(db, [])
  233. expect(yield* db.get(sql`SELECT id FROM migration`)).toEqual({ id: "20260127222353_familiar_lady_ursula" })
  234. }),
  235. )
  236. })
  237. test("does not replay a migrated session metadata column", async () => {
  238. await run(
  239. Effect.gen(function* () {
  240. const db = yield* makeDb
  241. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  242. yield* db.run(
  243. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  244. )
  245. yield* db.run(sql`
  246. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  247. VALUES ('hash', 1, '20260511173437_session-metadata', ${new Date().toISOString()})
  248. `)
  249. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  250. expect(yield* db.all(sql`SELECT id FROM migration`)).toEqual([{ id: "20260511173437_session-metadata" }])
  251. }),
  252. )
  253. })
  254. test("accepts the temporary replacement session metadata migration id", async () => {
  255. await run(
  256. Effect.gen(function* () {
  257. const db = yield* makeDb
  258. yield* db.run(sql`CREATE TABLE session (id text PRIMARY KEY, metadata text)`)
  259. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  260. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('20260530232709_lovely_romulus', 1)`)
  261. yield* DatabaseMigration.applyOnly(db, [sessionMetadataMigration])
  262. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([
  263. { id: "20260511173437_session-metadata" },
  264. { id: "20260530232709_lovely_romulus" },
  265. ])
  266. }),
  267. )
  268. })
  269. test("skips drizzle import when migration table already has state", async () => {
  270. await run(
  271. Effect.gen(function* () {
  272. const db = yield* makeDb
  273. yield* db.run(sql`CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER NOT NULL)`)
  274. yield* db.run(sql`INSERT INTO migration (id, time_completed) VALUES ('existing', 1)`)
  275. yield* db.run(
  276. sql`CREATE TABLE __drizzle_migrations (id INTEGER PRIMARY KEY, hash text NOT NULL, created_at numeric, name text, applied_at TEXT)`,
  277. )
  278. yield* db.run(sql`
  279. INSERT INTO __drizzle_migrations (hash, created_at, name, applied_at)
  280. VALUES ('hash', 1, '20260127222353_familiar_lady_ursula', ${new Date().toISOString()})
  281. `)
  282. yield* DatabaseMigration.applyOnly(db, [])
  283. expect(yield* db.all(sql`SELECT id FROM migration ORDER BY id`)).toEqual([{ id: "existing" }])
  284. }),
  285. )
  286. })
  287. })