@supatype/cli 0.3.4 → 0.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +168 -158
  3. package/.turbo/turbo-typecheck.log +1 -1
  4. package/CHANGELOG.md +36 -0
  5. package/dist/adopt-walkthrough.d.ts +40 -0
  6. package/dist/adopt-walkthrough.d.ts.map +1 -0
  7. package/dist/adopt-walkthrough.js +113 -0
  8. package/dist/adopt-walkthrough.js.map +1 -0
  9. package/dist/cli-version-embedded.js +1 -1
  10. package/dist/commands/admin.d.ts.map +1 -1
  11. package/dist/commands/admin.js +7 -16
  12. package/dist/commands/admin.js.map +1 -1
  13. package/dist/commands/adopt.d.ts.map +1 -1
  14. package/dist/commands/adopt.js +5 -6
  15. package/dist/commands/adopt.js.map +1 -1
  16. package/dist/commands/db.js +3 -3
  17. package/dist/commands/db.js.map +1 -1
  18. package/dist/commands/deploy.d.ts.map +1 -1
  19. package/dist/commands/deploy.js +7 -4
  20. package/dist/commands/deploy.js.map +1 -1
  21. package/dist/commands/dev.d.ts.map +1 -1
  22. package/dist/commands/dev.js +20 -5
  23. package/dist/commands/dev.js.map +1 -1
  24. package/dist/commands/doctor.d.ts.map +1 -1
  25. package/dist/commands/doctor.js +5 -7
  26. package/dist/commands/doctor.js.map +1 -1
  27. package/dist/commands/init.js +1 -1
  28. package/dist/commands/init.js.map +1 -1
  29. package/dist/commands/migrate.d.ts.map +1 -1
  30. package/dist/commands/migrate.js +6 -3
  31. package/dist/commands/migrate.js.map +1 -1
  32. package/dist/commands/push.d.ts.map +1 -1
  33. package/dist/commands/push.js +10 -6
  34. package/dist/commands/push.js.map +1 -1
  35. package/dist/commands/seed.js +2 -2
  36. package/dist/commands/seed.js.map +1 -1
  37. package/dist/dev-compose.d.ts +42 -0
  38. package/dist/dev-compose.d.ts.map +1 -1
  39. package/dist/dev-compose.js +116 -71
  40. package/dist/dev-compose.js.map +1 -1
  41. package/dist/dev-db-reset.d.ts +19 -0
  42. package/dist/dev-db-reset.d.ts.map +1 -0
  43. package/dist/dev-db-reset.js +75 -0
  44. package/dist/dev-db-reset.js.map +1 -0
  45. package/dist/dev-initial-push.d.ts +37 -0
  46. package/dist/dev-initial-push.d.ts.map +1 -0
  47. package/dist/dev-initial-push.js +91 -0
  48. package/dist/dev-initial-push.js.map +1 -0
  49. package/dist/dev-ports.d.ts.map +1 -1
  50. package/dist/dev-ports.js +1 -1
  51. package/dist/dev-ports.js.map +1 -1
  52. package/dist/diff-output.d.ts +2 -2
  53. package/dist/diff-output.d.ts.map +1 -1
  54. package/dist/diff-output.js +1 -1
  55. package/dist/diff-output.js.map +1 -1
  56. package/dist/engine-client.d.ts +5 -1
  57. package/dist/engine-client.d.ts.map +1 -1
  58. package/dist/engine-client.js +8 -6
  59. package/dist/engine-client.js.map +1 -1
  60. package/dist/engine-push-output.d.ts +10 -0
  61. package/dist/engine-push-output.d.ts.map +1 -1
  62. package/dist/engine-push-output.js +12 -0
  63. package/dist/engine-push-output.js.map +1 -1
  64. package/dist/{seed-connection.d.ts → host-database.d.ts} +20 -10
  65. package/dist/host-database.d.ts.map +1 -0
  66. package/dist/{seed-connection.js → host-database.js} +40 -14
  67. package/dist/host-database.js.map +1 -0
  68. package/dist/resolve-target.d.ts +2 -2
  69. package/dist/resolve-target.d.ts.map +1 -1
  70. package/dist/resolve-target.js +15 -11
  71. package/dist/resolve-target.js.map +1 -1
  72. package/dist/retired-no-cache.d.ts +18 -0
  73. package/dist/retired-no-cache.d.ts.map +1 -0
  74. package/dist/retired-no-cache.js +21 -0
  75. package/dist/retired-no-cache.js.map +1 -0
  76. package/dist/self-host-compose.d.ts +6 -0
  77. package/dist/self-host-compose.d.ts.map +1 -1
  78. package/dist/self-host-compose.js +9 -3
  79. package/dist/self-host-compose.js.map +1 -1
  80. package/dist/type-extractor.d.ts.map +1 -1
  81. package/dist/type-extractor.js +31 -25
  82. package/dist/type-extractor.js.map +1 -1
  83. package/package.json +2 -2
  84. package/src/adopt-walkthrough.ts +142 -0
  85. package/src/cli-version-embedded.ts +1 -1
  86. package/src/commands/admin.ts +7 -20
  87. package/src/commands/adopt.ts +5 -6
  88. package/src/commands/db.ts +3 -3
  89. package/src/commands/deploy.ts +7 -4
  90. package/src/commands/dev.ts +22 -6
  91. package/src/commands/doctor.ts +5 -7
  92. package/src/commands/init.ts +1 -1
  93. package/src/commands/migrate.ts +7 -4
  94. package/src/commands/push.ts +28 -10
  95. package/src/commands/seed.ts +2 -2
  96. package/src/dev-compose.ts +166 -77
  97. package/src/dev-db-reset.ts +95 -0
  98. package/src/dev-initial-push.ts +134 -0
  99. package/src/dev-ports.ts +1 -1
  100. package/src/diff-output.ts +2 -2
  101. package/src/engine-client.ts +5 -4
  102. package/src/engine-push-output.ts +19 -0
  103. package/src/{seed-connection.ts → host-database.ts} +42 -12
  104. package/src/resolve-target.ts +20 -14
  105. package/src/retired-no-cache.ts +27 -0
  106. package/src/self-host-compose.ts +10 -3
  107. package/src/type-extractor.ts +39 -42
  108. package/tests/adopt-result.test.ts +27 -0
  109. package/tests/adopt-walkthrough.test.ts +129 -0
  110. package/tests/dev-db-reset.test.ts +162 -0
  111. package/tests/dev-initial-push.test.ts +142 -0
  112. package/tests/engine-push-output.test.ts +30 -1
  113. package/tests/host-connection-targets.test.ts +84 -0
  114. package/tests/{seed-connection.test.ts → host-database.test.ts} +33 -15
  115. package/tests/retired-no-cache.test.ts +46 -0
  116. package/tests/type-extractor.test.ts +80 -0
  117. package/tsconfig.tsbuildinfo +1 -1
  118. package/dist/seed-connection.d.ts.map +0 -1
  119. package/dist/seed-connection.js.map +0 -1
