@c9up/atlas 0.1.19 → 0.2.1

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 (250) hide show
  1. package/README.md +63 -14
  2. package/db.darwin-arm64.node +0 -0
  3. package/db.darwin-x64.node +0 -0
  4. package/db.linux-arm64-gnu.node +0 -0
  5. package/db.linux-x64-gnu.node +0 -0
  6. package/db.win32-x64-msvc.node +0 -0
  7. package/dist/AtlasProvider.d.ts +66 -7
  8. package/dist/AtlasProvider.d.ts.map +1 -1
  9. package/dist/AtlasProvider.js +205 -39
  10. package/dist/AtlasProvider.js.map +1 -1
  11. package/dist/BaseEntity.d.ts +181 -5
  12. package/dist/BaseEntity.d.ts.map +1 -1
  13. package/dist/BaseEntity.js +339 -33
  14. package/dist/BaseEntity.js.map +1 -1
  15. package/dist/BaseModel.d.ts +127 -0
  16. package/dist/BaseModel.d.ts.map +1 -0
  17. package/dist/BaseModel.js +250 -0
  18. package/dist/BaseModel.js.map +1 -0
  19. package/dist/BaseRepository.d.ts +81 -15
  20. package/dist/BaseRepository.d.ts.map +1 -1
  21. package/dist/BaseRepository.js +1433 -387
  22. package/dist/BaseRepository.js.map +1 -1
  23. package/dist/ConnectionManager.d.ts +106 -0
  24. package/dist/ConnectionManager.d.ts.map +1 -0
  25. package/dist/ConnectionManager.js +228 -0
  26. package/dist/ConnectionManager.js.map +1 -0
  27. package/dist/ModelQuery.d.ts +577 -41
  28. package/dist/ModelQuery.d.ts.map +1 -1
  29. package/dist/ModelQuery.js +2188 -291
  30. package/dist/ModelQuery.js.map +1 -1
  31. package/dist/Transaction.d.ts +71 -1
  32. package/dist/Transaction.d.ts.map +1 -1
  33. package/dist/Transaction.js +138 -24
  34. package/dist/Transaction.js.map +1 -1
  35. package/dist/adapters/NapiDbAdapter.d.ts +44 -4
  36. package/dist/adapters/NapiDbAdapter.d.ts.map +1 -1
  37. package/dist/adapters/NapiDbAdapter.js +131 -13
  38. package/dist/adapters/NapiDbAdapter.js.map +1 -1
  39. package/dist/console/contract.d.ts +62 -0
  40. package/dist/console/contract.d.ts.map +1 -0
  41. package/dist/console/contract.js +38 -0
  42. package/dist/console/contract.js.map +1 -0
  43. package/dist/console/factoryCommands.d.ts +23 -0
  44. package/dist/console/factoryCommands.d.ts.map +1 -0
  45. package/dist/console/factoryCommands.js +62 -0
  46. package/dist/console/factoryCommands.js.map +1 -0
  47. package/dist/console/migrationCommands.d.ts +78 -0
  48. package/dist/console/migrationCommands.d.ts.map +1 -0
  49. package/dist/console/migrationCommands.js +327 -0
  50. package/dist/console/migrationCommands.js.map +1 -0
  51. package/dist/console/schemaCheckCommand.d.ts +11 -17
  52. package/dist/console/schemaCheckCommand.d.ts.map +1 -1
  53. package/dist/console/schemaCheckCommand.js +21 -15
  54. package/dist/console/schemaCheckCommand.js.map +1 -1
  55. package/dist/console/schemaDumpCommand.d.ts +30 -0
  56. package/dist/console/schemaDumpCommand.d.ts.map +1 -0
  57. package/dist/console/schemaDumpCommand.js +69 -0
  58. package/dist/console/schemaDumpCommand.js.map +1 -0
  59. package/dist/console/schemaGenerateCommand.d.ts +100 -0
  60. package/dist/console/schemaGenerateCommand.d.ts.map +1 -0
  61. package/dist/console/schemaGenerateCommand.js +246 -0
  62. package/dist/console/schemaGenerateCommand.js.map +1 -0
  63. package/dist/console/seederCommands.d.ts +46 -0
  64. package/dist/console/seederCommands.d.ts.map +1 -0
  65. package/dist/console/seederCommands.js +136 -0
  66. package/dist/console/seederCommands.js.map +1 -0
  67. package/dist/decorators/entity.d.ts +50 -8
  68. package/dist/decorators/entity.d.ts.map +1 -1
  69. package/dist/decorators/entity.js +42 -2
  70. package/dist/decorators/entity.js.map +1 -1
  71. package/dist/decorators/hooks.d.ts +3 -3
  72. package/dist/decorators/hooks.d.ts.map +1 -1
  73. package/dist/decorators/hooks.js.map +1 -1
  74. package/dist/events.d.ts +69 -0
  75. package/dist/events.d.ts.map +1 -0
  76. package/dist/events.js +82 -0
  77. package/dist/events.js.map +1 -0
  78. package/dist/factories.d.ts +8 -0
  79. package/dist/factories.d.ts.map +1 -0
  80. package/dist/factories.js +8 -0
  81. package/dist/factories.js.map +1 -0
  82. package/dist/index.d.ts +15 -5
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +14 -3
  85. package/dist/index.js.map +1 -1
  86. package/dist/lucid-schema.d.ts +15 -0
  87. package/dist/lucid-schema.d.ts.map +1 -0
  88. package/dist/lucid-schema.js +16 -0
  89. package/dist/lucid-schema.js.map +1 -0
  90. package/dist/metadata-keys.d.ts +3 -2
  91. package/dist/metadata-keys.d.ts.map +1 -1
  92. package/dist/naming/NamingStrategy.d.ts +7 -0
  93. package/dist/naming/NamingStrategy.d.ts.map +1 -1
  94. package/dist/naming/NamingStrategy.js +16 -0
  95. package/dist/naming/NamingStrategy.js.map +1 -1
  96. package/dist/orm.d.ts +14 -0
  97. package/dist/orm.d.ts.map +1 -0
  98. package/dist/orm.js +14 -0
  99. package/dist/orm.js.map +1 -0
  100. package/dist/query/DatabaseQueryBuilder.d.ts +557 -0
  101. package/dist/query/DatabaseQueryBuilder.d.ts.map +1 -0
  102. package/dist/query/DatabaseQueryBuilder.js +1798 -0
  103. package/dist/query/DatabaseQueryBuilder.js.map +1 -0
  104. package/dist/query/DmlBuilder.d.ts +62 -0
  105. package/dist/query/DmlBuilder.d.ts.map +1 -0
  106. package/dist/query/DmlBuilder.js +84 -0
  107. package/dist/query/DmlBuilder.js.map +1 -0
  108. package/dist/query/QueryBuilder.d.ts +5 -0
  109. package/dist/query/QueryBuilder.d.ts.map +1 -1
  110. package/dist/query/QueryBuilder.js +7 -0
  111. package/dist/query/QueryBuilder.js.map +1 -1
  112. package/dist/query/RawQueryBuilder.d.ts +47 -0
  113. package/dist/query/RawQueryBuilder.d.ts.map +1 -0
  114. package/dist/query/RawQueryBuilder.js +138 -0
  115. package/dist/query/RawQueryBuilder.js.map +1 -0
  116. package/dist/query/interpolate.d.ts +45 -0
  117. package/dist/query/interpolate.d.ts.map +1 -0
  118. package/dist/query/interpolate.js +51 -0
  119. package/dist/query/interpolate.js.map +1 -0
  120. package/dist/query/native.d.ts +8 -0
  121. package/dist/query/native.d.ts.map +1 -1
  122. package/dist/query/native.js +14 -0
  123. package/dist/query/native.js.map +1 -1
  124. package/dist/query/operators.d.ts +4 -0
  125. package/dist/query/operators.d.ts.map +1 -0
  126. package/dist/query/operators.js +27 -0
  127. package/dist/query/operators.js.map +1 -0
  128. package/dist/schema/Migration.d.ts +50 -3
  129. package/dist/schema/Migration.d.ts.map +1 -1
  130. package/dist/schema/Migration.js +60 -24
  131. package/dist/schema/Migration.js.map +1 -1
  132. package/dist/schema/MigrationRunner.d.ts +95 -34
  133. package/dist/schema/MigrationRunner.d.ts.map +1 -1
  134. package/dist/schema/MigrationRunner.js +523 -68
  135. package/dist/schema/MigrationRunner.js.map +1 -1
  136. package/dist/schema/Schema.d.ts +114 -0
  137. package/dist/schema/Schema.d.ts.map +1 -1
  138. package/dist/schema/Schema.js +272 -3
  139. package/dist/schema/Schema.js.map +1 -1
  140. package/dist/schema/SchemaDumper.d.ts +121 -0
  141. package/dist/schema/SchemaDumper.d.ts.map +1 -0
  142. package/dist/schema/SchemaDumper.js +365 -0
  143. package/dist/schema/SchemaDumper.js.map +1 -0
  144. package/dist/schema/Seeder.d.ts +13 -0
  145. package/dist/schema/Seeder.d.ts.map +1 -1
  146. package/dist/schema/Seeder.js +28 -5
  147. package/dist/schema/Seeder.js.map +1 -1
  148. package/dist/schema/TableBuilder.d.ts +274 -16
  149. package/dist/schema/TableBuilder.d.ts.map +1 -1
  150. package/dist/schema/TableBuilder.js +656 -52
  151. package/dist/schema/TableBuilder.js.map +1 -1
  152. package/dist/schema/catalog.d.ts +71 -0
  153. package/dist/schema/catalog.d.ts.map +1 -0
  154. package/dist/schema/catalog.js +158 -0
  155. package/dist/schema/catalog.js.map +1 -0
  156. package/dist/schema/introspect.d.ts +1 -1
  157. package/dist/schema/introspect.d.ts.map +1 -1
  158. package/dist/schema/introspect.js +26 -11
  159. package/dist/schema/introspect.js.map +1 -1
  160. package/dist/schema/types.d.ts +150 -1
  161. package/dist/schema/types.d.ts.map +1 -1
  162. package/dist/schema/types.js +11 -0
  163. package/dist/schema/types.js.map +1 -1
  164. package/dist/seeders.d.ts +7 -0
  165. package/dist/seeders.d.ts.map +1 -0
  166. package/dist/seeders.js +7 -0
  167. package/dist/seeders.js.map +1 -0
  168. package/dist/services/db.d.ts +122 -5
  169. package/dist/services/db.d.ts.map +1 -1
  170. package/dist/services/db.js +187 -14
  171. package/dist/services/db.js.map +1 -1
  172. package/dist/testing/DatabaseCleanup.d.ts +33 -7
  173. package/dist/testing/DatabaseCleanup.d.ts.map +1 -1
  174. package/dist/testing/DatabaseCleanup.js +54 -24
  175. package/dist/testing/DatabaseCleanup.js.map +1 -1
  176. package/dist/testing/DbAssertions.d.ts +48 -0
  177. package/dist/testing/DbAssertions.d.ts.map +1 -0
  178. package/dist/testing/DbAssertions.js +80 -0
  179. package/dist/testing/DbAssertions.js.map +1 -0
  180. package/dist/testing/Factory.d.ts +166 -15
  181. package/dist/testing/Factory.d.ts.map +1 -1
  182. package/dist/testing/Factory.js +497 -23
  183. package/dist/testing/Factory.js.map +1 -1
  184. package/dist/testing/TestUtils.d.ts +49 -0
  185. package/dist/testing/TestUtils.d.ts.map +1 -0
  186. package/dist/testing/TestUtils.js +79 -0
  187. package/dist/testing/TestUtils.js.map +1 -0
  188. package/dist/testing/index.d.ts +3 -1
  189. package/dist/testing/index.d.ts.map +1 -1
  190. package/dist/testing/index.js +3 -1
  191. package/dist/testing/index.js.map +1 -1
  192. package/dist/types/relations.d.ts +31 -0
  193. package/dist/types/relations.d.ts.map +1 -0
  194. package/dist/types/relations.js +20 -0
  195. package/dist/types/relations.js.map +1 -0
  196. package/index.darwin-arm64.node +0 -0
  197. package/index.darwin-x64.node +0 -0
  198. package/index.linux-arm64-gnu.node +0 -0
  199. package/index.linux-x64-gnu.node +0 -0
  200. package/index.win32-x64-msvc.node +0 -0
  201. package/package.json +32 -2
  202. package/scripts/guard-publish.mjs +15 -0
  203. package/src/AtlasProvider.ts +305 -52
  204. package/src/BaseEntity.ts +460 -41
  205. package/src/BaseModel.ts +461 -0
  206. package/src/BaseRepository.ts +1710 -421
  207. package/src/ConnectionManager.ts +298 -0
  208. package/src/ModelQuery.ts +2998 -335
  209. package/src/Transaction.ts +227 -30
  210. package/src/adapters/NapiDbAdapter.ts +224 -17
  211. package/src/console/contract.ts +96 -0
  212. package/src/console/factoryCommands.ts +73 -0
  213. package/src/console/migrationCommands.ts +448 -0
  214. package/src/console/schemaCheckCommand.ts +26 -22
  215. package/src/console/schemaDumpCommand.ts +96 -0
  216. package/src/console/schemaGenerateCommand.ts +380 -0
  217. package/src/console/seederCommands.ts +174 -0
  218. package/src/decorators/entity.ts +71 -8
  219. package/src/decorators/hooks.ts +5 -3
  220. package/src/events.ts +117 -0
  221. package/src/factories.ts +10 -0
  222. package/src/index.ts +69 -3
  223. package/src/lucid-schema.ts +22 -0
  224. package/src/metadata-keys.ts +3 -2
  225. package/src/naming/NamingStrategy.ts +23 -0
  226. package/src/orm.ts +13 -0
  227. package/src/query/DatabaseQueryBuilder.ts +2724 -0
  228. package/src/query/DmlBuilder.ts +131 -0
  229. package/src/query/QueryBuilder.ts +8 -0
  230. package/src/query/RawQueryBuilder.ts +173 -0
  231. package/src/query/interpolate.ts +73 -0
  232. package/src/query/native.ts +29 -0
  233. package/src/query/operators.ts +27 -0
  234. package/src/schema/Migration.ts +71 -3
  235. package/src/schema/MigrationRunner.ts +676 -69
  236. package/src/schema/Schema.ts +359 -3
  237. package/src/schema/SchemaDumper.ts +518 -0
  238. package/src/schema/Seeder.ts +47 -10
  239. package/src/schema/TableBuilder.ts +783 -52
  240. package/src/schema/catalog.ts +236 -0
  241. package/src/schema/introspect.ts +26 -9
  242. package/src/schema/types.ts +137 -2
  243. package/src/seeders.ts +16 -0
  244. package/src/services/db.ts +361 -21
  245. package/src/testing/DatabaseCleanup.ts +78 -25
  246. package/src/testing/DbAssertions.ts +127 -0
  247. package/src/testing/Factory.ts +837 -40
  248. package/src/testing/TestUtils.ts +123 -0
  249. package/src/testing/index.ts +12 -1
  250. package/src/types/relations.ts +43 -0
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The console command contract, declared locally.
3
+ *
4
+ * Atlas stays framework-agnostic: it must not import `@c9up/ream`, so it
5
+ * describes the shape Ream's console kernel dispatches against rather than
6
+ * importing it. Same reasoning as the previous `AtlasCommand` interface — only
7
+ * the shape changed, from a plain object to a class carrying its inputs as
8
+ * metadata.
9
+ *
10
+ * Ream's decorators (`@args` / `@flags`) live in the framework, so the helpers
11
+ * below build the same metadata without them.
12
+ */
13
+
14
+ export interface CommandOptions {
15
+ /** Boot the application before `run()`. Off by default. */
16
+ startApp?: boolean;
17
+ staysAlive?: boolean;
18
+ allowUnknownFlags?: boolean;
19
+ }
20
+
21
+ export interface ArgumentMetaData {
22
+ type: "string" | "spread";
23
+ propertyName: string;
24
+ argumentName: string;
25
+ description?: string;
26
+ required: boolean;
27
+ default?: string | string[];
28
+ }
29
+
30
+ export interface FlagMetaData {
31
+ type: "string" | "boolean" | "number" | "array";
32
+ propertyName: string;
33
+ flagName: string;
34
+ description?: string;
35
+ alias: string[];
36
+ default?: string | string[] | number | boolean;
37
+ required: boolean;
38
+ }
39
+
40
+ /** The static side the kernel reads. */
41
+ export interface AtlasCommandClass {
42
+ new (): { run(): Promise<void> | void };
43
+ commandName: string;
44
+ description: string;
45
+ options?: CommandOptions;
46
+ args?: readonly ArgumentMetaData[];
47
+ flags?: readonly FlagMetaData[];
48
+ help?: string | string[];
49
+ }
50
+
51
+ /** `startServer` → `start-server`, matching the framework's decorators. */
52
+ function dashCase(value: string): string {
53
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
54
+ }
55
+
56
+ export function flag(
57
+ propertyName: string,
58
+ type: FlagMetaData["type"],
59
+ options: {
60
+ flagName?: string;
61
+ description?: string;
62
+ alias?: string[];
63
+ default?: FlagMetaData["default"];
64
+ required?: boolean;
65
+ } = {},
66
+ ): FlagMetaData {
67
+ return {
68
+ type,
69
+ propertyName,
70
+ flagName: options.flagName ?? dashCase(propertyName),
71
+ description: options.description,
72
+ alias: options.alias ?? [],
73
+ default: options.default,
74
+ required: options.required ?? false,
75
+ };
76
+ }
77
+
78
+ export function argument(
79
+ propertyName: string,
80
+ options: {
81
+ type?: ArgumentMetaData["type"];
82
+ argumentName?: string;
83
+ description?: string;
84
+ required?: boolean;
85
+ default?: ArgumentMetaData["default"];
86
+ } = {},
87
+ ): ArgumentMetaData {
88
+ return {
89
+ type: options.type ?? "string",
90
+ propertyName,
91
+ argumentName: options.argumentName ?? dashCase(propertyName),
92
+ description: options.description,
93
+ required: options.required ?? options.default === undefined,
94
+ default: options.default,
95
+ };
96
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Factory console command — `make:factory` (Adonis Lucid). Scaffolds a model
3
+ * factory file. Same shape as the migration/seeder commands: a plain
4
+ * `{ name, description, run }` object registered in `reamrc.commands`.
5
+ *
6
+ * @example
7
+ * // commands/make-factory.ts
8
+ * import { makeFactoryCommand } from '@c9up/atlas'
9
+ * export default makeFactoryCommand({ factoriesDir: 'database/factories' })
10
+ * // run: <console-entry> make:factory User
11
+ */
12
+
13
+ import * as fsp from "node:fs/promises";
14
+ import * as path from "node:path";
15
+ import { camelToSnake } from "../utils/casing.js";
16
+ import { assertSafeName } from "../utils/safePath.js";
17
+ import { type AtlasCommandClass, argument } from "./contract.js";
18
+
19
+ export interface FactoryCommandOptions {
20
+ /** Directory the factory files are scaffolded into. */
21
+ factoriesDir: string;
22
+ }
23
+
24
+ /** Scaffold body for a fresh factory (`make:factory <Model>`). */
25
+ function factoryStub(model: string): string {
26
+ return `import { factory } from '@c9up/atlas'
27
+ import ${model} from '#models/${model.toLowerCase()}'
28
+
29
+ export const ${model}Factory = factory(${model}, ({ faker }) => ({
30
+ // email: faker.internet.email(),
31
+ }))
32
+ `;
33
+ }
34
+
35
+ /**
36
+ * `make:factory <Model>` — scaffold `<Model>Factory.ts` in `factoriesDir`. The
37
+ * name is validated (no path separators / traversal) and written with `wx` so an
38
+ * existing factory is never clobbered.
39
+ */
40
+ export function makeFactoryCommand(
41
+ options: FactoryCommandOptions,
42
+ ): AtlasCommandClass {
43
+ return class MakeFactory {
44
+ static commandName = "make:factory";
45
+ static description = "Scaffold a new model factory file";
46
+ // Pure filesystem work: no reason to boot the app and open a connection.
47
+ static options = { startApp: false };
48
+ static args = [
49
+ argument("model", { description: "Model the factory is built for" }),
50
+ ];
51
+
52
+ declare model: string;
53
+
54
+ async run(): Promise<void> {
55
+ // A missing model is caught by the kernel before `run()` — it reports
56
+ // the required argument by name, so there is no usage check here.
57
+ // Lucid convention: `make:factory User` → `user_factory.ts`
58
+ // (`BlogPost` → `blog_post_factory.ts`).
59
+ const fileName = `${camelToSnake(this.model)}_factory.ts`;
60
+ try {
61
+ assertSafeName(fileName, "FACTORY_INVALID", "factory");
62
+ } catch {
63
+ console.error(`[atlas] invalid factory name: ${this.model}`);
64
+ process.exitCode = 1;
65
+ return;
66
+ }
67
+ const filePath = path.join(options.factoriesDir, fileName);
68
+ await fsp.mkdir(options.factoriesDir, { recursive: true });
69
+ await fsp.writeFile(filePath, factoryStub(this.model), { flag: "wx" });
70
+ console.log(`Created ${filePath}`);
71
+ }
72
+ };
73
+ }
@@ -0,0 +1,448 @@
1
+ /**
2
+ * Migration console commands — the Ream-idiomatic CLI for running, rolling back,
3
+ * inspecting, and wiping migrations. Same shape and contract as
4
+ * {@link schemaCheckCommand}: plain `{ name, description, run }` objects
5
+ * registered in `reamrc.commands` and dispatched by the console kernel.
6
+ *
7
+ * Each command resolves the live connection from atlas's OWN service locator
8
+ * (`getDb`), never importing `@c9up/ream`, and drives the already-tested
9
+ * {@link MigrationRunner}. Atlas has no global config registry (Lucid parity —
10
+ * you pass your own paths), so every factory takes the `migrationsDir`.
11
+ *
12
+ * @example
13
+ * // commands/migrate.ts
14
+ * import { migrationRunCommand } from '@c9up/atlas'
15
+ * export default migrationRunCommand({ migrationsDir: 'database/migrations' })
16
+ *
17
+ * // reamrc.ts → commands: [() => import('./commands/migrate.js')]
18
+ * // run: <console-entry> migration:run
19
+ */
20
+
21
+ import * as fsp from "node:fs/promises";
22
+ import * as path from "node:path";
23
+ import type { AsyncDatabaseConnection } from "../adapters/NapiDbAdapter.js";
24
+ import {
25
+ type DatabaseAdapter,
26
+ MigrationRunner,
27
+ } from "../schema/MigrationRunner.js";
28
+ import { getDb } from "../services/db.js";
29
+ import { assertSafeName } from "../utils/safePath.js";
30
+ import { type AtlasCommandClass, argument, flag } from "./contract.js";
31
+ import {
32
+ generateSchemaFile,
33
+ type SchemaGenerateOptions,
34
+ } from "./schemaGenerateCommand.js";
35
+
36
+ export interface MigrationCommandOptions {
37
+ /** Directory holding the numbered migration files. */
38
+ migrationsDir: string;
39
+ /**
40
+ * Sort migration files numerically (`2_x` before `10_x`). Adonis Lucid
41
+ * `migrations.naturalSort`. Defaults to `false`.
42
+ */
43
+ naturalSort?: boolean;
44
+ /**
45
+ * Run every migration outside a transaction. Adonis Lucid
46
+ * `migrations.disableTransactions`. A migration can also opt out with
47
+ * `static disableTransactions = true`. Defaults to `false`.
48
+ */
49
+ disableTransactions?: boolean;
50
+ /**
51
+ * Regenerate the schema file after a mutating migration command
52
+ * (run/rollback/reset/refresh/fresh) — Adonis Lucid's post-migration
53
+ * `schema:generate`. Off unless an `outputPath` is given; on by default once
54
+ * it is, unless `enabled: false`; suppress per-run with `--no-schema-generate`.
55
+ */
56
+ schemaGeneration?: SchemaGenerateOptions;
57
+ /**
58
+ * Default schema-dump path auto-loaded by `migration:run` / `migration:fresh`
59
+ * when the target DB has no applied migrations (Adonis Lucid bootstraps from
60
+ * the dump by default). Overridden per-run by `--schema-path`; a run never
61
+ * loads it once migrations exist.
62
+ */
63
+ schemaPath?: string;
64
+ }
65
+
66
+ /**
67
+ * Adapt the shared singleton connection to the runner's {@link DatabaseAdapter}.
68
+ * `close()` is intentionally a no-op — the console kernel owns the connection's
69
+ * lifecycle, so a command must not tear down a connection other commands share.
70
+ */
71
+ function toAdapter(conn: AsyncDatabaseConnection): DatabaseAdapter {
72
+ return {
73
+ execute: async (sql, params) => {
74
+ await conn.execute(sql, params);
75
+ },
76
+ query: (sql, params) => conn.query(sql, params),
77
+ runInTransaction: (batch) => conn.runInTransaction(batch),
78
+ // Thread the connection's managed interactive transaction through so the
79
+ // runner can make this.defer() atomic and restore MySQL FK checks.
80
+ transaction: conn.transaction?.bind(conn),
81
+ close: async () => {},
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Resolve a runner from the live connection, or report and set a failing exit
87
+ * code when no connection is registered (mirrors `schemaCheckCommand`).
88
+ */
89
+ function resolveRunner(
90
+ options: MigrationCommandOptions,
91
+ ): MigrationRunner | undefined {
92
+ const db = getDb();
93
+ if (!db) {
94
+ console.error(
95
+ "[atlas] no database connection — is AtlasProvider registered?",
96
+ );
97
+ process.exitCode = 1;
98
+ return undefined;
99
+ }
100
+ // Pass the connection's ACTUAL dialect — without it the runner defaults to
101
+ // sqlite and emits SQLite SQL (lock table, FK handling, DDL) against a
102
+ // Postgres/MySQL database.
103
+ return new MigrationRunner(toAdapter(db), {
104
+ migrationsDir: options.migrationsDir,
105
+ dialect: db.dialect,
106
+ naturalSort: options.naturalSort,
107
+ disableTransactions: options.disableTransactions,
108
+ });
109
+ }
110
+
111
+ /** `migration:run` — apply every pending migration. */
112
+ export function migrationRunCommand(
113
+ options: MigrationCommandOptions,
114
+ ): AtlasCommandClass {
115
+ return class MigrationRun {
116
+ static commandName = "migration:run";
117
+ static description =
118
+ "Run all pending migrations (--schema-path to bootstrap from a dump)";
119
+ static options = { startApp: true };
120
+ static flags = [schemaPathOption(), noSchemaGenerateFlag()];
121
+
122
+ declare schemaPath?: string;
123
+ declare noSchemaGenerate: boolean;
124
+
125
+ async run(): Promise<void> {
126
+ const runner = resolveRunner(options);
127
+ if (!runner) return;
128
+ const ran = await runner.migrate({
129
+ schemaPath: this.schemaPath ?? options.schemaPath,
130
+ });
131
+ console.log(
132
+ ran.length ? `Migrated: ${ran.join(", ")}` : "Already up to date",
133
+ );
134
+ await maybeRegenSchema(options, this);
135
+ }
136
+ };
137
+ }
138
+
139
+ /**
140
+ * `migration:rollback` — undo the latest batch, or with `--batch=N` roll back
141
+ * everything applied after batch N (`--batch=0` rolls back all).
142
+ */
143
+ export function migrationRollbackCommand(
144
+ options: MigrationCommandOptions,
145
+ ): AtlasCommandClass {
146
+ return class MigrationRollback {
147
+ static commandName = "migration:rollback";
148
+ static description =
149
+ "Roll back the latest batch (or --batch=N; --force in prod)";
150
+ static options = { startApp: true };
151
+ static flags = [
152
+ flag("batch", "number", {
153
+ description: "Roll back everything applied after batch N (0 = all)",
154
+ }),
155
+ forceFlag(),
156
+ noSchemaGenerateFlag(),
157
+ ];
158
+
159
+ declare batch?: number;
160
+ declare force: boolean;
161
+ declare noSchemaGenerate: boolean;
162
+
163
+ async run(): Promise<void> {
164
+ const runner = resolveRunner(options);
165
+ if (!runner) return;
166
+ const batch = parseBatchFlag(this.batch);
167
+ if (batch === "invalid") {
168
+ console.error("[atlas] --batch must be a non-negative integer");
169
+ process.exitCode = 1;
170
+ return;
171
+ }
172
+ const force = this.force === true;
173
+ const rolled = await runner.rollback(
174
+ batch === undefined ? { force } : { batch, force },
175
+ );
176
+ console.log(
177
+ rolled.length
178
+ ? `Rolled back: ${rolled.join(", ")}`
179
+ : "Nothing to roll back",
180
+ );
181
+ await maybeRegenSchema(options, this);
182
+ }
183
+ };
184
+ }
185
+
186
+ /** `migration:status` — list every migration and whether it is applied. */
187
+ export function migrationStatusCommand(
188
+ options: MigrationCommandOptions,
189
+ ): AtlasCommandClass {
190
+ return class MigrationStatus {
191
+ static commandName = "migration:status";
192
+ static description = "Show applied and pending migrations";
193
+ static options = { startApp: true };
194
+
195
+ async run(): Promise<void> {
196
+ const runner = resolveRunner(options);
197
+ if (!runner) return;
198
+ const rows = await runner.status();
199
+ if (rows.length === 0) {
200
+ console.log("No migrations found");
201
+ return;
202
+ }
203
+ for (const row of rows) {
204
+ const batch = row.batch === undefined ? "" : ` (batch ${row.batch})`;
205
+ console.log(`${row.status.padEnd(8)} ${row.name}${batch}`);
206
+ }
207
+ }
208
+ };
209
+ }
210
+
211
+ /** `migration:reset` — roll back every applied migration. */
212
+ export function migrationResetCommand(
213
+ options: MigrationCommandOptions,
214
+ ): AtlasCommandClass {
215
+ return class MigrationReset {
216
+ static commandName = "migration:reset";
217
+ static description =
218
+ "Roll back all migrations (--force to override prod guard)";
219
+ static options = { startApp: true };
220
+ static flags = [forceFlag(), noSchemaGenerateFlag()];
221
+
222
+ declare force: boolean;
223
+ declare noSchemaGenerate: boolean;
224
+
225
+ async run(): Promise<void> {
226
+ const runner = resolveRunner(options);
227
+ if (!runner) return;
228
+ const rolled = await runner.reset({ force: this.force === true });
229
+ console.log(
230
+ rolled.length
231
+ ? `Rolled back: ${rolled.join(", ")}`
232
+ : "Nothing to reset",
233
+ );
234
+ await maybeRegenSchema(options, this);
235
+ }
236
+ };
237
+ }
238
+
239
+ /** `migration:unlock` — force-clear a stuck migration lock (Lucid `migration:unlock`). */
240
+ export function migrationUnlockCommand(
241
+ options: MigrationCommandOptions,
242
+ ): AtlasCommandClass {
243
+ return class MigrationUnlock {
244
+ static commandName = "migration:unlock";
245
+ static description = "Force-clear a stuck migration lock";
246
+ static options = { startApp: true };
247
+
248
+ async run(): Promise<void> {
249
+ const runner = resolveRunner(options);
250
+ if (!runner) return;
251
+ const cleared = await runner.forceUnlock();
252
+ console.log(
253
+ cleared ? "Migration lock cleared" : "No migration lock was held",
254
+ );
255
+ }
256
+ };
257
+ }
258
+
259
+ /** `migration:fresh` — drop every table, then re-run all migrations (Lucid `migration:fresh`). */
260
+ export function migrationFreshCommand(
261
+ options: MigrationCommandOptions,
262
+ ): AtlasCommandClass {
263
+ return class MigrationFresh {
264
+ static commandName = "migration:fresh";
265
+ static description =
266
+ "Drop all tables, then re-run every migration (--force to override prod guard)";
267
+ static options = { startApp: true };
268
+ static flags = [forceFlag(), schemaPathOption(), noSchemaGenerateFlag()];
269
+
270
+ declare force: boolean;
271
+ declare schemaPath?: string;
272
+ declare noSchemaGenerate: boolean;
273
+
274
+ async run(): Promise<void> {
275
+ const runner = resolveRunner(options);
276
+ if (!runner) return;
277
+ const { executed } = await runner.fresh({
278
+ force: this.force === true,
279
+ schemaPath: this.schemaPath ?? options.schemaPath,
280
+ });
281
+ console.log(
282
+ executed.length
283
+ ? `Dropped all tables, re-ran: ${executed.join(", ")}`
284
+ : "Dropped all tables (no migrations to run)",
285
+ );
286
+ await maybeRegenSchema(options, this);
287
+ }
288
+ };
289
+ }
290
+
291
+ /** `migration:refresh` — roll everything back, then re-run all migrations. */
292
+ export function migrationRefreshCommand(
293
+ options: MigrationCommandOptions,
294
+ ): AtlasCommandClass {
295
+ return class MigrationRefresh {
296
+ static commandName = "migration:refresh";
297
+ static description =
298
+ "Roll back all migrations, then re-run them (--force to override prod guard)";
299
+ static options = { startApp: true };
300
+ static flags = [forceFlag(), noSchemaGenerateFlag()];
301
+
302
+ declare force: boolean;
303
+ declare noSchemaGenerate: boolean;
304
+
305
+ async run(): Promise<void> {
306
+ const runner = resolveRunner(options);
307
+ if (!runner) return;
308
+ const { rolled, executed } = await runner.refresh({
309
+ force: this.force === true,
310
+ });
311
+ console.log(`Rolled back: ${rolled.length}, re-ran: ${executed.length}`);
312
+ await maybeRegenSchema(options, this);
313
+ }
314
+ };
315
+ }
316
+
317
+ /** `db:wipe` — drop every table, including the migrations bookkeeping table. */
318
+ export function dbWipeCommand(
319
+ options: MigrationCommandOptions,
320
+ ): AtlasCommandClass {
321
+ return class DbWipe {
322
+ static commandName = "db:wipe";
323
+ static description =
324
+ "Drop all tables including the migrations table (--force to override prod guard)";
325
+ static options = { startApp: true };
326
+ static flags = [forceFlag()];
327
+
328
+ declare force: boolean;
329
+
330
+ async run(): Promise<void> {
331
+ const runner = resolveRunner(options);
332
+ if (!runner) return;
333
+ await runner.wipe({ force: this.force === true });
334
+ console.log("Dropped all tables");
335
+ }
336
+ };
337
+ }
338
+
339
+ /** Scaffold body for a fresh migration (`make:migration`). */
340
+ const MIGRATION_STUB = `import { Migration } from '@c9up/atlas'
341
+
342
+ export default class extends Migration {
343
+ async up() {
344
+ // this.schema.createTable('table_name', (table) => {
345
+ // table.increments('id')
346
+ // })
347
+ }
348
+
349
+ async down() {
350
+ // this.schema.dropTable('table_name')
351
+ }
352
+ }
353
+ `;
354
+
355
+ /**
356
+ * `make:migration <name>` — scaffold a timestamped migration file in
357
+ * `migrationsDir`. The `Date.now()` prefix keeps files in creation order under
358
+ * the runner's lexicographic sort (same convention as AdonisJS/Lucid). The name
359
+ * is validated (no path separators / traversal) and the file is written with
360
+ * `wx` so an existing migration is never clobbered.
361
+ */
362
+ export function makeMigrationCommand(
363
+ options: MigrationCommandOptions,
364
+ ): AtlasCommandClass {
365
+ return class MakeMigration {
366
+ static commandName = "make:migration";
367
+ static description = "Scaffold a new timestamped migration file";
368
+ // Filesystem only — no connection needed.
369
+ static options = { startApp: false };
370
+ static args = [argument("name", { description: "Migration file name" })];
371
+
372
+ declare name: string;
373
+
374
+ async run(): Promise<void> {
375
+ // A missing name never reaches here: the kernel reports the required
376
+ // argument by name before `run()`.
377
+ try {
378
+ assertSafeName(this.name, "MIGRATION_INVALID", "migration");
379
+ } catch {
380
+ console.error(`[atlas] invalid migration name: ${this.name}`);
381
+ process.exitCode = 1;
382
+ return;
383
+ }
384
+ const fileName = `${Date.now()}_${this.name}.ts`;
385
+ const filePath = path.join(options.migrationsDir, fileName);
386
+ await fsp.mkdir(options.migrationsDir, { recursive: true });
387
+ await fsp.writeFile(filePath, MIGRATION_STUB, { flag: "wx" });
388
+ console.log(`Created ${filePath}`);
389
+ }
390
+ };
391
+ }
392
+
393
+ /**
394
+ * Flags shared by several migration commands.
395
+ *
396
+ * Declared per command rather than inherited: `migration:status` takes neither
397
+ * `--force` nor `--schema-path`, and listing them anyway would put flags in its
398
+ * help that it ignores.
399
+ */
400
+ const forceFlag = () =>
401
+ flag("force", "boolean", {
402
+ description: "Override the production guard",
403
+ });
404
+
405
+ const schemaPathOption = () =>
406
+ flag("schemaPath", "string", {
407
+ description: "Bootstrap from a schema dump before migrating",
408
+ });
409
+
410
+ const noSchemaGenerateFlag = () =>
411
+ flag("noSchemaGenerate", "boolean", {
412
+ description: "Skip regenerating the schema file afterwards",
413
+ });
414
+
415
+ /**
416
+ * Regenerate the schema file after a mutating migration command (Adonis Lucid's
417
+ * post-migration `schema:generate`) — unless it's disabled, has no `outputPath`,
418
+ * or the run passed `--no-schema-generate`.
419
+ */
420
+ async function maybeRegenSchema(
421
+ options: MigrationCommandOptions,
422
+ command: { noSchemaGenerate?: boolean },
423
+ ): Promise<void> {
424
+ const cfg = options.schemaGeneration;
425
+ // Opt-in by configuring an outputPath; then ON unless explicitly disabled —
426
+ // Adonis Lucid presents `enabled: false` as the OFF switch (default on).
427
+ if (!cfg?.outputPath || cfg.enabled === false) return;
428
+ if (command.noSchemaGenerate === true) return;
429
+ const db = getDb();
430
+ if (!db) return;
431
+ const n = await generateSchemaFile(db, cfg);
432
+ console.log(
433
+ `Regenerated ${cfg.outputPath} (${n} table${n === 1 ? "" : "s"})`,
434
+ );
435
+ }
436
+
437
+ /**
438
+ * Parse the `--batch` flag: absent → undefined (default rollback), a
439
+ * non-negative integer string → that number, anything else → `"invalid"`.
440
+ */
441
+ function parseBatchFlag(
442
+ value: number | undefined,
443
+ ): number | undefined | "invalid" {
444
+ // The kernel already rejected a non-numeric `--batch`; what is left to check
445
+ // is that the number is a non-negative integer.
446
+ if (value === undefined) return undefined;
447
+ return Number.isInteger(value) && value >= 0 ? value : "invalid";
448
+ }
@@ -1,33 +1,29 @@
1
1
  /**
2
2
  * `atlas:check` console command — the Ream-idiomatic CLI for schema
3
- * verification. Ream commands are plain `{ name, description, run }` objects
4
- * registered in `reamrc.commands` and dispatched by the console kernel
5
- * (`new Ignitor(...).console().handle(argv)`).
3
+ * verification. Ream commands are classes carrying their name, description and
4
+ * inputs as statics; the console kernel discovers them in `commands/` or reads
5
+ * them from `reamrc.commands`.
6
6
  *
7
7
  * Stays framework-agnostic: resolves the live connection + dialect from atlas's
8
8
  * OWN service locators (`getDb` / `getAtlasDialect`), never importing
9
- * `@c9up/ream`. The {@link AtlasCommand} shape structurally matches Ream's
10
- * `Command` interface, so the console kernel accepts it without a type
11
- * dependency in either direction.
9
+ * `@c9up/ream`. The {@link AtlasCommandClass} shape structurally matches Ream's
10
+ * command contract, so the console kernel accepts it without a type dependency
11
+ * in either direction.
12
12
  */
13
13
 
14
14
  import { getAtlasDialect } from "../query/native.js";
15
15
  import { runSchemaCheck } from "../schema/SchemaCheck.js";
16
16
  import { getDb } from "../services/db.js";
17
+ import { type AtlasCommandClass, flag } from "./contract.js";
17
18
 
18
19
  type Constructor = new (...args: unknown[]) => unknown;
19
20
 
20
- /** Structural match of Ream's console `Command` (no `@c9up/ream` import). */
21
- export interface AtlasCommand {
22
- name: string;
23
- description: string;
24
- run(args: string[], flags: Record<string, string | boolean>): Promise<void>;
25
- }
21
+ export type { AtlasCommandClass } from "./contract.js";
26
22
 
27
23
  /**
28
24
  * Build the `atlas:check` command for the given models. Register it in
29
25
  * `reamrc.commands` (atlas has no global entity registry — list your models,
30
- * as in Lucid). Run it via the console kernel; `--warn` reports drift without a
26
+ * as in Lucid). Run it as `ream atlas:check`; `--warn` reports drift without a
31
27
  * non-zero exit (useful for an advisory CI step).
32
28
  *
33
29
  * @example
@@ -36,16 +32,24 @@ export interface AtlasCommand {
36
32
  * import { User } from '#models/user'
37
33
  * export default schemaCheckCommand([User])
38
34
  *
39
- * // reamrc.ts → commands: [() => import('./commands/atlas-check.js')]
40
- * // run: <console-entry> atlas:check
35
+ * // run: ream atlas:check --warn
41
36
  */
42
37
  export function schemaCheckCommand(
43
38
  entities: readonly Constructor[],
44
- ): AtlasCommand {
45
- return {
46
- name: "atlas:check",
47
- description: "Verify models match the live database schema",
48
- async run(_args, flags) {
39
+ ): AtlasCommandClass {
40
+ return class SchemaCheck {
41
+ static commandName = "atlas:check";
42
+ static description = "Verify models match the live database schema";
43
+ static options = { startApp: true };
44
+ static flags = [
45
+ flag("warn", "boolean", {
46
+ description: "Report drift without failing (exit 0)",
47
+ }),
48
+ ];
49
+
50
+ declare warn: boolean;
51
+
52
+ async run(): Promise<void> {
49
53
  const db = getDb();
50
54
  if (!db) {
51
55
  console.error(
@@ -56,7 +60,7 @@ export function schemaCheckCommand(
56
60
  }
57
61
  const code = await runSchemaCheck(entities, db, getAtlasDialect());
58
62
  // `--warn` downgrades drift to advisory (exit 0); default fails CI.
59
- if (code !== 0 && !flags.warn) process.exitCode = code;
60
- },
63
+ if (code !== 0 && !this.warn) process.exitCode = code;
64
+ }
61
65
  };
62
66
  }