migration.ts 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. import fs from "fs/promises"
  4. import os from "os"
  5. import path from "path"
  6. import { pathToFileURL } from "url"
  7. import { parseArgs } from "util"
  8. const root = path.resolve(import.meta.dirname, "../../..")
  9. const snapshot = path.join(root, "packages/core/schema.json")
  10. const tsDir = path.join(root, "packages/core/src/database/migration")
  11. const registry = path.join(root, "packages/core/src/database/migration.gen.ts")
  12. const schema = path.join(root, "packages/core/src/database/schema.gen.ts")
  13. const args = parseArgs({
  14. args: process.argv.slice(2),
  15. options: {
  16. check: { type: "boolean" },
  17. name: { type: "string" },
  18. },
  19. })
  20. if (args.values.check) {
  21. await check()
  22. process.exit(0)
  23. }
  24. await generate()
  25. async function generate() {
  26. const temporary = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-core-migration-"))
  27. const incremental = path.join(temporary, "incremental")
  28. const full = path.join(temporary, "full")
  29. try {
  30. await fs.mkdir(incremental)
  31. await fs.mkdir(path.join(incremental, "baseline"))
  32. await fs.copyFile(snapshot, path.join(incremental, "baseline/snapshot.json"))
  33. await drizzle(temporary, incremental, args.values.name)
  34. const generated = await generatedMigrations(incremental)
  35. if (generated.length > 1) throw new Error(`Expected one generated migration, found ${generated.length}.`)
  36. const name = generated[0]
  37. if (name) {
  38. const target = path.join(tsDir, `${name}.ts`)
  39. if (await Bun.file(target).exists()) throw new Error(`Database migration already exists: ${name}`)
  40. await Bun.write(
  41. target,
  42. await formatTypescript(
  43. renderMigration(name, await Bun.file(path.join(incremental, name, "migration.sql")).text()),
  44. ),
  45. )
  46. await fs.copyFile(path.join(incremental, name, "snapshot.json"), snapshot)
  47. }
  48. await fs.mkdir(full)
  49. await drizzle(temporary, full, "schema")
  50. await Bun.write(schema, await formatTypescript(renderSchema(await generatedSql(full))))
  51. await Bun.write(registry, await formatTypescript(renderRegistry(await typescriptMigrations())))
  52. } finally {
  53. await fs.rm(temporary, { recursive: true, force: true })
  54. }
  55. }
  56. async function check() {
  57. const temporary = await fs.mkdtemp(path.join(os.tmpdir(), "opencode-core-migration-check-"))
  58. const incremental = path.join(temporary, "incremental")
  59. const full = path.join(temporary, "full")
  60. try {
  61. await fs.mkdir(incremental)
  62. await fs.mkdir(path.join(incremental, "baseline"))
  63. await fs.copyFile(snapshot, path.join(incremental, "baseline/snapshot.json"))
  64. await drizzle(temporary, incremental)
  65. if ((await generatedMigrations(incremental)).length > 0) {
  66. throw new Error(
  67. "Core schema has ungenerated database migrations. Run `bun script/migration.ts` from packages/core.",
  68. )
  69. }
  70. await fs.mkdir(full)
  71. await drizzle(temporary, full, "schema")
  72. if ((await Bun.file(schema).text()) !== (await formatTypescript(renderSchema(await generatedSql(full))))) {
  73. throw new Error("Current database schema is stale. Run `bun script/migration.ts` from packages/core.")
  74. }
  75. const migrations = await typescriptMigrations()
  76. if ((await Bun.file(registry).text()) !== (await formatTypescript(renderRegistry(migrations)))) {
  77. throw new Error("Database migration registry is stale. Run `bun script/migration.ts` from packages/core.")
  78. }
  79. } finally {
  80. await fs.rm(temporary, { recursive: true, force: true })
  81. }
  82. }
  83. async function drizzle(temporary: string, output: string, name?: string) {
  84. const config = path.join(temporary, `${path.basename(output)}.config.ts`)
  85. await Bun.write(
  86. config,
  87. `import config from ${JSON.stringify(pathToFileURL(path.join(root, "packages/core/drizzle.config.ts")).href)}
  88. export default { ...config, out: ${JSON.stringify(output)} }
  89. `,
  90. )
  91. await $`bun drizzle-kit generate --config ${config} ${name ? ["--name", name] : []}`.cwd(
  92. path.join(root, "packages/core"),
  93. )
  94. }
  95. async function generatedMigrations(directory: string) {
  96. return (await Array.fromAsync(new Bun.Glob("*/migration.sql").scan({ cwd: directory })))
  97. .map((file) => file.split("/")[0])
  98. .filter((name): name is string => name !== undefined)
  99. .sort()
  100. }
  101. async function generatedSql(directory: string) {
  102. const generated = await generatedMigrations(directory)
  103. if (generated.length !== 1) throw new Error(`Expected one full schema migration, found ${generated.length}.`)
  104. return Bun.file(path.join(directory, generated[0]!, "migration.sql")).text()
  105. }
  106. async function typescriptMigrations() {
  107. return (await Array.fromAsync(new Bun.Glob("*.ts").scan({ cwd: tsDir })))
  108. .map((file) => path.basename(file, ".ts"))
  109. .sort()
  110. }
  111. function renderMigration(name: string, sql: string) {
  112. return `import { Effect } from "effect"
  113. import type { DatabaseMigration } from "../migration"
  114. export default {
  115. id: ${JSON.stringify(name)},
  116. up(tx) {
  117. return Effect.gen(function* () {
  118. ${renderStatements(sql)}
  119. })
  120. },
  121. } satisfies DatabaseMigration.Migration
  122. `
  123. }
  124. function renderSchema(sql: string) {
  125. return `import { Effect } from "effect"
  126. import type { DatabaseMigration } from "./migration"
  127. export default {
  128. up(tx) {
  129. return Effect.gen(function* () {
  130. ${renderStatements(sql)}
  131. })
  132. },
  133. } satisfies Omit<DatabaseMigration.Migration, "id">
  134. `
  135. }
  136. function renderStatements(sql: string) {
  137. return sql
  138. .split("--> statement-breakpoint")
  139. .map((statement) => statement.trim())
  140. .filter((statement) => statement.length > 0)
  141. .map(renderRun)
  142. .join("\n")
  143. }
  144. function renderRun(statement: string) {
  145. const lines = statement.replaceAll("\t", " ").split("\n")
  146. if (lines.length === 1) return ` yield* tx.run(\`${escapeTemplate(lines[0])}\`)`
  147. return ` yield* tx.run(\`\n${lines.map((line) => ` ${escapeTemplate(line)}`).join("\n")}\n \`)`
  148. }
  149. function escapeTemplate(line: string) {
  150. return line.replaceAll("\\", "\\\\").replaceAll("`", "\\`").replaceAll("${", "\\${")
  151. }
  152. async function formatTypescript(input: string) {
  153. const prettier = await import("prettier")
  154. const typescript = await import("prettier/plugins/typescript")
  155. const estree = await import("prettier/plugins/estree")
  156. return prettier.format(input, {
  157. parser: "typescript",
  158. plugins: [typescript.default, estree.default],
  159. semi: false,
  160. printWidth: 120,
  161. })
  162. }
  163. function renderRegistry(names: string[]) {
  164. return `import type { DatabaseMigration } from "./migration"
  165. export const migrations = (
  166. await Promise.all([
  167. ${names.map((name) => ` import("./migration/${name}"),`).join("\n")}
  168. ])
  169. ).map((module) => module.default) satisfies DatabaseMigration.Migration[]
  170. `
  171. }