@c9up/atlas 0.1.19 → 0.2.0

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 (121) hide show
  1. package/README.md +55 -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 +6 -0
  8. package/dist/AtlasProvider.d.ts.map +1 -1
  9. package/dist/AtlasProvider.js +2 -2
  10. package/dist/AtlasProvider.js.map +1 -1
  11. package/dist/BaseEntity.d.ts +164 -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 +91 -0
  16. package/dist/BaseModel.d.ts.map +1 -0
  17. package/dist/BaseModel.js +193 -0
  18. package/dist/BaseModel.js.map +1 -0
  19. package/dist/BaseRepository.d.ts +71 -15
  20. package/dist/BaseRepository.d.ts.map +1 -1
  21. package/dist/BaseRepository.js +1355 -384
  22. package/dist/BaseRepository.js.map +1 -1
  23. package/dist/ModelQuery.d.ts +341 -18
  24. package/dist/ModelQuery.d.ts.map +1 -1
  25. package/dist/ModelQuery.js +1406 -177
  26. package/dist/ModelQuery.js.map +1 -1
  27. package/dist/Transaction.d.ts +17 -0
  28. package/dist/Transaction.d.ts.map +1 -1
  29. package/dist/Transaction.js +57 -5
  30. package/dist/Transaction.js.map +1 -1
  31. package/dist/adapters/NapiDbAdapter.d.ts +33 -4
  32. package/dist/adapters/NapiDbAdapter.d.ts.map +1 -1
  33. package/dist/adapters/NapiDbAdapter.js +101 -11
  34. package/dist/adapters/NapiDbAdapter.js.map +1 -1
  35. package/dist/console/migrationCommands.d.ts +48 -0
  36. package/dist/console/migrationCommands.d.ts.map +1 -0
  37. package/dist/console/migrationCommands.js +220 -0
  38. package/dist/console/migrationCommands.js.map +1 -0
  39. package/dist/decorators/entity.d.ts +37 -6
  40. package/dist/decorators/entity.d.ts.map +1 -1
  41. package/dist/decorators/entity.js +32 -2
  42. package/dist/decorators/entity.js.map +1 -1
  43. package/dist/events.d.ts +64 -0
  44. package/dist/events.d.ts.map +1 -0
  45. package/dist/events.js +82 -0
  46. package/dist/events.js.map +1 -0
  47. package/dist/index.d.ts +5 -1
  48. package/dist/index.d.ts.map +1 -1
  49. package/dist/index.js +3 -0
  50. package/dist/index.js.map +1 -1
  51. package/dist/metadata-keys.d.ts +3 -2
  52. package/dist/metadata-keys.d.ts.map +1 -1
  53. package/dist/naming/NamingStrategy.d.ts +7 -0
  54. package/dist/naming/NamingStrategy.d.ts.map +1 -1
  55. package/dist/naming/NamingStrategy.js +16 -0
  56. package/dist/naming/NamingStrategy.js.map +1 -1
  57. package/dist/schema/Migration.d.ts +26 -3
  58. package/dist/schema/Migration.d.ts.map +1 -1
  59. package/dist/schema/Migration.js +33 -24
  60. package/dist/schema/Migration.js.map +1 -1
  61. package/dist/schema/MigrationRunner.d.ts +43 -32
  62. package/dist/schema/MigrationRunner.d.ts.map +1 -1
  63. package/dist/schema/MigrationRunner.js +211 -26
  64. package/dist/schema/MigrationRunner.js.map +1 -1
  65. package/dist/schema/Schema.d.ts +57 -0
  66. package/dist/schema/Schema.d.ts.map +1 -1
  67. package/dist/schema/Schema.js +138 -3
  68. package/dist/schema/Schema.js.map +1 -1
  69. package/dist/schema/TableBuilder.d.ts +247 -8
  70. package/dist/schema/TableBuilder.d.ts.map +1 -1
  71. package/dist/schema/TableBuilder.js +607 -41
  72. package/dist/schema/TableBuilder.js.map +1 -1
  73. package/dist/schema/catalog.d.ts +47 -0
  74. package/dist/schema/catalog.d.ts.map +1 -0
  75. package/dist/schema/catalog.js +111 -0
  76. package/dist/schema/catalog.js.map +1 -0
  77. package/dist/schema/types.d.ts +150 -1
  78. package/dist/schema/types.d.ts.map +1 -1
  79. package/dist/schema/types.js +11 -0
  80. package/dist/schema/types.js.map +1 -1
  81. package/dist/services/db.d.ts +6 -0
  82. package/dist/services/db.d.ts.map +1 -1
  83. package/dist/services/db.js +17 -0
  84. package/dist/services/db.js.map +1 -1
  85. package/dist/testing/DatabaseCleanup.d.ts +7 -4
  86. package/dist/testing/DatabaseCleanup.d.ts.map +1 -1
  87. package/dist/testing/DatabaseCleanup.js +21 -18
  88. package/dist/testing/DatabaseCleanup.js.map +1 -1
  89. package/dist/testing/Factory.d.ts +70 -5
  90. package/dist/testing/Factory.d.ts.map +1 -1
  91. package/dist/testing/Factory.js +209 -10
  92. package/dist/testing/Factory.js.map +1 -1
  93. package/index.darwin-arm64.node +0 -0
  94. package/index.darwin-x64.node +0 -0
  95. package/index.linux-arm64-gnu.node +0 -0
  96. package/index.linux-x64-gnu.node +0 -0
  97. package/index.win32-x64-msvc.node +0 -0
  98. package/package.json +3 -1
  99. package/scripts/guard-publish.mjs +15 -0
  100. package/src/AtlasProvider.ts +8 -1
  101. package/src/BaseEntity.ts +431 -41
  102. package/src/BaseModel.ts +324 -0
  103. package/src/BaseRepository.ts +1589 -419
  104. package/src/ModelQuery.ts +1817 -203
  105. package/src/Transaction.ts +68 -5
  106. package/src/adapters/NapiDbAdapter.ts +159 -10
  107. package/src/console/migrationCommands.ts +258 -0
  108. package/src/decorators/entity.ts +53 -6
  109. package/src/events.ts +112 -0
  110. package/src/index.ts +19 -0
  111. package/src/metadata-keys.ts +3 -2
  112. package/src/naming/NamingStrategy.ts +23 -0
  113. package/src/schema/Migration.ts +42 -3
  114. package/src/schema/MigrationRunner.ts +270 -27
  115. package/src/schema/Schema.ts +210 -3
  116. package/src/schema/TableBuilder.ts +735 -41
  117. package/src/schema/catalog.ts +166 -0
  118. package/src/schema/types.ts +137 -2
  119. package/src/services/db.ts +28 -0
  120. package/src/testing/DatabaseCleanup.ts +23 -22
  121. package/src/testing/Factory.ts +332 -15