@@ -71,6 +71,8 @@ import {
71
71
  formatEnginePushMessage,
72
72
  parseEngineJsonOutput,
73
73
  parseEnginePushOutput,
74
+ printPushWarnings,
75
+ type EnginePushResult,
74
76
  } from "./engine-push-output.js"
75
77
  import { withAdminRoles } from "./studio-admin-roles.js"
76
78
  import { restoreSystemRelationTargets } from "./restore-system-relation-targets.js"
@@ -78,9 +80,10 @@ import { provisionBucketsFromAst } from "./storage-provision.js"
78
80
  import type { ExtractedSchemaAstV2 } from "./schema-ast-v2.js"
79
81
  import { ensureFirstAdminUserForProject } from "./commands/admin.js"
80
82
  import { publishDevReady } from "./dev-ready-panel.js"
81
-
82
- /** Default host port for compose Postgres when `overrides.engine` is set (devLocal). */
83
- const COMPOSE_DEV_DB_PORT = 54329
83
+ import { exitInitialPushFailed, pushInitialSchema, type InitialPushSteps } from "./dev-initial-push.js"
84
+ import { offerAdoption, unmanagedTables, type AdoptionSteps } from "./adopt-walkthrough.js"
85
+ import { resetDevDatabase } from "./dev-db-reset.js"
86
+ import { hostComposeDbUrl, resolveHostDatabaseUrl } from "./host-database.js"
84
87
 
85
88
  /** Sync optional Docker image pins from config into `.env` (no JWT rotation). */
