@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,236 @@
1
+ /**
2
+ * Dialect-aware catalog queries — "which base tables exist right now".
3
+ *
4
+ * The single source of truth for listing user tables, shared by the migration
5
+ * runner's drop/wipe and the test-time `truncateAll`. Each query hits the
6
+ * dialect's own catalog (`sqlite_master`, `pg_tables`, `information_schema`);
7
+ * they are framework introspection, not user queries, so they stay raw SQL.
8
+ */
9
+
10
+ import { AtlasError } from "../errors.js";
11
+ import type { AtlasDialect } from "../query/native.js";
12
+
13
+ /**
14
+ * The minimal connection surface these helpers need — just `query`/`execute`.
15
+ * Narrower than `AsyncDatabaseConnection` on purpose, so the migration runner's
16
+ * `DatabaseAdapter` (which has no `dialect`/`ping`) satisfies it too.
17
+ */
18
+ export interface CatalogConnection {
19
+ query<T = Record<string, unknown>>(
20
+ sql: string,
21
+ params?: unknown[],
22
+ ): Promise<T[]>;
23
+ // Return value is ignored — the two adapter shapes disagree on it
24
+ // (`void` vs `{ rowsAffected }`), and these helpers only run it for effect.
25
+ execute(sql: string, params?: unknown[]): Promise<unknown>;
26
+ /**
27
+ * Optional: run a batch of statements atomically on ONE pinned pooled
28
+ * connection. When present, {@link runWithoutForeignKeys} uses it so the FK
29
+ * toggle and the operations can't scatter across the pool.
30
+ */
31
+ runInTransaction?(
32
+ batch: readonly { sql: string; params?: unknown[] }[],
33
+ ): Promise<number>;
34
+ /**
35
+ * Optional MANAGED interactive transaction pinned to ONE connection (Lucid
36
+ * `db.transaction(cb)`). When present, {@link runWithoutForeignKeys} uses it
37
+ * on MySQL so the FK restore runs in a real `finally` on that same connection.
38
+ */
39
+ transaction?<T>(callback: (trx: CatalogConnection) => Promise<T>): Promise<T>;
40
+ }
41
+
42
+ /**
43
+ * Prefix for framework-private tables (migrations bookkeeping), following the
44
+ * same `ream_`-prefix convention as AdonisJS's `adonis_`.
45
+ */
46
+ const FRAMEWORK_PREFIX = "ream_";
47
+
48
+ export interface ListTablesOptions {
49
+ /**
50
+ * Include `ream_*` framework tables (the migrations table). Off by default
51
+ * so cleanup helpers leave the bookkeeping intact; `fresh()` turns it on
52
+ * because it re-creates the tracking table afterwards.
53
+ */
54
+ includeFrameworkTables?: boolean;
55
+ /**
56
+ * PostgreSQL only — restrict the listing to these schemas instead of just the
57
+ * current one (Adonis Lucid `schemaGeneration.schemas`). Ignored on
58
+ * sqlite/mysql, which have no schema namespace of this kind.
59
+ */
60
+ schemas?: string[];
61
+ }
62
+
63
+ /** List every base table in the current schema/database, for `dialect`. */
64
+ export async function listUserTables(
65
+ db: CatalogConnection,
66
+ dialect: AtlasDialect,
67
+ options: ListTablesOptions = {},
68
+ ): Promise<string[]> {
69
+ let sql: string;
70
+ const params: unknown[] = [];
71
+ switch (dialect) {
72
+ case "sqlite":
73
+ sql =
74
+ "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'";
75
+ break;
76
+ case "postgres":
77
+ // Restrict to the given schemas (Lucid `schemas`) or the current one.
78
+ // Bind each schema as its own scalar placeholder — atlas's driver binds
79
+ // arrays as text, so `schemaname = ANY($1)` would fail; an IN list works.
80
+ if (options.schemas && options.schemas.length > 0) {
81
+ const placeholders = options.schemas.map((_, i) => `$${i + 1}`);
82
+ params.push(...options.schemas);
83
+ sql = `SELECT tablename AS name FROM pg_tables WHERE schemaname IN (${placeholders.join(", ")})`;
84
+ } else {
85
+ sql =
86
+ "SELECT tablename AS name FROM pg_tables WHERE schemaname = current_schema()";
87
+ }
88
+ break;
89
+ case "mysql":
90
+ // CAST to CHAR: MySQL returns information_schema identifier columns as
91
+ // binary (Uint8Array), which the string filter below would drop.
92
+ sql =
93
+ "SELECT CAST(table_name AS CHAR) AS name FROM information_schema.tables WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'";
94
+ break;
95
+ }
96
+ const rows = await db.query<{ name: unknown }>(sql, params);
97
+ const names: string[] = [];
98
+ for (const row of rows) {
99
+ if (typeof row.name !== "string") continue;
100
+ if (
101
+ !options.includeFrameworkTables &&
102
+ row.name.startsWith(FRAMEWORK_PREFIX)
103
+ ) {
104
+ continue;
105
+ }
106
+ names.push(row.name);
107
+ }
108
+ return names;
109
+ }
110
+
111
+ /**
112
+ * Does base table `name` exist right now, for `dialect`? The name is passed as a
113
+ * bound parameter (never interpolated) so this is injection-safe on every
114
+ * dialect. Backs `Schema.hasTable` (Adonis Lucid parity).
115
+ */
116
+ export async function tableExists(
117
+ db: CatalogConnection,
118
+ dialect: AtlasDialect,
119
+ name: string,
120
+ ): Promise<boolean> {
121
+ const ph = dialect === "postgres" ? "$1" : "?";
122
+ let sql: string;
123
+ switch (dialect) {
124
+ case "sqlite":
125
+ sql = `SELECT 1 FROM sqlite_master WHERE type='table' AND name = ${ph}`;
126
+ break;
127
+ case "postgres":
128
+ sql = `SELECT 1 FROM pg_tables WHERE schemaname = current_schema() AND tablename = ${ph}`;
129
+ break;
130
+ case "mysql":
131
+ sql = `SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ${ph} AND table_type = 'BASE TABLE'`;
132
+ break;
133
+ }
134
+ const rows = await db.query(sql, [name]);
135
+ return rows.length > 0;
136
+ }
137
+
138
+ /**
139
+ * Does column `column` exist on table `table` right now, for `dialect`? Both
140
+ * names are bound parameters. Backs `Schema.hasColumn` (Adonis Lucid parity).
141
+ */
142
+ export async function columnExists(
143
+ db: CatalogConnection,
144
+ dialect: AtlasDialect,
145
+ table: string,
146
+ column: string,
147
+ ): Promise<boolean> {
148
+ if (dialect === "sqlite") {
149
+ // PRAGMA introspection via the table-valued function form, which accepts a
150
+ // bound table-name argument (unlike `PRAGMA table_info(x)`).
151
+ const rows = await db.query(
152
+ "SELECT 1 FROM pragma_table_info(?) WHERE name = ?",
153
+ [table, column],
154
+ );
155
+ return rows.length > 0;
156
+ }
157
+ const [p1, p2] = dialect === "postgres" ? ["$1", "$2"] : ["?", "?"];
158
+ const schemaPredicate =
159
+ dialect === "postgres"
160
+ ? "table_schema = current_schema()"
161
+ : "table_schema = DATABASE()";
162
+ const rows = await db.query(
163
+ `SELECT 1 FROM information_schema.columns WHERE ${schemaPredicate} AND table_name = ${p1} AND column_name = ${p2}`,
164
+ [table, column],
165
+ );
166
+ return rows.length > 0;
167
+ }
168
+
169
+ /**
170
+ * Run `fn` with foreign-key enforcement suspended, then restore it — the toggle
171
+ * runs even if `fn` throws. Lets a bulk drop/truncate ignore inter-table FK
172
+ * order. Postgres has no session-level switch (it uses `TRUNCATE … CASCADE` /
173
+ * `DROP … CASCADE` instead), so this is a no-op there.
174
+ */
175
+ export async function runWithoutForeignKeys(
176
+ db: CatalogConnection,
177
+ dialect: AtlasDialect,
178
+ statements: ReadonlyArray<{ sql: string; params?: unknown[] }>,
179
+ ): Promise<void> {
180
+ if (statements.length === 0) return;
181
+
182
+ // MySQL: `SET FOREIGN_KEY_CHECKS` is a SESSION variable (not transactional),
183
+ // so it MUST be restored in a real `finally` on the SAME pinned connection —
184
+ // otherwise a mid-batch failure leaves the pooled connection with FK checks
185
+ // off. Use the managed interactive transaction: SET 0 → ops → finally SET 1,
186
+ // all on the one pinned connection, restore guaranteed even on error.
187
+ if (dialect === "mysql") {
188
+ // MySQL `SET FOREIGN_KEY_CHECKS` is a SESSION variable (not transactional),
189
+ // so it MUST be restored in a real `finally` on the SAME pinned connection.
190
+ // That needs the managed interactive transaction: SET 0 → ops → finally
191
+ // SET 1, restore guaranteed even on error. Without transaction() there is
192
+ // no safe restore — a mid-batch failure would leave the pooled connection
193
+ // with FK checks OFF (a poisoned connection). Refuse rather than corrupt.
194
+ if (!db.transaction) {
195
+ throw new AtlasError(
196
+ "E_MYSQL_FK_REQUIRES_TRANSACTION",
197
+ "Suspending MySQL foreign-key checks needs an interactive transaction() to restore them in a finally — a session-level SET can't be rolled back, so a failure mid-batch would leave the pooled connection with FK checks disabled. This adapter has none.",
198
+ {
199
+ hint: "Use a real connection (createNapiConnection) or an adapter that implements transaction().",
200
+ },
201
+ );
202
+ }
203
+ await db.transaction(async (trx) => {
204
+ try {
205
+ await trx.execute("SET FOREIGN_KEY_CHECKS = 0");
206
+ for (const stmt of statements) {
207
+ await trx.execute(stmt.sql, stmt.params);
208
+ }
209
+ } finally {
210
+ await trx.execute("SET FOREIGN_KEY_CHECKS = 1");
211
+ }
212
+ });
213
+ return;
214
+ }
215
+
216
+ // sqlite/postgres: run the FK toggle + ops on ONE pinned connection via
217
+ // runInTransaction so a pool can't scatter the connection-local toggle away
218
+ // from the ops.
219
+ // - sqlite: `PRAGMA defer_foreign_keys` is transaction-scoped and auto-resets
220
+ // at txn end (no leak); plain `PRAGMA foreign_keys` is ignored in a txn;
221
+ // - postgres: no session toggle — drops use CASCADE and `truncateAll` uses
222
+ // `TRUNCATE … CASCADE`, so pg statements are already FK-safe.
223
+ const batch: Array<{ sql: string; params?: unknown[] }> = [];
224
+ if (dialect === "sqlite") {
225
+ batch.push({ sql: "PRAGMA defer_foreign_keys = ON" });
226
+ }
227
+ batch.push(...statements);
228
+ if (db.runInTransaction) {
229
+ await db.runInTransaction(batch);
230
+ return;
231
+ }
232
+ // No transaction support at all (a bare fake): best effort, single connection.
233
+ for (const stmt of batch) {
234
+ await db.execute(stmt.sql, stmt.params);
235
+ }
236
+ }
@@ -49,15 +49,17 @@ export async function introspectTable(
49
49
  db: SchemaIntrospectable,
50
50
  dialect: AtlasDialect,
51
51
  table: string,
52
+ schema?: string,
52
53
  ): Promise<IntrospectedColumn[] | null> {
53
54
  assertIdent(table);
55
+ if (schema !== undefined) assertIdent(schema);
54
56
  switch (dialect) {
55
57
  case "sqlite":
56
58
  return introspectSqlite(db, table);
57
59
  case "postgres":
58
- return introspectPostgres(db, table);
60
+ return introspectPostgres(db, table, schema);
59
61
  case "mysql":
60
- return introspectMysql(db, table);
62
+ return introspectMysql(db, table, schema);
61
63
  }
62
64
  }