@@ -15,21 +15,94 @@ import {
15
15
  import { RawSql } from "../query/QueryBuilder.js";
16
16
  import { type DefaultValue, renderDefaultValue } from "./raw.js";
17
17
  import {
18
+ type AlterOperation,
19
+ type CheckExpression,
20
+ type CheckOperator,
21
+ type CheckValue,
18
22
  type ColumnDefinition,
19
23
  type ColumnType,
24
+ type ForeignKeyReference,
20
25
  type IndexDefinition,
26
+ type ReferentialAction,
27
+ type TableConstraintSpec,
28
+ type TableOptionsSpec,
29
+ type TextVariant,
21
30
  TYPE_KIND_MAP,
22
31
  } from "./types.js";
23
32
 
33
+ /**
34
+ * The chainable returned by `table.foreign([...])`, so the target reads in
35
+ * Knex order: `.references([...]).inTable('other').onDelete('cascade')`. It
36
+ * mutates the already-recorded constraint in place.
37
+ */
38
+ export class ForeignKeyBuilder {
39
+ readonly #references: ForeignKeyReference;
40
+
41
+ constructor(references: ForeignKeyReference) {
42
+ this.#references = references;
43
+ }
44
+
45
+ /** Target column(s) on the referenced table. */
46
+ references(columns: string | readonly string[]): this {
47
+ this.#references.columns =
48
+ typeof columns === "string" ? [columns] : [...columns];
49
+ return this;
50
+ }
51
+
52
+ /**
53
+ * Referenced table. Keeps returning this builder so `.onDelete()` /
54
+ * `.onUpdate()` can follow, as in Knex — the constraint was already
55
+ * recorded on the table when `foreign()` was called, so there is nothing to
56
+ * hand back to.
57
+ */
58
+ inTable(table: string): this {
59
+ this.#references.table = table;
60
+ return this;
61
+ }
62
+
63
+ onDelete(action: ReferentialAction): this {
64
+ this.#references.onDelete = action;
65
+ return this;
66
+ }
67
+
68
+ onUpdate(action: ReferentialAction): this {
69
+ this.#references.onUpdate = action;
70
+ return this;
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Whether the builder is filling a `CREATE TABLE` or an `ALTER TABLE`. In
76
+ * `alter` mode a column-type method (`t.string('x')`) becomes `ADD COLUMN`,
77
+ * and `.alter()` turns the pending add into a type change (Lucid/Knex).
78
+ */
79
+ export type TableBuilderMode = "create" | "alter";
80
+
24
81
  /** Table builder — used inside `schema.createTable(name, callback)`. */
25
82
  export class TableBuilder {
26
83
  readonly tableName: string;
84
+ readonly mode: TableBuilderMode;
27
85
  #columns: ColumnDefinition[] = [];
28
86
  #indexes: IndexDefinition[] = [];
29
87
  #currentColumn?: ColumnDefinition;
88
+ /** Ordered ALTER TABLE ops. Empty (and unused) in `create` mode. */
89
+ #operations: AlterOperation[] = [];
90
+ /** Table-level constraints. In `alter` mode these become `addConstraint` ops instead. */
91
+ #constraints: TableConstraintSpec[] = [];
92
+ #options: TableOptionsSpec = {};
93
+ /** The op the pending column modifiers apply to, in `alter` mode. */
94
+ #currentOp?: Extract<AlterOperation, { op: "addColumn" | "alterColumn" }>;
95
+ /**
96
+ * Whether `.nullable()` / `.notNullable()` was called on the current column.
97
+ * `ColumnDefinition.nullable` defaults to `true`, so without this flag
98
+ * `.alter()` could not tell "leave nullability alone" from "make it
99
+ * nullable" — see `AlterOperation.setNullable`.
100
+ */
101
+ #nullabilityTouched = false;
30
102
 
31
- constructor(tableName: string) {
103
+ constructor(tableName: string, mode: TableBuilderMode = "create") {
32
104
  this.tableName = tableName;
105
+ this.mode = mode;
33
106
  }
34
107
 
35
108
  // ─── Column types ─────────────────────────────────────────
@@ -59,12 +132,29 @@ export class TableBuilder {
59
132
  return this;
60
133
  }
61
134
 
62
- text(name: string): this {
63
- return this.#addColumn(name, "text");
135
+ /**
136
+ * Text column (Lucid/Knex `text(name, textType)`). `textType` widens the
137
+ * MySQL type (`MEDIUMTEXT` / `LONGTEXT`); Postgres and SQLite have a single
138
+ * unbounded `TEXT` and ignore it.
139
+ */
140
+ text(name: string, textType: TextVariant = "text"): this {
141
+ return this.#addColumn(name, textType);
64
142
  }
65
143
  integer(name: string): this {
66
144
  return this.#addColumn(name, "integer");
67
145
  }
146
+ /** 24-bit integer (Lucid/Knex `mediumint`). MySQL `MEDIUMINT`; pg/SQLite widen to `INTEGER`. */
147
+ mediumint(name: string): this {
148
+ return this.#addColumn(name, "mediumint");
149
+ }
150
+ /** 8-bit integer (Lucid `tinyint`). MySQL `TINYINT`; Postgres widens to `SMALLINT`; SQLite `INTEGER`. */
151
+ tinyint(name: string): this {
152
+ return this.#addColumn(name, "tinyint");
153
+ }
154
+ /** 16-bit integer (Lucid `smallint`). `SMALLINT` on pg/mysql, `INTEGER` on SQLite. */
155
+ smallint(name: string): this {
156
+ return this.#addColumn(name, "smallint");
157
+ }
68
158
  bigInteger(name: string): this {
69
159
  return this.#addColumn(name, "bigInteger");
70
160
  }
@@ -78,14 +168,57 @@ export class TableBuilder {
78
168
  return this;
79
169
  }
80
170
 
171
+ /**
172
+ * Single-precision float (Lucid `float`). `REAL` on pg/sqlite, `FLOAT` on
173
+ * MySQL. `precision`/`scale` render `FLOAT(p, s)` on MySQL only — pg and
174
+ * SQLite have fixed-width floats and ignore them.
175
+ */
176
+ float(name: string, precision?: number, scale?: number): this {
177
+ return this.#addFloat(name, "float", precision, scale);
178
+ }
179
+ /** Double-precision float (Lucid `double`). `DOUBLE PRECISION` on pg, `REAL` on SQLite, `DOUBLE` on MySQL. See {@link float} for precision/scale. */
180
+ double(name: string, precision?: number, scale?: number): this {
181
+ return this.#addFloat(name, "double", precision, scale);
182
+ }
183
+
81
184
  boolean(name: string): this {
82
185
  return this.#addColumn(name, "boolean");
83
186
  }
84
187
  date(name: string): this {
85
188
  return this.#addColumn(name, "date");
86
189
  }
87
- timestamp(name: string): this {
88
- return this.#addColumn(name, "timestamp");
190
+ /**
191
+ * Time of day (Lucid `time`). `TIME` on pg/mysql, `TEXT` on SQLite.
192
+ * `precision` renders `TIME(p)` fractional seconds (ignored on SQLite,
193
+ * which has no time type to carry it).
194
+ */
195
+ time(name: string, precision?: number): this {
196
+ this.#addColumn(name, "time");
197
+ if (this.#currentColumn) this.#currentColumn.precision = precision;
198
+ return this;
199
+ }
200
+ /**
201
+ * Timestamp column (Lucid `timestamp(name, options)`).
202
+ *
203
+ * `useTz: true` selects the tz-aware type — the same thing
204
+ * {@link timestamptz} does, exposed here for Lucid's option spelling.
205
+ * `precision` renders `TIMESTAMP(p)` (ignored on SQLite, which stores
206
+ * timestamps as TEXT).
207
+ */
208
+ timestamp(
209
+ name: string,
210
+ options: { useTz?: boolean; precision?: number } = {},
211
+ ): this {
212
+ this.#addColumn(name, options.useTz ? "timestamptz" : "timestamp");
213
+ if (this.#currentColumn) this.#currentColumn.precision = options.precision;
214
+ return this;
215
+ }
216
+ /** Alias of {@link timestamp} (Lucid `dateTime`). Use `{ useTz: true }` or {@link timestamptz} for a tz-aware column. */
217
+ dateTime(
218
+ name: string,
219
+ options: { useTz?: boolean; precision?: number } = {},
220
+ ): this {
221
+ return this.timestamp(name, options);
89
222
  }
90
223
  /**
91
224
  * `timestamp WITH time zone` — Postgres normalises every writer (atlas,
@@ -102,8 +235,54 @@ export class TableBuilder {
102
235
  json(name: string): this {
103
236
  return this.#addColumn(name, "json");
104
237
  }
105
- binary(name: string): this {
106
- return this.#addColumn(name, "binary");
238
+ /**
239
+ * Binary JSON (Lucid/Knex `jsonb`). `JSONB` on pg, `JSON` on MySQL, `TEXT`
240
+ * on SQLite.
241
+ *
242
+ * Deviation, named: atlas's {@link json} already maps to `JSONB` on
243
+ * Postgres (it predates this method), where Lucid's `json()` maps to
244
+ * `json`. Leaving `json()` alone avoids silently rewriting the physical
245
+ * type of existing columns and desyncing `SchemaCheck`, so on Postgres the
246
+ * two spellings coincide.
247
+ */
248
+ jsonb(name: string): this {
249
+ return this.#addColumn(name, "jsonb");
250
+ }
251
+ /**
252
+ * Binary blob (Lucid/Knex `binary(name, length)`). `BYTEA` on pg, `BLOB` on
253
+ * SQLite; on MySQL `length` selects `VARBINARY(n)` over `BLOB`.
254
+ */
255
+ binary(name: string, length?: number): this {
256
+ this.#addColumn(name, "binary");
257
+ if (this.#currentColumn) this.#currentColumn.length = length;
258
+ return this;
259
+ }
260
+
261
+ /**
262
+ * A column typed with a verbatim dialect type (Lucid/Knex `specificType`) —
263
+ * the escape hatch for types atlas has no method for (`inet`, `tsvector`,
264
+ * `geometry(Point, 4326)`…).
265
+ *
266
+ * Deviation, named: Knex passes the string straight through. Atlas cannot —
267
+ * it lands verbatim in DDL, so the Rust compiler validates it against a
268
+ * narrow grammar (letters, digits, spaces, `_`, and one parenthesised
269
+ * argument list) and rejects anything else with `E_UNSAFE_SQL`.
270
+ */
271
+ specificType(name: string, type: string): this {
272
+ this.#addColumn(name, "specificType");
273
+ if (this.#currentColumn) this.#currentColumn.rawType = type;
274
+ return this;
275
+ }
276
+
277
+ /**
278
+ * Fixed value-set column (Lucid `enum`). MySQL renders a native `ENUM(...)`;
279
+ * Postgres and SQLite render `TEXT` plus a `CHECK (col IN (...))` that pins the
280
+ * value set. At least one value is required.
281
+ */
282
+ enum(name: string, values: string[]): this {
283
+ this.#addColumn(name, "enum");
284
+ if (this.#currentColumn) this.#currentColumn.values = values;
285
+ return this;
107
286
  }
108
287
 
109
288
  // ─── Shortcuts ────────────────────────────────────────────
@@ -164,23 +343,15 @@ export class TableBuilder {
164
343
 
165
344
  // ─── Column modifiers ─────────────────────────────────────
166
345
 
167
- primary(): this {
168
- if (this.#currentColumn) this.#currentColumn.primary = true;
169
- return this;
170
- }
171
-
172
346
  notNullable(): this {
173
347
  if (this.#currentColumn) this.#currentColumn.nullable = false;
348
+ this.#nullabilityTouched = true;
174
349
  return this;
175
350
  }
176
351
 
177
352
  nullable(): this {
178
353
  if (this.#currentColumn) this.#currentColumn.nullable = true;
179
- return this;
180
- }
181
-
182
- unique(): this {
183
- if (this.#currentColumn) this.#currentColumn.unique = true;
354
+ this.#nullabilityTouched = true;
184
355
  return this;
185
356
  }
186
357
 
@@ -196,11 +367,312 @@ export class TableBuilder {
196
367
  return this;
197
368
  }
198
369
 
370
+ /** MySQL `UNSIGNED` numeric modifier (Lucid `unsigned()`). No-op on pg/sqlite. */
371
+ unsigned(): this {
372
+ if (this.#currentColumn) this.#currentColumn.unsigned = true;
373
+ return this;
374
+ }
375
+
199
376
  references(table: string, column = "id"): this {
200
377
  if (this.#currentColumn) this.#currentColumn.references = { table, column };
201
378
  return this;
202
379
  }
203
380
 
381
+ /**
382
+ * Referential action for the current column's foreign key `ON DELETE`
383
+ * (Lucid parity). Must follow {@link references}.
384
+ */
385
+ onDelete(action: ReferentialAction): this {
386
+ if (this.#currentColumn?.references) {
387
+ this.#currentColumn.references.onDelete = action;
388
+ }
389
+ return this;
390
+ }
391
+
392
+ /** Referential action for the current column's foreign key `ON UPDATE`. Must follow {@link references}. */
393
+ onUpdate(action: ReferentialAction): this {
394
+ if (this.#currentColumn?.references) {
395
+ this.#currentColumn.references.onUpdate = action;
396
+ }
397
+ return this;
398
+ }
399
+
400
+ /**
401
+ * Comment the current **column** (Lucid/Knex column `comment()`). Inline on
402
+ * MySQL, a separate `COMMENT ON COLUMN` on Postgres, dropped on SQLite.
403
+ *
404
+ * Deviation, named: Knex's `table.comment()` is the TABLE comment, because
405
+ * its column methods return a separate column builder. Atlas flattens the
406
+ * column modifiers onto the table builder (`.notNullable()`, `.unique()`,
407
+ * `.defaultTo()` all work this way), so `comment()` follows that same rule
408
+ * and the table comment is {@link tableComment}. Resolving it by "is a
409
+ * column pending?" would be exactly the kind of guessing that bites later.
410
+ */
411
+ comment(text: string): this {
412
+ if (this.#currentColumn) this.#currentColumn.comment = text;
413
+ return this;
414
+ }
415
+
416
+ /** Collate the current **column** (Lucid/Knex column `collate()`). See {@link comment} for why the table form is {@link tableCollate}. */
417
+ collate(collation: string): this {
418
+ if (this.#currentColumn) this.#currentColumn.collate = collation;
419
+ return this;
420
+ }
421
+
422
+ /**
423
+ * Place an added column first (Lucid/Knex `first()`). MySQL-only —
424
+ * Postgres and SQLite always append, and the Rust compiler raises
425
+ * `E_UNSUPPORTED` rather than dropping the instruction silently.
426
+ */
427
+ first(): this {
428
+ if (this.#currentColumn) this.#currentColumn.position = { at: "first" };
429
+ return this;
430
+ }
431
+
432
+ /** Place an added column after `column` (Lucid/Knex `after()`). MySQL-only — see {@link first}. */
433
+ after(column: string): this {
434
+ if (this.#currentColumn) {
435
+ this.#currentColumn.position = { at: "after", column };
436
+ }
437
+ return this;
438
+ }
439
+
440
+ // ─── CHECK constraints ────────────────────────────────────
441
+
442
+ /** `CHECK (col > 0)` on the current column (Lucid/Knex `checkPositive`). */
443
+ checkPositive(constraintName?: string): this {
444
+ return this.#addCheck(
445
+ (column) => ({ check: "positive", column }),
446
+ constraintName,
447
+ );
448
+ }
449
+
450
+ /** `CHECK (col < 0)` on the current column (Lucid/Knex `checkNegative`). */
451
+ checkNegative(constraintName?: string): this {
452
+ return this.#addCheck(
453
+ (column) => ({ check: "negative", column }),
454
+ constraintName,
455
+ );
456
+ }
457
+
458
+ /** `CHECK (col IN (…))` on the current column (Lucid/Knex `checkIn`). Values are quoted, never interpolated raw. */
459
+ checkIn(values: readonly CheckValue[], constraintName?: string): this {
460
+ return this.#addCheck(
461
+ (column) => ({ check: "in", column, values: [...values] }),
462
+ constraintName,
463
+ );
464
+ }
465
+
466
+ /** `CHECK (col NOT IN (…))` on the current column (Lucid/Knex `checkNotIn`). */
467
+ checkNotIn(values: readonly CheckValue[], constraintName?: string): this {
468
+ return this.#addCheck(
469
+ (column) => ({ check: "notIn", column, values: [...values] }),
470
+ constraintName,
471
+ );
472
+ }
473
+
474
+ /**
475
+ * `CHECK (col BETWEEN lo AND hi)` on the current column (Lucid/Knex
476
+ * `checkBetween`). Accepts one `[min, max]` interval or a list of them —
477
+ * several intervals are OR'd together, as in Knex.
478
+ */
479
+ checkBetween(
480
+ range: readonly CheckValue[] | readonly (readonly CheckValue[])[],
481
+ constraintName?: string,
482
+ ): this {
483
+ // A single [min, max] vs a list of intervals: the first element of a
484
+ // list-of-intervals is itself an array.
485
+ const ranges = Array.isArray(range[0])
486
+ ? (range as readonly (readonly CheckValue[])[]).map((r) => [...r])
487
+ : [[...(range as readonly CheckValue[])]];
488
+ return this.#addCheck(
489
+ (column) => ({ check: "between", column, ranges }),
490
+ constraintName,
491
+ );
492
+ }
493
+
494
+ /** `CHECK (LENGTH(col) <op> n)` on the current column (Lucid/Knex `checkLength`). The operator is allow-listed by the Rust compiler. */
495
+ checkLength(
496
+ operator: CheckOperator,
497
+ length: number,
498
+ constraintName?: string,
499
+ ): this {
500
+ return this.#addCheck(
501
+ (column) => ({ check: "length", column, operator, length }),
502
+ constraintName,
503
+ );
504
+ }
505
+
506
+ /**
507
+ * `CHECK (col ~ 'pattern')` on the current column (Lucid/Knex `checkRegex`).
508
+ * Postgres spells it `~`; MySQL and SQLite use `REGEXP`.
509
+ *
510
+ * SQLite parses `REGEXP` but ships no implementation — the constraint only
511
+ * works if the connection registers a `regexp` function. Knex behaves the
512
+ * same way, so this is parity rather than a new trap, but it is worth
513
+ * knowing before you rely on it there.
514
+ */
515
+ checkRegex(pattern: string, constraintName?: string): this {
516
+ return this.#addCheck(
517
+ (column) => ({ check: "regex", column, pattern }),
518
+ constraintName,
519
+ );
520
+ }
521
+
522
+ /**
523
+ * A free-form `CHECK (predicate)` (Lucid/Knex `check`). The predicate is
524
+ * emitted verbatim — exactly as trusted as {@link Schema.raw}, so never
525
+ * build it from user input. Prefer the typed `check*` helpers, which are
526
+ * safe by construction.
527
+ */
528
+ check(predicate: string, constraintName?: string): this {
529
+ this.#pushConstraint({
530
+ constraint: "check",
531
+ name: constraintName,
532
+ expr: { check: "raw", predicate },
533
+ });
534
+ return this;
535
+ }
536
+
537
+ /** Drop named CHECK constraints (Lucid/Knex `dropChecks`). */
538
+ dropChecks(...constraintNames: string[]): this {
539
+ this.#assertAlterMode("dropChecks()");
540
+ for (const name of constraintNames) {
541
+ this.#pushStandaloneOp({ op: "dropConstraint", name });
542
+ }
543
+ return this;
544
+ }
545
+
546
+ // ─── Table-level constraints ──────────────────────────────
547
+
548
+ /**
549
+ * With no argument, mark the current column as the primary key (the
550
+ * existing column modifier). With a column list, declare a composite
551
+ * `PRIMARY KEY (…)` table constraint (Lucid/Knex `primary([...])`).
552
+ */
553
+ primary(columns?: readonly string[], constraintName?: string): this {
554
+ if (columns === undefined) {
555
+ if (this.#currentColumn) this.#currentColumn.primary = true;
556
+ return this;
557
+ }
558
+ this.#pushConstraint({
559
+ constraint: "primary",
560
+ name: constraintName,
561
+ columns: [...columns],
562
+ });
563
+ return this;
564
+ }
565
+
566
+ /**
567
+ * With no argument, mark the current column `UNIQUE` (the existing column
568
+ * modifier). With a column list, declare a composite `UNIQUE (…)` table
569
+ * constraint (Lucid/Knex `unique([...])`).
570
+ *
571
+ * Note this is a real constraint, unlike {@link uniqueIndex}, which creates
572
+ * a separate `CREATE UNIQUE INDEX`.
573
+ */
574
+ unique(columns?: readonly string[], constraintName?: string): this {
575
+ if (columns === undefined) {
576
+ if (this.#currentColumn) this.#currentColumn.unique = true;
577
+ return this;
578
+ }
579
+ this.#pushConstraint({
580
+ constraint: "unique",
581
+ name: constraintName ?? this.#constraintName(columns, "unique"),
582
+ columns: [...columns],
583
+ });
584
+ return this;
585
+ }
586
+
587
+ /**
588
+ * Declare a composite foreign key (Lucid/Knex
589
+ * `foreign([...]).references([...]).inTable(…)`). Returns a small chainable
590
+ * so the target reads in Knex order; the constraint is recorded up front
591
+ * and filled in as you chain.
592
+ */
593
+ foreign(
594
+ columns: string | readonly string[],
595
+ constraintName?: string,
596
+ ): ForeignKeyBuilder {
597
+ const cols = typeof columns === "string" ? [columns] : [...columns];
598
+ const references: ForeignKeyReference = { table: "", columns: [] };
599
+ this.#pushConstraint({
600
+ constraint: "foreign",
601
+ name: constraintName ?? this.#constraintName(cols, "foreign"),
602
+ columns: cols,
603
+ references,
604
+ });
605
+ // The constraint is already recorded; the builder fills `references` in
606
+ // place as the caller chains, so order of arrival doesn't matter.
607
+ return new ForeignKeyBuilder(references);
608
+ }
609
+
610
+ // ─── Dropping constraints ─────────────────────────────────
611
+
612
+ /** Drop the primary key (Lucid/Knex `dropPrimary`). MySQL drops it by keyword; Postgres by name (default `<table>_pkey`). */
613
+ dropPrimary(constraintName?: string): this {
614
+ this.#assertAlterMode("dropPrimary()");
615
+ this.#pushStandaloneOp({ op: "dropPrimary", name: constraintName });
616
+ return this;
617
+ }
618
+
619
+ /** Drop a unique constraint by columns (using the default name) or by explicit name (Lucid/Knex `dropUnique`). */
620
+ dropUnique(
621
+ columns: string | readonly string[],
622
+ constraintName?: string,
623
+ ): this {
624
+ this.#assertAlterMode("dropUnique()");
625
+ this.#pushStandaloneOp({
626
+ op: "dropUnique",
627
+ name: constraintName ?? this.#constraintName(columns, "unique"),
628
+ });
629
+ return this;
630
+ }
631
+
632
+ /** Drop a foreign key by columns (using the default name) or by explicit name (Lucid/Knex `dropForeign`). */
633
+ dropForeign(
634
+ columns: string | readonly string[],
635
+ constraintName?: string,
636
+ ): this {
637
+ this.#assertAlterMode("dropForeign()");
638
+ this.#pushStandaloneOp({
639
+ op: "dropForeign",
640
+ name: constraintName ?? this.#constraintName(columns, "foreign"),
641
+ });
642
+ return this;
643
+ }
644
+
645
+ /** Drop `created_at` + `updated_at` (Lucid/Knex `dropTimestamps`). */
646
+ dropTimestamps(): this {
647
+ return this.dropColumns("created_at", "updated_at");
648
+ }
649
+
650
+ // ─── Table options ────────────────────────────────────────
651
+
652
+ /** MySQL storage engine (Lucid/Knex `engine`). Ignored on pg/sqlite. */
653
+ engine(name: string): this {
654
+ this.#options.engine = name;
655
+ return this;
656
+ }
657
+
658
+ /** MySQL default charset (Lucid/Knex `charset`). Ignored on pg/sqlite. */
659
+ charset(name: string): this {
660
+ this.#options.charset = name;
661
+ return this;
662
+ }
663
+
664
+ /** MySQL default collation for the table. Named `tableCollate` because {@link collate} is the column modifier — see {@link comment}. */
665
+ tableCollate(name: string): this {
666
+ this.#options.collate = name;
667
+ return this;
668
+ }
669
+
670
+ /** Table comment. Named `tableComment` because {@link comment} is the column modifier — see there for why. */
671
+ tableComment(text: string): this {
672
+ this.#options.comment = text;
673
+ return this;
674
+ }
675
+
204
676
  // ─── Indexes ──────────────────────────────────────────────
205
677
 
206
678
  index(columns: string | string[], name?: string): this {
@@ -223,6 +695,86 @@ export class TableBuilder {
223
695
  return this;
224
696
  }
225
697
 
698
+ // ─── ALTER TABLE operations ───────────────────────────────
699
+
700
+ /**
701
+ * Apply the pending column definition as a type change instead of an
702
+ * `ADD COLUMN` (Lucid/Knex `alter()`). Must follow a column-type method.
703
+ *
704
+ * Nullability moves only if `.nullable()` / `.notNullable()` was called
705
+ * before this — a bare `t.string('x').alter()` changes the type and leaves
706
+ * the NOT NULL constraint exactly as it is.
707
+ *
708
+ * SQLite cannot alter a column in place; the Rust compiler rejects it with
709
+ * `E_UNSUPPORTED` rather than emitting a table rebuild behind your back.
710
+ */
711
+ alter(): this {
712
+ this.#assertAlterMode("alter()");
713
+ const pending = this.#currentOp;
714
+ if (!pending) {
715
+ throw new Error(
716
+ "E_ALTER_MISUSE: alter() must follow a column definition, e.g. table.string('email').alter()",
717
+ );
718
+ }
719
+ if (pending.op === "addColumn") {
720
+ const converted: AlterOperation = {
721
+ op: "alterColumn",
722
+ column: pending.column,
723
+ setNullable: this.#nullabilityTouched
724
+ ? pending.column.nullable
725
+ : undefined,
726
+ };
727
+ this.#operations[this.#operations.indexOf(pending)] = converted;
728
+ this.#currentOp = converted;
729
+ }
730
+ return this;
731
+ }
732
+
733
+ /** Drop a column (Lucid/Knex `dropColumn`). */
734
+ dropColumn(name: string): this {
735
+ this.#assertAlterMode("dropColumn()");
736
+ this.#pushStandaloneOp({ op: "dropColumn", name });
737
+ return this;
738
+ }
739
+
740
+ /** Drop several columns in call order (Lucid/Knex `dropColumns`). */
741
+ dropColumns(...names: string[]): this {
742
+ for (const name of names) this.dropColumn(name);
743
+ return this;
744
+ }
745
+
746
+ /** Rename a column (Lucid/Knex `renameColumn`). */
747
+ renameColumn(from: string, to: string): this {
748
+ this.#assertAlterMode("renameColumn()");
749
+ this.#pushStandaloneOp({ op: "renameColumn", from, to });
750
+ return this;
751
+ }
752
+
753
+ /**
754
+ * Make an existing column nullable — `DROP NOT NULL` (Lucid/Knex
755
+ * `setNullable`).
756
+ *
757
+ * **Deviation from Knex, named deliberately.** Knex supports this on every
758
+ * dialect by querying `columnInfo()` at runtime to recover the column's
759
+ * type. Atlas compiles SQL synchronously in Rust with no round-trip, so
760
+ * this is Postgres-only — Postgres is the one dialect whose syntax needs no
761
+ * type. On MySQL use `table.<type>('col').nullable().alter()`, which
762
+ * restates the type; SQLite cannot alter a column in place at all. Both
763
+ * raise `E_UNSUPPORTED` with the alternative spelled out.
764
+ */
765
+ setNullable(name: string): this {
766
+ this.#assertAlterMode("setNullable()");
767
+ this.#pushStandaloneOp({ op: "setNullable", name, nullable: true });
768
+ return this;
769
+ }
770
+
771
+ /** Make an existing column `NOT NULL` (Lucid/Knex `dropNullable`). Postgres-only — see {@link setNullable}. */
772
+ dropNullable(name: string): this {
773
+ this.#assertAlterMode("dropNullable()");
774
+ this.#pushStandaloneOp({ op: "setNullable", name, nullable: false });
775
+ return this;
776
+ }
777
+
226
778
  // ─── Accessors ────────────────────────────────────────────
227
779
 
228
780
  getColumns(): ColumnDefinition[] {
@@ -231,33 +783,152 @@ export class TableBuilder {
231
783
  getIndexes(): IndexDefinition[] {
232
784
  return [...this.#indexes];
233
785
  }
786
+ /** Ordered ALTER TABLE operations. Empty in `create` mode. */
787
+ getOperations(): AlterOperation[] {
788
+ return [...this.#operations];
789
+ }
234
790
 
235
791
  /** Compile to SQL statements via the Rust compiler. */
236
- toStatements(dialect: AtlasDialect = getAtlasDialect()): string[] {
237
- const spec = {
238
- kind: "createTable",
239
- table: this.tableName,
240
- columns: this.#columns.map((c) => ({
241
- name: c.name,
242
- kind: TYPE_KIND_MAP[c.type],
243
- length: c.length ?? null,
244
- precision: c.precision ?? null,
245
- scale: c.scale ?? null,
246
- nullable: c.nullable,
247
- primary: c.primary,
248
- autoIncrement: c.autoIncrement ?? false,
249
- unique: c.unique,
250
- default: c.defaultValue ?? null,
251
- references: c.references ?? null,
252
- })),
253
- indexes: this.#indexes.map((i) => ({
254
- name: i.name,
255
- columns: i.columns,
256
- unique: i.unique,
257
- })),
258
- ifNotExists: false,
792
+ toStatements(
793
+ dialect: AtlasDialect = getAtlasDialect(),
794
+ options: { ifNotExists?: boolean } = {},
795
+ ): string[] {
796
+ const spec =
797
+ this.mode === "alter"
798
+ ? {
799
+ kind: "alterTable",
800
+ table: this.tableName,
801
+ operations: this.#operations.map((op) =>
802
+ op.op === "addColumn"
803
+ ? { op: op.op, column: this.#serializeColumn(op.column) }
804
+ : op.op === "alterColumn"
805
+ ? {
806
+ op: op.op,
807
+ column: this.#serializeColumn(op.column),
808
+ setNullable: op.setNullable ?? null,
809
+ }
810
+ : op,
811
+ ),
812
+ }
813
+ : {
814
+ kind: "createTable",
815
+ table: this.tableName,
816
+ columns: this.#columns.map((c) => this.#serializeColumn(c)),
817
+ indexes: this.#indexes.map((i) => ({
818
+ name: i.name,
819
+ columns: i.columns,
820
+ unique: i.unique,
821
+ })),
822
+ ifNotExists: options.ifNotExists ?? false,
823
+ constraints: this.#constraints,
824
+ options: this.#options,
825
+ };
826
+ const statements = compileStatementNative(spec, dialect).statements;
827
+ // `alterTable` carries no index list — an index added alongside an
828
+ // ALTER compiles to its own CREATE INDEX, appended in declaration order.
829
+ if (this.mode === "alter" && this.#indexes.length > 0) {
830
+ for (const idx of this.#indexes) {
831
+ statements.push(
832
+ ...compileStatementNative(
833
+ {
834
+ kind: "createIndex",
835
+ table: this.tableName,
836
+ name: idx.name,
837
+ columns: idx.columns,
838
+ unique: idx.unique,
839
+ },
840
+ dialect,
841
+ ).statements,
842
+ );
843
+ }
844
+ }
845
+ return statements;
846
+ }
847
+
848
+ /** Flatten a column into the wire shape the Rust `ColumnDef` deserialises. */
849
+ #serializeColumn(c: ColumnDefinition): Record<string, unknown> {
850
+ return {
851
+ name: c.name,
852
+ kind: TYPE_KIND_MAP[c.type],
853
+ length: c.length ?? null,
854
+ precision: c.precision ?? null,
855
+ scale: c.scale ?? null,
856
+ // Flattened into the Rust ColumnTypeSpec — each read for one kind only.
857
+ values: c.values ?? null,
858
+ rawType: c.rawType ?? null,
859
+ nullable: c.nullable,
860
+ primary: c.primary,
861
+ autoIncrement: c.autoIncrement ?? false,
862
+ unique: c.unique,
863
+ unsigned: c.unsigned ?? false,
864
+ default: c.defaultValue ?? null,
865
+ references: c.references ?? null,
866
+ comment: c.comment ?? null,
867
+ collate: c.collate ?? null,
868
+ position: c.position ?? null,
259
869
  };
260
- return compileStatementNative(spec, dialect).statements;
870
+ }
871
+
872
+ /**
873
+ * Record a constraint. In `create` mode it renders inside the
874
+ * `CREATE TABLE`; in `alter` mode it becomes an `ADD CONSTRAINT`, kept in
875
+ * call order with the surrounding column operations.
876
+ */
877
+ #pushConstraint(spec: TableConstraintSpec): void {
878
+ if (this.mode === "alter") {
879
+ this.#operations.push({ op: "addConstraint", constraint: spec });
880
+ } else {
881
+ this.#constraints.push(spec);
882
+ }
883
+ }
884
+
885
+ /** Build a CHECK against the pending column. */
886
+ #addCheck(
887
+ build: (column: string) => CheckExpression,
888
+ constraintName?: string,
889
+ ): this {
890
+ const column = this.#currentColumn?.name;
891
+ if (!column) {
892
+ throw new Error(
893
+ "E_CHECK_MISUSE: a check* helper must follow a column definition, e.g. table.integer('qty').checkPositive()",
894
+ );
895
+ }
896
+ this.#pushConstraint({
897
+ constraint: "check",
898
+ name: constraintName,
899
+ expr: build(column),
900
+ });
901
+ return this;
902
+ }
903
+
904
+ /**
905
+ * Default constraint name, following Knex's `<table>_<columns>_<suffix>`
906
+ * convention so `unique([...])` and `dropUnique([...])` agree without the
907
+ * caller naming anything. Distinct from {@link uniqueIndex}, which names a
908
+ * separate INDEX object `idx_…`.
909
+ */
910
+ #constraintName(
911
+ columns: string | readonly string[],
912
+ suffix: "unique" | "foreign",
913
+ ): string {
914
+ const cols = typeof columns === "string" ? [columns] : columns;
915
+ return `${this.tableName}_${cols.join("_")}_${suffix}`;
916
+ }
917
+
918
+ #assertAlterMode(method: string): void {
919
+ if (this.mode !== "alter") {
920
+ throw new Error(
921
+ `E_ALTER_MISUSE: ${method} is only available inside schema.alterTable() — a new table has nothing to alter`,
922
+ );
923
+ }
924
+ }
925
+
926
+ /** Record an op that takes no column modifiers, so `.nullable()` etc. can't silently attach to it. */
927
+ #pushStandaloneOp(op: AlterOperation): void {
928
+ this.#operations.push(op);
929
+ this.#currentColumn = undefined;
930
+ this.#currentOp = undefined;
931
+ this.#nullabilityTouched = false;
261
932
  }
262
933
 
263
934
  #addColumn(name: string, type: ColumnType): this {
@@ -270,6 +941,29 @@ export class TableBuilder {
270
941
  };
271
942
  this.#columns.push(col);
272
943
  this.#currentColumn = col;
944
+ this.#nullabilityTouched = false;
945
+ if (this.mode === "alter") {
946
+ const op: Extract<AlterOperation, { op: "addColumn" }> = {
947
+ op: "addColumn",
948
+ column: col,
949
+ };
950
+ this.#operations.push(op);
951
+ this.#currentOp = op;
952
+ }
953
+ return this;
954
+ }
955
+
956
+ #addFloat(
957
+ name: string,
958
+ type: "float" | "double",
959
+ precision?: number,
960
+ scale?: number,
961
+ ): this {
962
+ this.#addColumn(name, type);
963
+ if (this.#currentColumn) {
964
+ this.#currentColumn.precision = precision;
965
+ this.#currentColumn.scale = scale;
966
+ }
273
967
  return this;
274
968
  }
275
969