86
89
  export function syncComposeImagePins(cwd: string, config: SupatypeProjectConfig): void {
@@ -96,6 +99,10 @@ export function syncComposeImagePins(cwd: string, config: SupatypeProjectConfig)
96
99
 
97
100
  export interface DevComposeOptions {
98
101
  watch: boolean
102
+ /** Remove the Postgres data volume before starting, after confirmation. Never implied. */
103
+ resetDb: boolean
104
+ /** The reset was already confirmed on the command line, so do not prompt for it. */
105
+ yes: boolean
99
106
  }
100
107
 
101
108
  /** In-compose Postgres URL (SCRAM; not published to the host). */
@@ -118,22 +125,14 @@ async function resolveDevDbPort(cwd: string): Promise<number> {
118
125
  *
119
126
  * The compose helpers below describe the `db` *container*, on the host at
120
127
  * `SUPATYPE_DEV_DB_PORT`, or in-network at `db:5432`. Neither exists for a project pointed at an
121
- * external database, and passing one produced "pool timed out while waiting for an open connection"
122
- *- a message with nothing in it about the URL being wrong.
128
+ * external database, and passing one produced "pool timed out while waiting for an open connection",
129
+ * a message with nothing in it about the URL being wrong.
123
130
  */
124
131
  function projectDatabaseUrl(cwd: string, config: SupatypeProjectConfig, inNetwork = false): string {
125
132
  if (usesExternalDatabase(config)) return connectionString(config)
126
133
  return inNetwork ? composeDbUrl(cwd) : hostComposeDbUrl(cwd)
127
134
  }
128
135
 
129
- function hostComposeDbUrl(cwd: string): string {
130
- const port = readEnvValue(cwd, "SUPATYPE_DEV_DB_PORT", String(COMPOSE_DEV_DB_PORT))
131
- const user = readEnvValue(cwd, "POSTGRES_USER", "supatype_admin")
132
- const pass = devPostgresPassword(cwd)
133
- const db = readEnvValue(cwd, "POSTGRES_DB", "supatype")
134
- return `postgresql://${user}:${pass}@127.0.0.1:${port}/${db}?sslmode=disable`
135
- }
136
-
137
136
  /**
138
137
  * When `provider: docker` and `overrides.engine` is set, ensure Postgres is published
139
138
  * on the host (SUPATYPE_DEV_DB_PORT) so the local engine binary can connect.
@@ -193,13 +192,12 @@ export async function resolveHostEngineDatabaseUrl(
193
192
  config: SupatypeProjectConfig,
194
193
  explicit?: string,
195
194
  ): Promise<string> {
196
- if (explicit?.trim()) return explicit
197
- if (config.connection?.trim()) return config.connection
198
- if (usesLocalDockerEngineDb(config)) {
195
+ // Published first, when this project's Postgres is the local docker one, so the URL below
196
+ // reaches something. The URL itself comes from the one resolver every host-side command uses.
197
+ if (usesLocalDockerEngineDb(config, explicit)) {
199
198
  await ensureDockerDbPublishedForHostEngine(cwd, config)
200
- return hostComposeDbUrl(cwd)
201
199
  }
202
- return connectionString(config)
200
+ return resolveHostDatabaseUrl(cwd, config, { connection: explicit, allowDerived: true }).dsn
203
201
  }
204
202
 
205
203
  /**
@@ -763,7 +761,7 @@ async function runComposeSchemaPush(
763
761
  const pgSchema = config.schema?.pg_schema ?? "public"
764
762
  const sources = writeSchemaSourcePushArtifacts(cwd)
765
763
  try {
766
- await engineRequest("/push", {
764
+ const result = await engineRequest<EnginePushResult>("/push", {
767
765
  ast,
768
766
  database_url: projectDatabaseUrl(cwd, config),
769
767
  schema: pgSchema,
@@ -775,6 +773,7 @@ async function runComposeSchemaPush(
775
773
  }
776
774
  : {}),
777
775
  })
776
+ printPushWarnings(result)
778
777
  } catch (err) {
779
778
  _lastFailedAst = astJson
780
779
  throw err
@@ -898,6 +897,7 @@ async function runComposeEnginePush(
898
897
  if (exitStatus === 0) {
899
898
  if (pushResult) {
900
899
  console.log(`[supatype] ${formatEnginePushMessage(pushResult)}`)
900
+ printPushWarnings(pushResult)
901
901
  } else {
902
902
  console.log("[supatype] Schema applied.")
903
903
  }
@@ -906,13 +906,38 @@ async function runComposeEnginePush(
906
906
  return { status: exitStatus, output }
907
907
  }
908
908
 
909
- async function runComposeEngineDiff(
909
+ /**
910
+ * One schema-engine subcommand in the compose `tools` profile, against the stack's own database.
911
+ *
912
+ * In a container, so it reaches Postgres at the compose-internal address and needs nothing
913
+ * published to the host. That is what a host-side `supatype adopt` got wrong on a docker project
914
+ * (supatype#85), and why the push walkthrough runs adopt this way instead.
915
+ */
916
+ /** One engine run: its exit, what it printed on stdout alone, and everything it printed. */
917
+ export interface EngineRun {
918
+ status: number
919
+ stdout: string
920
+ output: string
921
+ }
922
+
923
+ /**
924
+ * The adopt result from one engine run, or null when there is none to read.
925
+ *
926
+ * From stdout alone. The engine prints the preview as multi-line JSON, which only parses as a
927
+ * whole, and with stderr joined on (a compose warning about an unset variable, an engine log line)
928
+ * it did not parse at all, so a preview that worked was reported as a failed adopt.
929
+ */
930
+ export function adoptResultFrom(run: EngineRun): AdoptResult | null {
931
+ return run.status === 0 ? parseEngineJsonOutput<AdoptResult>(run.stdout) : null
932
+ }
933
+
934
+ async function runComposeEngineCommand(
910
935
  paths: SelfHostComposePaths,
911
936
  cwd: string,
912
937
  composeProject: string,
913
938
  config: SupatypeProjectConfig,
914
- pgSchema: string,
915
- ): Promise<{ status: number; output: string; diff: DiffResult | null }> {
939
+ command: readonly string[],
940
+ ): Promise<EngineRun> {
916
941
  const envFile = resolve(cwd, ".env")
917
942
  const composeArgs = ["compose", "--progress", "quiet"]
918
943
  if (composeProject) composeArgs.push("-p", composeProject)
@@ -927,33 +952,85 @@ async function runComposeEngineDiff(
927
952
  "run",
928
953
  "--rm",
929
954
  "schema-engine",
930
- "diff",
955
+ ...command,
931
956
  "-i",
932
957
  "/project/.supatype/schema.ast.json",
933
958
  "--database-url",
934
959
  projectDatabaseUrl(cwd, config, true),
935
960
  "--schema",
936
- pgSchema,
961
+ config.schema?.pg_schema ?? "public",
937
962
  )
938
- const diffEnv: NodeJS.ProcessEnv = {
939
- ...process.env,
940
- COMPOSE_PROGRESS: "quiet",
941
- }
963
+ const env: NodeJS.ProcessEnv = { ...process.env, COMPOSE_PROGRESS: "quiet" }
942
964
  const engineImage = await schemaEngineImageForPush(config)
943
- if (engineImage) {
944
- diffEnv.SUPATYPE_ENGINE_IMAGE = engineImage
945
- }
965
+ if (engineImage) env.SUPATYPE_ENGINE_IMAGE = engineImage
946
966
  const result = spawnSync("docker", composeArgs, {
947
967
  cwd,
948
968
  encoding: "utf8",
949
969
  maxBuffer: 10 * 1024 * 1024,
950
- env: diffEnv,
970
+ env,
951
971
  })
952
- const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim()
953
- const exitStatus = result.status ?? 1
954
- const diff = parseEngineJsonOutput<DiffResult>(output)
972
+ return {
973
+ status: result.status ?? 1,
974
+ stdout: result.stdout ?? "",
975
+ output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim(),
976
+ }
977
+ }
978
+
979
+ async function runComposeEngineDiff(
980
+ paths: SelfHostComposePaths,
981
+ cwd: string,
982
+ composeProject: string,
983
+ config: SupatypeProjectConfig,
984
+ ): Promise<{ status: number; output: string; diff: DiffResult | null }> {
985
+ const result = await runComposeEngineCommand(paths, cwd, composeProject, config, ["diff"])
986
+ return { ...result, diff: parseEngineJsonOutput<DiffResult>(result.output) }
987
+ }
988
+
989
+ /** Adoption against a docker project's own database, for the push walkthrough. */
990
+ export function dockerAdoptionSteps(cwd: string, config: SupatypeProjectConfig): AdoptionSteps {
991
+ return {
992
+ preview: async () => (await adoptSchemaDocker(cwd, config, false)).stampStatements ?? [],
993
+ apply: async () => (await adoptSchemaDocker(cwd, config, true)).stamped ?? 0,
994
+ }
995
+ }
955
996
 
956
- return { status: exitStatus, output, diff }
997
+ /** What `adopt` reports, previewing or applying. */
998
+ export interface AdoptResult {
999
+ status?: string
1000
+ stampStatements?: string[]
1001
+ stamped?: number
1002
+ }
1003
+
1004
+ /**
1005
+ * Adopt on a docker project's own database: the stamp preview, or with `yes`, the stamps applied.
1006
+ *
1007
+ * Through the compose schema-engine, or the local engine binary when `overrides.engine` is set,
1008
+ * the same way `diffSchemaDocker` reaches the database. The stack's database must be running,
1009
+ * which it is whenever a push has just been refused by it.
1010
+ */
1011
+ export async function adoptSchemaDocker(
1012
+ cwd: string,
1013
+ config: SupatypeProjectConfig,
1014
+ yes: boolean,
1015
+ ): Promise<AdoptResult> {
1016
+ const project = composeProjectName(config.project.name)
1017
+ if (hasEngineOverride(config)) {
1018
+ await ensureDockerDbPublishedForHostEngine(cwd, config, { intro: "Adopt" })
1019
+ await ensureEngine()
1020
+ return engineRequest<AdoptResult>("/adopt", {
1021
+ ast: withPublishing(loadSchemaAst(schemaPathFromProject(config, cwd), cwd), config),
1022
+ database_url: projectDatabaseUrl(cwd, config),
1023
+ schema: config.schema?.pg_schema ?? "public",
1024
+ yes,
1025
+ })
1026
+ }
1027
+ const paths = writeSelfHostCompose(cwd, config, { devLocal: true })
1028
+ const result = await runComposeEngineCommand(paths, cwd, project, config, yes ? ["adopt", "--yes"] : ["adopt"])
1029
+ const parsed = adoptResultFrom(result)
1030
+ if (parsed === null) {
1031
+ throw new Error(filterComposeNoise(result.output) || `Engine adopt failed (exit ${result.status})`)
1032
+ }
1033
+ return parsed
957
1034
  }
958
1035
 
959
1036
  /**
@@ -1001,11 +1078,11 @@ export async function diffSchemaDocker(cwd: string, config: SupatypeProjectConfi
1001
1078
  const astPath = join(supatypeDir, "schema.ast.json")
1002
1079
  writeFileSync(astPath, JSON.stringify(ast))
1003
1080
 
1004
- let result = await runComposeEngineDiff(paths, cwd, project, config, pgSchema)
1081
+ let result = await runComposeEngineDiff(paths, cwd, project, config)
1005
1082
  // Windows Docker bind mounts can lag briefly after the host write.
1006
1083
  if (result.status !== 0) {
1007
1084
  await new Promise((r) => setTimeout(r, 250))
1008
- result = await runComposeEngineDiff(paths, cwd, project, config, pgSchema)
1085
+ result = await runComposeEngineDiff(paths, cwd, project, config)
1009
1086
  }
1010
1087
  if (result.status !== 0) {
1011
1088
  const detail = filterComposeNoise(result.output) || result.output
@@ -1079,6 +1156,41 @@ export async function pushSchemaDocker(cwd: string, config: SupatypeProjectConfi
1079
1156
  console.log("[supatype] Schema pushed.")
1080
1157
  }
1081
1158
 
1159
+ /**
1160
+ * The first push of a `dev` session. A retry only ever brings Postgres back up: it never removes
1161
+ * a volume, so a refused push leaves the developer's database exactly as it found it.
1162
+ */
1163
+ async function applyInitialSchema(
1164
+ cwd: string,
1165
+ config: SupatypeProjectConfig,
1166
+ paths: SelfHostComposePaths,
1167
+ schemaPath: string,
1168
+ project: string,
1169
+ brand: DockerBrandOptions,
1170
+ ): Promise<void> {
1171
+ const steps: InitialPushSteps = {
1172
+ push: () => runComposeSchemaPush(cwd, config, paths, schemaPath, project),
1173
+ recoverDatabase: () => startComposeDatabase(config, paths, cwd, project, brand, undefined, endDevSession),
1174
+ dumpLogs: (reason) => dumpComposeDbLogs(paths, cwd, project, reason),
1175
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
1176
+ }
1177
+ let outcome = await pushInitialSchema(steps)
1178
+ if (outcome.kind === "refused" && outcome.reason === "unmanaged-tables") {
1179
+ // Offered rather than only named: the stack's database is up, so adoption can run against it
1180
+ // here, and a push straight after it is the one that was just refused.
1181
+ const tables = unmanagedTables(outcome.message) ?? []
1182
+ const adopted = await offerAdoption(tables, dockerAdoptionSteps(cwd, config), {
1183
+ yes: false,
1184
+ retry: "supatype dev",
1185
+ })
1186
+ if (adopted === "adopted") outcome = await pushInitialSchema(steps)
1187
+ }
1188
+ if (outcome.kind === "applied") return
1189
+ // Before the message, so it reaches the real terminal rather than a TUI that is going away.
1190
+ endDevSession()
1191
+ exitInitialPushFailed(outcome, brand)
1192
+ }
1193
+
1082
1194
  export async function runDevCompose(cwd: string, config: SupatypeProjectConfig, opts: DevComposeOptions): Promise<void> {
1083
1195
  if (resolveRuntimeProvider(config) !== "docker") {
1084
1196
  throw new Error("runDevCompose requires provider: docker")
@@ -1150,6 +1262,21 @@ export async function runDevCompose(cwd: string, config: SupatypeProjectConfig,
1150
1262
  await recoverStaleDevSession(cwd)
1151
1263
  await handleComposeProjectRename(cwd, config.project.name, paths)
1152
1264
 
1265
+ // Only on request, and before Postgres starts, so it comes up on an empty volume.
1266
+ if (opts.resetDb) {
1267
+ await resetDevDatabase(
1268
+ {
1269
+ composePath: paths.composePath,
1270
+ cwd,
1271
+ project,
1272
+ external: usesExternalDatabase(config),
1273
+ brand: devBrand,
1274
+ onFailure: endDevSession,
1275
+ },
1276
+ { yes: opts.yes },
1277
+ )
1278
+ }
1279
+
1153
1280
  if (!usesExternalDatabase(config)) {
1154
1281
  console.log("[supatype] Bringing up Postgres (compose db)...")
1155
1282
  }
@@ -1163,45 +1290,7 @@ export async function runDevCompose(cwd: string, config: SupatypeProjectConfig,
1163
1290
 
1164
1291
  // A: apply schema before realtime (and the rest of the stack) starts decoding WAL.
1165
1292
  const schemaPath = schemaPathFromProject(config, cwd)
1166
- {
1167
- const maxAttempts = 3
1168
- let lastErr: unknown
1169
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1170
- try {
1171
- await runComposeSchemaPush(cwd, config, paths, schemaPath, project)
1172
- lastErr = undefined
1173
- break
1174
- } catch (e: unknown) {
1175
- lastErr = e
1176
- console.error(
1177
- `[supatype] Initial schema push failed (attempt ${attempt}/${maxAttempts}):`,
1178
- (e as Error).message,
1179
- )
1180
- dumpComposeDbLogs(paths, cwd, project, `schema push attempt ${attempt}/${maxAttempts}`)
1181
- if (attempt < maxAttempts) {
1182
- // Only for a database Supatype created. Tearing down an external one is not ours to do,
1183
- // and `down -v` would destroy the stack's other volumes for a failure that was never
1184
- // about Postgres.
1185
- if (!usesExternalDatabase(config)) {
1186
- console.log("[supatype] Resetting Postgres after failed schema push...")
1187
- runDockerCompose(paths.composePath, ["down", "-v"], cwd, project, {
1188
- quiet: true,
1189
- brand: devBrand,
1190
- })
1191
- await startComposeDatabase(config, paths, cwd, project, devBrand)
1192
- }
1193
- await new Promise((r) => setTimeout(r, 3000 * attempt))
1194
- }
1195
- }
1196
- }
1197
- if (lastErr) {
1198
- dumpComposeDbLogs(paths, cwd, project, "initial schema push exhausted")
1199
- endDevSession()
1200
- throw new Error(
1201
- `Initial schema push failed after ${maxAttempts} attempts: ${(lastErr as Error).message}`,
1202
- )
1203
- }
1204
- }
1293
+ await applyInitialSchema(cwd, config, paths, schemaPath, project, devBrand)
1205
1294
 
1206
1295
  console.log("[supatype] Bringing up Docker Compose services...")
1207
1296
  const upStatus = runDockerCompose(paths.composePath, ["up", "-d"], cwd, project, {
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `supatype dev --reset-db`: start again from an empty local database, on request only.
3
+ *
4
+ * The one place `dev` removes data, and it removes exactly one volume. Storage and the cache keep
5
+ * the developer's uploaded files and warm keys, and nothing about a database reset is a reason to
6
+ * lose those, which is what `docker compose down -v` used to do whenever a push failed.
7
+ *
8
+ * Confirmed by a prompt that names the volume. With no TTY there is nobody to answer it, so the
9
+ * flag is refused unless `--yes` says the caller has already decided.
10
+ */
11
+ import { spawnSync } from "node:child_process"
12
+ import type { DockerBrandOptions } from "./docker-runtime.js"
13
+ import { DB_VOLUME_KEY, exitComposeFailed, runDockerCompose } from "./self-host-compose.js"
14
+ import { confirm } from "./ui/confirm.js"
15
+ import { fatalError } from "./ui/fatal.js"
16
+ import { isInteractive } from "./ui/interactive.js"
17
+
18
+ export interface DevDbResetTarget {
19
+ composePath: string
20
+ cwd: string
21
+ /** The compose project name, which Docker prefixes every volume with. */
22
+ project: string
23
+ /** True when the project points at a database Supatype does not run. */
24
+ external: boolean
25
+ brand?: DockerBrandOptions
26
+ /** Runs before any exit, so the message reaches the terminal rather than the dev TUI. */
27
+ onFailure?: () => void
28
+ }
29
+
30
+ /** The Docker volume holding this project's Postgres data. */
31
+ export function devDbVolumeName(composeProject: string): string {
32
+ return `${composeProject}_${DB_VOLUME_KEY}`
33
+ }
34
+
35
+ function brandOpts(target: DevDbResetTarget): { brand?: DockerBrandOptions } {
36
+ return target.brand !== undefined ? { brand: target.brand } : {}
37
+ }
38
+
39
+ function fail(target: DevDbResetTarget, message: string, hints: string[]): never {
40
+ target.onFailure?.()
41
+ fatalError(message, hints, brandOpts(target))
42
+ }
43
+
44
+ function volumeExists(volume: string): boolean {
45
+ return spawnSync("docker", ["volume", "inspect", volume], { encoding: "utf8" }).status === 0
46
+ }
47
+
48
+ /** Returns once the developer has agreed to lose the volume, and exits otherwise. */
49
+ async function requireApproval(target: DevDbResetTarget, volume: string, yes: boolean): Promise<void> {
50
+ if (yes) return
51
+ if (!isInteractive()) {
52
+ fail(target, `--reset-db would remove the Postgres data volume ${volume}, and there is no terminal to confirm it.`, [
53
+ "Re-run with --yes to remove it without a prompt. Nothing was removed.",
54
+ ])
55
+ }
56
+ const approved = await confirm(
57
+ `Remove the Postgres data volume ${volume}? Every row in the local database is deleted. Storage and other volumes are kept.`,
58
+ { default: false },
59
+ )
60
+ if (!approved) fail(target, "Reset cancelled. Nothing was removed.", [])
61
+ }
62
+
63
+ function removeDbVolume(target: DevDbResetTarget, volume: string): void {
64
+ // The volume cannot be removed while a container holds it, so the db container goes first, and
65
+ // alone. No `-v` anywhere: the one volume that goes is named explicitly below.
66
+ const rm = runDockerCompose(target.composePath, ["rm", "--stop", "--force", "db"], target.cwd, target.project, {
67
+ quiet: true,
68
+ ...brandOpts(target),
69
+ })
70
+ if (rm !== 0) {
71
+ target.onFailure?.()
72
+ exitComposeFailed(rm, "Could not stop the Postgres container. Nothing was removed.", target.brand)
73
+ }
74
+ const removed = spawnSync("docker", ["volume", "rm", volume], { encoding: "utf8" })
75
+ if (removed.status !== 0) {
76
+ fail(target, `Could not remove the Postgres data volume ${volume}.`, [String(removed.stderr ?? "").trim()])
77
+ }
78
+ }
79
+
80
+ /** Remove the Postgres data volume, and nothing else, once the developer has agreed to it. */
81
+ export async function resetDevDatabase(target: DevDbResetTarget, opts: { yes: boolean }): Promise<void> {
82
+ if (target.external) {
83
+ fail(target, "--reset-db only resets a database Supatype runs.", [
84
+ "This project points at an external database (database.external). Nothing was removed.",
85
+ ])
86
+ }
87
+ const volume = devDbVolumeName(target.project)
88
+ if (!volumeExists(volume)) {
89
+ console.log(`[supatype] No Postgres data volume ${volume} yet, nothing to reset.`)
90
+ return
91
+ }
92
+ await requireApproval(target, volume, opts.yes)
93
+ removeDbVolume(target, volume)
94
+ console.log(`[supatype] Removed the Postgres data volume ${volume}. Postgres starts empty.`)
95
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * The first schema push of `supatype dev`, and what a failed one is allowed to do.
3
+ *
4
+ * This loop used to answer every failure the same way: `docker compose down -v`, start Postgres
5
+ * again, push again. `-v` removes every volume in the stack, so a push the engine refused on
6
+ * purpose (a table Supatype does not manage, a destructive change) cost the developer their local
7
+ * database and their uploaded files, and the second attempt then succeeded against an empty one.
8
+ * A refusal is deterministic. The same schema against the same database is refused again, and the
9
+ * only thing a reset changed was that there was no longer anything to refuse.
10
+ *
11
+ * So a failure is classified before anything else happens. A database that is not reachable yet is
12
+ * retried, and the retry never removes anything. Everything else is the engine's answer, and `dev`
13
+ * stops with it. Resetting the database is `supatype dev --reset-db`, which is asked for, confirmed,
14
+ * and removes only Postgres's volume.
15
+ */
16
+ import { unmanagedTables } from "./adopt-walkthrough.js"
17
+ import { fatalError } from "./ui/fatal.js"
18
+ import type { DockerBrandOptions } from "./docker-runtime.js"
19
+
20
+ /** What one failed push means for the next step. */
21
+ export type PushFailureKind = "transient" | "unmanaged-tables" | "engine"
22
+
23
+ /**
24
+ * How the initial push ended.
25
+ *
26
+ * A refusal is its own outcome rather than a thrown error so a caller can act on it: the
27
+ * unmanaged-tables case is the one an adopt walkthrough will pick up.
28
+ */
29
+ export type InitialPushOutcome =
30
+ | { kind: "applied" }
31
+ | { kind: "refused"; reason: Exclude<PushFailureKind, "transient">; message: string }
32
+ | { kind: "exhausted"; attempts: number; message: string }
33
+
34
+ export type InitialPushFailure = Exclude<InitialPushOutcome, { kind: "applied" }>
35
+
36
+ export interface InitialPushSteps {
37
+ /** One push. Throws with the engine's output when it fails. */
38
+ push: () => Promise<void>
39
+ /** Start Postgres if it is not running and wait for it. Must never remove anything. */
40
+ recoverDatabase: () => Promise<void>
41
+ /** Capture the database logs while they still describe the failure. */
42
+ dumpLogs: (reason: string) => void
43
+ sleep: (ms: number) => Promise<void>
44
+ }
45
+
46
+ /**
47
+ * Output that means "Postgres is not reachable yet", not "the schema is wrong".
48
+ *
49
+ * The same vocabulary as `packages/realtime/src/db-retry.ts` and its storage twin, which match a
50
+ * driver's error codes. The engine reports through its exit output rather than an error object, so
51
+ * here the codes and their messages are matched as text. Narrow on purpose: whatever matches is
52
+ * retried, and a loose pattern would turn a refusal back into the retry that hid it.
53
+ */
54
+ const TRANSIENT_PATTERNS: readonly RegExp[] = [
55
+ /\b(ECONNREFUSED|ECONNRESET|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|EPIPE|EAI_AGAIN)\b/,
56
+ /connection (refused|reset)/i,
57
+ /connection terminated unexpectedly/i,
58
+ /the database system is (starting up|shutting down|in recovery)/i,
59
+ /too many clients already/i,
60
+ /timeout expired|timed out/i,
61
+ ]
62
+
63
+ function classifyPushFailure(message: string): PushFailureKind {
64
+ // Checked first: the refusal is long prose, and it must not be retried because a word in it
65
+ // happens to look like a connection error. Read from the engine's JSON reason, with its wording
66
+ // only as the fallback for an engine that predates the JSON.
67
+ if (unmanagedTables(message) !== null) return "unmanaged-tables"
68
+ if (TRANSIENT_PATTERNS.some((pattern) => pattern.test(message))) return "transient"
69
+ return "engine"
70
+ }
71
+
72
+ /** Run one push, returning the failure message instead of throwing it. */
73
+ async function attemptPush(push: () => Promise<void>): Promise<string | null> {
74
+ try {
75
+ await push()
76
+ return null
77
+ } catch (err: unknown) {
78
+ return err instanceof Error ? err.message : String(err)
79
+ }
80
+ }
81
+
82
+ /** Push the schema, retrying only while Postgres is unreachable. */
83
+ export async function pushInitialSchema(
84
+ steps: InitialPushSteps,
85
+ maxAttempts = 3,
86
+ ): Promise<InitialPushOutcome> {
87
+ let message = ""
88
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
89
+ const failure = await attemptPush(steps.push)
90
+ if (failure === null) return { kind: "applied" }
91
+ message = failure
92
+ console.error(`[supatype] Initial schema push failed (attempt ${attempt}/${maxAttempts}):`, failure)
93
+ steps.dumpLogs(`schema push attempt ${attempt}/${maxAttempts}`)
94
+
95
+ const kind = classifyPushFailure(failure)
96
+ if (kind !== "transient") return { kind: "refused", reason: kind, message }
97
+ if (attempt < maxAttempts) {
98
+ await steps.recoverDatabase()
99
+ await steps.sleep(3000 * attempt)
100
+ }
101
+ }
102
+ return { kind: "exhausted", attempts: maxAttempts, message }
103
+ }
104
+
105
+ /** Every refusal ends with this, because the old loop taught people a failure meant data loss. */
106
+ const DATABASE_KEPT = "Your local database was left as it was."
107
+
108
+ /** End `dev` with what the engine said, and what to do about it. */
109
+ export function exitInitialPushFailed(failure: InitialPushFailure, brand?: DockerBrandOptions): never {
110
+ const opts = { ...(brand !== undefined && { brand }) }
111
+ if (failure.kind === "exhausted") {
112
+ fatalError(
113
+ `Initial schema push failed after ${failure.attempts} attempts: ${failure.message}`,
114
+ ["Postgres did not become reachable. Check logs: supatype self-host compose logs db", DATABASE_KEPT],
115
+ opts,
116
+ )
117
+ }
118
+ if (failure.reason === "unmanaged-tables") {
119
+ fatalError(
120
+ "The engine refused the schema push. Nothing was applied.",
121
+ [
122
+ failure.message,
123
+ "Run `supatype adopt` to bring those tables under management, then run `supatype dev` again.",
124
+ DATABASE_KEPT,
125
+ ],
126
+ opts,
127
+ )
128
+ }
129
+ fatalError(
130
+ "The engine refused the schema push.",
131
+ [failure.message, "Fix the schema and run `supatype dev` again.", DATABASE_KEPT],
132
+ opts,
133
+ )
134
+ }
package/src/dev-ports.ts CHANGED
@@ -11,6 +11,7 @@ import { isPortInUse } from "./postgres-ctl.js"
11
11
  import { readEnvInt, upsertEnvFile } from "./env-file.js"
12
12
  import { isInteractive } from "./ui/interactive.js"
13
13
  import { fatalError } from "./ui/fatal.js"
14
+ import { COMPOSE_DEV_DB_PORT } from "./host-database.js"
14
15
 
15
16
  const MIN_PORT = 1024
16
17
  const MAX_PORT = 65535
@@ -240,7 +241,6 @@ async function promptPortConflictWithoutPersist(
240
241
  return port
241
242
  }
242
243
 
243
- const COMPOSE_DEV_DB_PORT = 54329
244
244
 
245
245
  function devDbConnectionUrl(port: number): string {
246
246
  return `postgresql://supatype_admin:postgres@localhost:${port}/supatype?sslmode=disable`
@@ -40,8 +40,8 @@ export function formatOperation(op: Operation): string {
40
40
  return kind
41
41
  }
42
42
 
43
- /** Print engine diff warnings before the operation list. */
44
- export function printDiffWarnings(diff: DiffResult): void {
43
+ /** Print engine warnings: a diff's before its operation list, or a push's once it has run. */
44
+ export function printDiffWarnings(diff: Pick<DiffResult, "warnings">): void {
45
45
  const warnings = diff.warnings ?? []
46
46
  if (warnings.length === 0) return
47
47
  console.log(`\n${warnings.length} warning(s):\n`)
@@ -68,6 +68,8 @@ export class EngineError extends Error {
68
68
  message: string,
69
69
  public readonly endpoint: string,
70
70
  public readonly exitCode: number | null,
71
+ /** What the engine printed on stdout. A refused push puts its machine-readable reason there. */
72
+ public readonly stdout = "",
71
73
  ) {
72
74
  super(message)
73
75
  this.name = "EngineError"
@@ -221,6 +223,7 @@ export async function engineRequest<T = unknown>(
221
223
  `Engine ${endpoint} failed (exit ${result.status}): ${stderr}`,
222
224
  endpoint,
223
225
  result.status,
226
+ result.stdout ?? "",
224
227
  )
225
228
  }
226
229
 
@@ -316,14 +319,12 @@ function endpointToArgs(
316
319
 
317
320
  case "/doctor": {
318
321
  const strict = body["strict"] ? ["--strict"] : []
319
- const noCache = body["no_cache"] ? ["--no-cache"] : []
320
- return ["doctor", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...strict, ...noCache]
322
+ return ["doctor", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...strict]
321
323
  }
322
324
 
323
325
  case "/adopt": {
324
326
  const yes = body["yes"] ? ["--yes"] : []
325
- const noCache = body["no_cache"] ? ["--no-cache"] : []
326
- return ["adopt", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...yes, ...noCache]
327
+ return ["adopt", "--input", reqFile, "--database-url", dbUrl, "--schema", schema, ...yes]
327
328
  }
328
329
 
329
330
  case "/validate":