63
65
 
@@ -79,13 +81,17 @@ async function introspectSqlite(
79
81
  async function introspectPostgres(
80
82
  db: SchemaIntrospectable,
81
83
  table: string,
84
+ schema?: string,
82
85
  ): Promise<IntrospectedColumn[] | null> {
86
+ // Target a specific schema when given (Lucid `schemas`), else the current one.
87
+ const schemaPred = schema ? "$2" : "current_schema()";
88
+ const args = schema ? [table, schema] : [table];
83
89
  const cols = await db.query(
84
90
  `SELECT column_name, data_type, is_nullable, column_default
85
91
  FROM information_schema.columns
86
- WHERE table_schema = current_schema() AND table_name = $1
92
+ WHERE table_schema = ${schemaPred} AND table_name = $1
87
93
  ORDER BY ordinal_position`,
88
- [table],
94
+ args,
89
95
  );
90
96
  if (cols.length === 0) return null;
91
97
  const pkRows = await db.query(
@@ -94,8 +100,9 @@ async function introspectPostgres(
94
100
  JOIN information_schema.key_column_usage kcu
95
101
  ON kcu.constraint_name = tc.constraint_name
96
102
  AND kcu.table_schema = tc.table_schema
97
- WHERE tc.table_name = $1 AND tc.constraint_type = 'PRIMARY KEY'`,
98
- [table],
103
+ WHERE tc.table_name = $1 AND tc.constraint_type = 'PRIMARY KEY'
104
+ AND tc.table_schema = ${schemaPred}`,
105
+ args,
99
106
  );
100
107
  const pks = new Set(pkRows.map((r) => String(r.column_name)));
101
108
  return cols.map((r) => ({
@@ -110,13 +117,23 @@ async function introspectPostgres(
110
117
  async function introspectMysql(
111
118
  db: SchemaIntrospectable,
112
119
  table: string,
120
+ schema?: string,
113
121
  ): Promise<IntrospectedColumn[] | null> {
122
+ // In MySQL a "schema" IS a database; target it when given, else DATABASE().
123
+ const schemaPred = schema ? "?" : "DATABASE()";
124
+ const args = schema ? [schema, table] : [table];
125
+ // CAST the identifier/enum columns to CHAR: MySQL returns information_schema
126
+ // text as binary (Uint8Array), which `String(...)` would turn into byte lists.
114
127
  const rows = await db.query(
115
- `SELECT column_name, data_type, is_nullable, column_default, column_key
128
+ `SELECT CAST(column_name AS CHAR) AS column_name,
129
+ CAST(data_type AS CHAR) AS data_type,
130
+ CAST(is_nullable AS CHAR) AS is_nullable,
131
+ column_default,
132
+ CAST(column_key AS CHAR) AS column_key
116
133
  FROM information_schema.columns
117
- WHERE table_schema = DATABASE() AND table_name = ?
134
+ WHERE table_schema = ${schemaPred} AND table_name = ?
118
135
  ORDER BY ordinal_position`,
119
- [table],
136
+ args,
120
137
  );
121
138
  if (rows.length === 0) return null;
122
139
  return rows.map((r) => ({
@@ -6,33 +6,69 @@
6
6
  export type ColumnType =
7
7
  | "string"
8
8
  | "text"
9
+ | "mediumtext"
10
+ | "longtext"
9
11
  | "integer"
12
+ | "tinyint"
13
+ | "smallint"
14
+ | "mediumint"
10
15
  | "bigInteger"
11
16
  | "decimal"
17
+ | "float"
18
+ | "double"
12
19
  | "boolean"
13
20
  | "date"
21
+ | "time"
14
22
  | "timestamp"
15
23
  | "timestamptz"
16
24
  | "uuid"
17
25
  | "json"
18
- | "binary";
26
+ | "jsonb"
27
+ | "binary"
28
+ | "enum"
29
+ | "specificType";
19
30
 
20
31
  /** Maps our logical type names to the ColumnTypeKind expected by the Rust compiler. */
21
32
  export const TYPE_KIND_MAP: Record<ColumnType, string> = {
22
33
  string: "string",
23
34
  text: "text",
35
+ mediumtext: "mediumText",
36
+ longtext: "longText",
24
37
  integer: "integer",
38
+ tinyint: "tinyInt",
39
+ smallint: "smallInt",
40
+ mediumint: "mediumInt",
25
41
  bigInteger: "bigInteger",
26
42
  decimal: "decimal",
43
+ float: "float",
44
+ double: "double",
27
45
  boolean: "boolean",
28
46
  date: "date",
47
+ time: "time",
29
48
  timestamp: "timestamp",
30
49
  timestamptz: "timestamptz",
31
50
  uuid: "uuid",
32
51
  json: "json",
52
+ jsonb: "jsonb",
33
53
  binary: "binary",
54
+ enum: "enum",
55
+ specificType: "specificType",
34
56
  };
35
57
 
58
+ /** MySQL text width (Lucid/Knex `text(name, textType)`). `TEXT` on pg/sqlite. */
59
+ export type TextVariant = "text" | "mediumtext" | "longtext";
60
+
61
+ /**
62
+ * SQL referential action for a foreign key's `ON DELETE` / `ON UPDATE`
63
+ * (Lucid parity). Validated case-insensitively by the Rust compiler.
64
+ */
65
+ export type ReferentialAction =
66
+ | "cascade"
67
+ | "restrict"
68
+ | "set null"
69
+ | "set default"
70
+ | "no action";
71
+
36
72
  export interface ColumnDefinition {
37
73
  name: string;
38
74
  type: ColumnType;
@@ -44,8 +80,29 @@ export interface ColumnDefinition {
44
80
  /** Dialect-appropriate auto-increment / identity column (Lucid `increments`). Implies primary key. */
45
81
  autoIncrement?: boolean;
46
82
  unique: boolean;
83
+ /** MySQL `UNSIGNED` numeric modifier (Lucid `unsigned()`). No-op on pg/sqlite. */
84
+ unsigned?: boolean;
85
+ /** Allowed values for an `enum` column. */
86
+ values?: string[];
87
+ /**
88
+ * Verbatim SQL type for a `specificType` column. Validated by the Rust
89
+ * compiler against a narrow grammar before it reaches DDL — it is
90
+ * interpolated, not bound.
91
+ */
92
+ rawType?: string;
93
+ /** Column comment. Inline on MySQL, `COMMENT ON COLUMN` on pg, dropped on SQLite. */
94
+ comment?: string;
95
+ /** Column collation, e.g. `utf8mb4_unicode_ci`. Validated as an identifier. */
96
+ collate?: string;
97
+ /** MySQL-only placement of an added column (`FIRST` / `AFTER col`). */
98
+ position?: ColumnPosition;
47
99
  defaultValue?: string;
48
- references?: { table: string; column: string };
100
+ references?: {
101
+ table: string;
102
+ column: string;
103
+ onDelete?: ReferentialAction;
104
+ onUpdate?: ReferentialAction;
105
+ };
49
106
  }
50
107
 
51
108
  export interface IndexDefinition {
@@ -53,3 +110,81 @@ export interface IndexDefinition {
53
110
  columns: string[];
54
111
  unique: boolean;
55
112
  }
113
+
114
+ /** MySQL-only placement of an added column. Mirrors the Rust `ColumnPosition`. */
115
+ export type ColumnPosition = { at: "first" } | { at: "after"; column: string };
116
+
117
+ /** A scalar a CHECK constraint can compare against. DDL cannot bind params — these are quoted, not bound. */
118
+ export type CheckValue = string | number | boolean | null;
119
+
120
+ /**
121
+ * A CHECK predicate. Structured rather than free-form SQL so each variant is
122
+ * safe by construction; `raw` is the escape hatch and is exactly as trusted as
123
+ * `schema.raw()`. Mirrors the Rust `CheckExpr` tagged union.
124
+ */
125
+ export type CheckExpression =
126
+ | { check: "positive"; column: string }
127
+ | { check: "negative"; column: string }
128
+ | { check: "in"; column: string; values: CheckValue[] }
129
+ | { check: "notIn"; column: string; values: CheckValue[] }
130
+ | { check: "between"; column: string; ranges: CheckValue[][] }
131
+ | { check: "length"; column: string; operator: string; length: number }
132
+ | { check: "regex"; column: string; pattern: string }
133
+ | { check: "raw"; predicate: string };
134
+
135
+ /** Comparison operator accepted by `checkLength` (Lucid/Knex). */
136
+ export type CheckOperator = "=" | "!=" | "<>" | "<" | "<=" | ">" | ">=";
137
+
138
+ /** A multi-column foreign key target. Mirrors the Rust `ForeignKeyRefMulti`. */
139
+ export interface ForeignKeyReference {
140
+ table: string;
141
+ columns: string[];
142
+ onDelete?: ReferentialAction;
143
+ onUpdate?: ReferentialAction;
144
+ }
145
+
146
+ /** A table-level constraint. Mirrors the Rust `TableConstraint` tagged union. */
147
+ export type TableConstraintSpec =
148
+ | { constraint: "primary"; name?: string; columns: string[] }
149
+ | { constraint: "unique"; name?: string; columns: string[] }
150
+ | {
151
+ constraint: "foreign";
152
+ name?: string;
153
+ columns: string[];
154
+ references: ForeignKeyReference;
155
+ }
156
+ | { constraint: "check"; name?: string; expr: CheckExpression };
157
+
158
+ /** Storage options for `CREATE TABLE`. Mirrors the Rust `TableOptions`. */
159
+ export interface TableOptionsSpec {
160
+ engine?: string;
161
+ charset?: string;
162
+ collate?: string;
163
+ comment?: string;
164
+ }
165
+
166
+ /**
167
+ * One ALTER TABLE operation, in call order (Lucid/Knex semantics). Mirrors the
168
+ * Rust `AlterOp` tagged union — the `op` tags and field names are the wire
169
+ * contract with `compile_alter_table`.
170
+ */
171
+ export type AlterOperation =
172
+ | { op: "addColumn"; column: ColumnDefinition }
173
+ | { op: "dropColumn"; name: string }
174
+ | { op: "renameColumn"; from: string; to: string }
175
+ | {
176
+ op: "alterColumn";
177
+ column: ColumnDefinition;
178
+ /**
179
+ * Tri-state. `undefined` leaves nullability untouched so a bare type
180
+ * change never silently adds a NOT NULL — only an explicit
181
+ * `.nullable()` / `.notNullable()` before `.alter()` sets it.
182
+ */
183
+ setNullable?: boolean;
184
+ }
185
+ | { op: "setNullable"; name: string; nullable: boolean }
186
+ | { op: "addConstraint"; constraint: TableConstraintSpec }
187
+ | { op: "dropConstraint"; name: string }
188
+ | { op: "dropPrimary"; name?: string }
189
+ | { op: "dropUnique"; name: string }
190
+ | { op: "dropForeign"; name: string };
package/src/seeders.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@c9up/atlas/seeders` — Adonis Lucid seeders parity subpath. The `BaseSeeder`
3
+ * base class plus the runners and the `make:seeder` / `db:seed` console commands.
4
+ */
5
+
6
+ export {
7
+ dbSeedCommand,
8
+ makeSeederCommand,
9
+ type SeederCommandOptions,
10
+ } from "./console/seederCommands.js";
11
+ export {
12
+ BaseSeeder,
13
+ runSeederDirectory,
14
+ runSeeders,
15
+ Seeder,
16
+ } from "./schema/Seeder.js";