@an5/orm 1.0.8 → 1.1.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 (73) hide show
  1. package/README.md +174 -175
  2. package/dist/an5Metadata.js +64 -0
  3. package/dist/an5Orm.d.ts +92 -3
  4. package/dist/an5Orm.js +697 -206
  5. package/dist/config.d.ts +9 -1
  6. package/dist/config.js +13 -18
  7. package/dist/errors.d.ts +1 -1
  8. package/dist/errors.js +1 -1
  9. package/dist/generator/src/api.d.ts +35 -0
  10. package/dist/generator/src/api.js +58 -0
  11. package/dist/generator/src/code-generator.d.ts +14 -13
  12. package/dist/generator/src/code-generator.js +249 -225
  13. package/dist/generator/src/config.d.ts +162 -0
  14. package/dist/generator/src/config.js +354 -0
  15. package/dist/generator/src/dialect.d.ts +88 -0
  16. package/dist/generator/src/dialect.js +318 -0
  17. package/dist/generator/src/dotnet-generator.d.ts +21 -11
  18. package/dist/generator/src/dotnet-generator.js +1053 -546
  19. package/dist/generator/src/field-types.d.ts +96 -0
  20. package/dist/generator/src/field-types.js +433 -0
  21. package/dist/generator/src/golang-generator.d.ts +36 -0
  22. package/dist/generator/src/golang-generator.js +1229 -0
  23. package/dist/generator/src/index.d.ts +1 -1
  24. package/dist/generator/src/index.js +137 -88
  25. package/dist/generator/src/metadata-generator.d.ts +11 -8
  26. package/dist/generator/src/metadata-generator.js +105 -90
  27. package/dist/generator/src/parser.d.ts +37 -11
  28. package/dist/generator/src/parser.js +208 -206
  29. package/dist/generator/src/push-apply.d.ts +37 -0
  30. package/dist/generator/src/push-apply.js +109 -0
  31. package/dist/generator/src/push-schema.d.ts +93 -0
  32. package/dist/generator/src/push-schema.js +189 -0
  33. package/dist/generator/src/python-generator.d.ts +37 -9
  34. package/dist/generator/src/python-generator.js +428 -105
  35. package/dist/generator/src/rust-generator.d.ts +38 -0
  36. package/dist/generator/src/rust-generator.js +971 -0
  37. package/dist/generator/src/suggest.d.ts +17 -0
  38. package/dist/generator/src/suggest.js +45 -0
  39. package/dist/generator/src/type-kinds.d.ts +27 -0
  40. package/dist/generator/src/type-kinds.js +72 -0
  41. package/dist/generator/src/types.d.ts +60 -27
  42. package/dist/generator/src/types.js +41 -2
  43. package/dist/index.d.ts +3 -2
  44. package/dist/index.js +19 -8
  45. package/dist/logger.js +1 -1
  46. package/dist/migration-core.d.ts +102 -0
  47. package/dist/migration-core.js +731 -0
  48. package/dist/orm.d.ts +147 -0
  49. package/dist/orm.js +1654 -0
  50. package/dist/provider-support.d.ts +27 -0
  51. package/dist/provider-support.js +50 -0
  52. package/dist/scripts/release-cli.d.ts +2 -2
  53. package/dist/scripts/release-cli.js +115 -115
  54. package/dist/sql-utils.d.ts +3 -1
  55. package/dist/sql-utils.js +94 -24
  56. package/generator/src/api.ts +45 -0
  57. package/generator/src/code-generator.ts +259 -230
  58. package/generator/src/config.ts +496 -0
  59. package/generator/src/dialect.ts +415 -0
  60. package/generator/src/dotnet-generator.ts +1071 -544
  61. package/generator/src/field-types.ts +473 -0
  62. package/generator/src/golang-generator.ts +1267 -0
  63. package/generator/src/index.ts +146 -116
  64. package/generator/src/metadata-generator.ts +116 -101
  65. package/generator/src/parser.ts +234 -202
  66. package/generator/src/push-apply.ts +148 -0
  67. package/generator/src/push-schema.ts +250 -0
  68. package/generator/src/python-generator.ts +480 -114
  69. package/generator/src/rust-generator.ts +974 -0
  70. package/generator/src/suggest.ts +41 -0
  71. package/generator/src/type-kinds.ts +78 -0
  72. package/generator/src/types.ts +77 -29
  73. package/package.json +32 -6
@@ -1,202 +1,234 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import { Model, Field, Relation } from './types';
4
-
5
- // SQL Server type → TypeScript type mapping
6
- const AN5_TO_TS: Record<string, string> = {
7
- // String types
8
- 'NVARCHAR': 'string',
9
- 'VARCHAR': 'string',
10
- 'CHAR': 'string',
11
- 'NCHAR': 'string',
12
- 'TEXT': 'string',
13
- 'NTEXT': 'string',
14
- 'XML': 'string',
15
- // Numeric types
16
- 'INT': 'number',
17
- 'SMALLINT': 'number',
18
- 'TINYINT': 'number',
19
- 'BIGINT': 'number | bigint',
20
- 'FLOAT': 'number',
21
- 'REAL': 'number',
22
- 'DECIMAL': 'number',
23
- 'NUMERIC': 'number',
24
- 'MONEY': 'number',
25
- 'SMALLMONEY': 'number',
26
- // Boolean
27
- 'BIT': 'boolean',
28
- // Date types
29
- 'DATETIME': 'Date',
30
- 'DATETIME2': 'Date',
31
- 'SMALLDATETIME': 'Date',
32
- 'DATE': 'Date',
33
- 'TIME': 'Date',
34
- 'DATETIMEOFFSET': 'Date',
35
- // Binary types
36
- 'VARBINARY': 'Buffer',
37
- 'BINARY': 'Buffer',
38
- 'IMAGE': 'Buffer',
39
- // Other
40
- 'UNIQUEIDENTIFIER': 'string',
41
- 'SQL_VARIANT': 'any',
42
- 'ROWVERSION': 'Buffer',
43
- 'HIERARCHYID': 'string',
44
- 'GEOGRAPHY': 'string',
45
- 'GEOMETRY': 'string',
46
- 'VECTOR': 'number[] | string',
47
- };
48
-
49
- // Parse base type from "NVARCHAR(255)" → "NVARCHAR"
50
- function parseSqlType(raw: string): { base: string; params: string } {
51
- const match = raw.match(/^(\w+)(?:\((.+)\))?$/);
52
- if (!match) return { base: raw, params: '' };
53
- return { base: match[1].toUpperCase(), params: match[2] || '' };
54
- }
55
-
56
- // Map SQL Server type to TypeScript type
57
- export function sqlTypeToTs(sqlType: string): string {
58
- const { base } = parseSqlType(sqlType);
59
- return AN5_TO_TS[base] || 'any';
60
- }
61
-
62
- export class SchemaParser {
63
- private schemaText: string = '';
64
-
65
- constructor(private schemaDir: string) {}
66
-
67
- public async parse(): Promise<Model[]> {
68
- this.loadSchema();
69
- const lines = this.schemaText.split('\n');
70
- const models: Model[] = [];
71
- let currentModel: Model | null = null;
72
-
73
- for (let line of lines) {
74
- line = line.trim();
75
- if (!line || line.startsWith('//')) continue;
76
-
77
- const modelHeaderMatch = line.match(/^model\s+(\w+)\s*\{/);
78
- if (modelHeaderMatch) {
79
- const modelName = modelHeaderMatch[1];
80
- currentModel = {
81
- name: modelName,
82
- tableName: modelName.toLowerCase() + 's',
83
- schemaName: 'dbo',
84
- fields: [],
85
- relations: []
86
- };
87
- models.push(currentModel);
88
- continue;
89
- }
90
-
91
- if (line === '}') {
92
- currentModel = null;
93
- continue;
94
- }
95
-
96
- if (currentModel) {
97
- this.parseModelLine(line, currentModel);
98
- }
99
- }
100
-
101
- this.postProcessRelations(models);
102
- return models;
103
- }
104
-
105
- private loadSchema() {
106
- if (fs.existsSync(this.schemaDir)) {
107
- const files = fs.readdirSync(this.schemaDir).filter(f => f.endsWith('.an5'));
108
- for (const file of files) {
109
- this.schemaText += fs.readFileSync(path.join(this.schemaDir, file), 'utf8') + '\n';
110
- }
111
- } else {
112
- throw new Error(`No schema directory found at ${this.schemaDir}`);
113
- }
114
- }
115
-
116
- private parseModelLine(line: string, model: Model) {
117
- if (line.startsWith('@@map')) {
118
- const mapMatch = line.match(/@@map\("(.+)"\)/);
119
- if (mapMatch) model.tableName = mapMatch[1];
120
- return;
121
- }
122
- if (line.startsWith('@@schema')) {
123
- const schemaMatch = line.match(/@@schema\("(.+)"\)/);
124
- if (schemaMatch) model.schemaName = schemaMatch[1];
125
- return;
126
- }
127
- if (line.startsWith('@@unique')) {
128
- const uniqueMatch = line.match(/@@unique\(\[([\w,\s]+)\]\)/);
129
- if (uniqueMatch) {
130
- const fields = uniqueMatch[1].split(',').map(f => f.trim());
131
- model.compoundUniques = model.compoundUniques || [];
132
- model.compoundUniques.push(fields);
133
- }
134
- return;
135
- }
136
- if (line.startsWith('@@description')) {
137
- const descMatch = line.match(/@@description\("(.+)"\)/);
138
- if (descMatch) model.description = descMatch[1];
139
- return;
140
- }
141
- if (line.startsWith('@@')) return;
142
-
143
- const parts = line.split(/\s+/);
144
- const fieldName = parts[0];
145
- let fieldType = parts[1];
146
- if (!fieldName || !fieldType) return;
147
-
148
- const isArray = fieldType.endsWith('[]');
149
- const isOptional = fieldType.endsWith('?');
150
- const cleanType = fieldType.replace('[]', '').replace('?', '');
151
-
152
- // Parse SQL Server type (e.g., "NVARCHAR(255)" → base="NVARCHAR")
153
- const { base: sqlBase } = parseSqlType(cleanType);
154
-
155
- let tsType = 'any';
156
- let isRelation = false;
157
-
158
- // Check if it's a known SQL Server type
159
- if (AN5_TO_TS[sqlBase]) {
160
- tsType = sqlTypeToTs(cleanType);
161
- } else if (cleanType[0] === cleanType[0].toUpperCase() && !cleanType.includes('(')) {
162
- // Uppercase without parens = likely a relation to another model
163
- tsType = cleanType;
164
- isRelation = true;
165
- }
166
-
167
- if (isRelation) {
168
- let foreignKey = '', localKey = '', relationName = '';
169
- const nameMatch = line.match(/@relation\("(\w+)"/);
170
- if (nameMatch) relationName = nameMatch[1];
171
- const relationMatch = line.match(/@relation\((?:.*fields:\s*\[(\w+)\],)?\s*(?:.*references:\s*\[(\w+)\],?)?.*\)/);
172
- if (relationMatch) {
173
- foreignKey = relationMatch[1] || '';
174
- localKey = relationMatch[2] || '';
175
- }
176
- model.relations.push({ name: fieldName, type: tsType, isArray, isOptional, foreignKey, localKey, relationName });
177
- } else {
178
- const hasDefault = line.includes('@default') || line.includes('@updatedAt') || line.includes('@id');
179
- const isId = line.includes('@id');
180
- let description: string | undefined;
181
- const descMatch = line.match(/@description\("(.+)"\)/);
182
- if (descMatch) description = descMatch[1];
183
- model.fields.push({ name: fieldName, type: tsType, sqlType: cleanType, isOptional, hasDefault, isId, description });
184
- }
185
- }
186
-
187
- private postProcessRelations(models: Model[]) {
188
- for (const model of models) {
189
- for (const rel of model.relations) {
190
- if (!rel.foreignKey || !rel.localKey) {
191
- const targetModel = models.find(m => m.name === rel.type);
192
- if (targetModel) {
193
- let opposite = rel.relationName ?
194
- targetModel.relations.find(r => r.type === model.name && r.relationName === rel.relationName && r.foreignKey && r.localKey) :
195
- targetModel.relations.find(r => r.type === model.name && r.foreignKey && r.localKey);
196
- if (opposite) { rel.foreignKey = opposite.foreignKey; rel.localKey = opposite.localKey; }
197
- }
198
- }
199
- }
200
- }
201
- }
202
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { Model, Field, Relation } from './types';
4
+ import {
5
+ DEFAULT_PROVIDER,
6
+ FieldTypeError,
7
+ FieldTypeIssue,
8
+ Provider,
9
+ readFieldLineHead,
10
+ resolveFieldType,
11
+ unknownFieldTypeMessage,
12
+ } from './field-types';
13
+
14
+ /**
15
+ * Maps a column type of a provider to its TypeScript type.
16
+ *
17
+ * `provider` defaults to SQL Server so existing callers keep their behaviour;
18
+ * the generator passes the provider derived from the connection string.
19
+ */
20
+ export function sqlTypeToTs(sqlType: string, provider: Provider = DEFAULT_PROVIDER): string {
21
+ return resolveFieldType(sqlType, provider)?.ts ?? 'any';
22
+ }
23
+
24
+ /**
25
+ * A field whose type is in no table for this provider. Whether it is a relation
26
+ * or a typo is not known yet, so the decision waits until the whole schema has
27
+ * been read.
28
+ */
29
+ interface PendingModelRef {
30
+ model: Model;
31
+ name: string;
32
+ /** The name as written in the schema, kept verbatim to compare with model names. */
33
+ type: string;
34
+ isArray: boolean;
35
+ isOptional: boolean;
36
+ /** The original line, needed to read `@relation`/`@description`. */
37
+ line: string;
38
+ }
39
+
40
+ export class SchemaParser {
41
+ private schemaText: string = '';
42
+ private issues: FieldTypeIssue[] = [];
43
+ private modelRefs: PendingModelRef[] = [];
44
+ private models: Model[] = [];
45
+
46
+ /**
47
+ * @param schemaDir directory holding the `.an5` files
48
+ * @param provider target database; decides which field types are valid
49
+ */
50
+ constructor(
51
+ private schemaDir: string,
52
+ private provider: Provider = DEFAULT_PROVIDER,
53
+ ) {}
54
+
55
+ public async parse(): Promise<Model[]> {
56
+ this.issues = [];
57
+ this.modelRefs = [];
58
+ this.models = [];
59
+ this.loadSchema();
60
+ const lines = this.schemaText.split('\n');
61
+ const models: Model[] = [];
62
+ let currentModel: Model | null = null;
63
+
64
+ for (let line of lines) {
65
+ line = line.trim();
66
+ if (!line || line.startsWith('//')) continue;
67
+
68
+ const modelHeaderMatch = line.match(/^model\s+(\w+)\s*\{/);
69
+ if (modelHeaderMatch) {
70
+ const modelName = modelHeaderMatch[1];
71
+ currentModel = {
72
+ name: modelName,
73
+ tableName: modelName.toLowerCase() + 's',
74
+ // SQL Server's default schema, and only SQL Server's. For SQLite or MySQL
75
+ // an unqualified name is what the connection resolves, and for PostgreSQL
76
+ // it follows `search_path` — the same rule `db:push` now uses, so the
77
+ // generated client and the pushed table cannot drift apart.
78
+ schemaName: this.provider === 'mssql' ? 'dbo' : '',
79
+ provider: this.provider,
80
+ fields: [],
81
+ relations: []
82
+ };
83
+ models.push(currentModel);
84
+ continue;
85
+ }
86
+
87
+ if (line === '}') {
88
+ currentModel = null;
89
+ continue;
90
+ }
91
+
92
+ if (currentModel) {
93
+ this.parseModelLine(line, currentModel);
94
+ }
95
+ }
96
+
97
+ this.models = models;
98
+ this.resolveModelRefs();
99
+
100
+ // Every bad type is reported at once, so one pass over the schema is enough
101
+ // instead of re-running the generator after every line.
102
+ if (this.issues.length > 0) {
103
+ throw new FieldTypeError(this.provider, this.issues);
104
+ }
105
+
106
+ this.postProcessRelations(models);
107
+ return models;
108
+ }
109
+
110
+ private loadSchema() {
111
+ if (fs.existsSync(this.schemaDir)) {
112
+ const files = fs.readdirSync(this.schemaDir).filter(f => f.endsWith('.an5'));
113
+ for (const file of files) {
114
+ this.schemaText += fs.readFileSync(path.join(this.schemaDir, file), 'utf8') + '\n';
115
+ }
116
+ } else {
117
+ throw new Error(`No schema directory found at ${this.schemaDir}`);
118
+ }
119
+ }
120
+
121
+ private parseModelLine(line: string, model: Model) {
122
+ if (line.startsWith('@@map')) {
123
+ const mapMatch = line.match(/@@map\("(.+)"\)/);
124
+ if (mapMatch) model.tableName = mapMatch[1];
125
+ return;
126
+ }
127
+ if (line.startsWith('@@schema')) {
128
+ // `(.*)` rather than `(.+)`: `@@schema("")` is how a model says "no
129
+ // schema", needed for databases that have no schema concept. With `(.+)`
130
+ // the empty string does not match, the directive is silently ignored and
131
+ // the model keeps `dbo`.
132
+ const schemaMatch = line.match(/@@schema\("(.*)"\)/);
133
+ if (schemaMatch) model.schemaName = schemaMatch[1].trim();
134
+ return;
135
+ }
136
+ if (line.startsWith('@@unique')) {
137
+ const uniqueMatch = line.match(/@@unique\(\[([\w,\s]+)\]\)/);
138
+ if (uniqueMatch) {
139
+ const fields = uniqueMatch[1].split(',').map(f => f.trim());
140
+ model.compoundUniques = model.compoundUniques || [];
141
+ model.compoundUniques.push(fields);
142
+ }
143
+ return;
144
+ }
145
+ if (line.startsWith('@@description')) {
146
+ const descMatch = line.match(/@@description\("(.+)"\)/);
147
+ if (descMatch) model.description = descMatch[1];
148
+ return;
149
+ }
150
+ if (line.startsWith('@@')) return;
151
+
152
+ const head = readFieldLineHead(line);
153
+ if (!head) return;
154
+
155
+ // No table entry for this provider. This used to fall through to
156
+ // `tsType = 'any'` (or, worse, become a relation to a model that does not
157
+ // exist) and the client was still generated; the failure only surfaced
158
+ // later at the database layer, in a message unrelated to the schema.
159
+ const resolved = resolveFieldType(head.type, this.provider);
160
+ if (!resolved) {
161
+ this.modelRefs.push({ model, name: head.name, type: head.type, isArray: head.isArray, isOptional: head.isOptional, line });
162
+ return;
163
+ }
164
+
165
+ const hasDefault = line.includes('@default') || line.includes('@updatedAt') || line.includes('@id');
166
+ const isId = line.includes('@id');
167
+ let description: string | undefined;
168
+ const descMatch = line.match(/@description\("(.+)"\)/);
169
+ if (descMatch) description = descMatch[1];
170
+ model.fields.push({ name: head.name, type: resolved.ts, sqlType: head.type, isOptional: head.isOptional, hasDefault, isId, description });
171
+ }
172
+
173
+ /**
174
+ * Settles the fields that matched no type: a name matching a model in the
175
+ * schema is a relation, anything else is a bad type — reported with the
176
+ * provider name and a suggestion.
177
+ *
178
+ * The decision has to wait for the whole schema, because a relation may point
179
+ * at a model declared later. Every upper-case token used to count as a
180
+ * relation, so `INTEGER` written for SQL Server became a relation to a model
181
+ * named `INTEGER` and nothing ever complained.
182
+ */
183
+ private resolveModelRefs() {
184
+ const modelNames = this.models.map((model) => model.name);
185
+
186
+ for (const ref of this.modelRefs) {
187
+ if (!modelNames.includes(ref.type)) {
188
+ this.issues.push({
189
+ path: `${ref.model.name}.${ref.name}`,
190
+ message: unknownFieldTypeMessage(ref.type, this.provider, modelNames),
191
+ });
192
+ continue;
193
+ }
194
+
195
+ let foreignKey = '', localKey = '', relationName = '';
196
+ const nameMatch = ref.line.match(/@relation\("(\w+)"/);
197
+ if (nameMatch) relationName = nameMatch[1];
198
+ const relationMatch = ref.line.match(/@relation\((?:.*fields:\s*\[(\w+)\],)?\s*(?:.*references:\s*\[(\w+)\],?)?.*\)/);
199
+ if (relationMatch) {
200
+ foreignKey = relationMatch[1] || '';
201
+ localKey = relationMatch[2] || '';
202
+ }
203
+ const description = ref.line.match(/@description\("(.+)"\)/)?.[1];
204
+ ref.model.relations.push({
205
+ name: ref.name,
206
+ type: ref.type,
207
+ isArray: ref.isArray,
208
+ isOptional: ref.isOptional,
209
+ foreignKey,
210
+ localKey,
211
+ relationName,
212
+ ...(description ? { description } : {}),
213
+ });
214
+ }
215
+
216
+ this.modelRefs = [];
217
+ }
218
+
219
+ private postProcessRelations(models: Model[]) {
220
+ for (const model of models) {
221
+ for (const rel of model.relations) {
222
+ if (!rel.foreignKey || !rel.localKey) {
223
+ const targetModel = models.find(m => m.name === rel.type);
224
+ if (targetModel) {
225
+ let opposite = rel.relationName ?
226
+ targetModel.relations.find(r => r.type === model.name && r.relationName === rel.relationName && r.foreignKey && r.localKey) :
227
+ targetModel.relations.find(r => r.type === model.name && r.foreignKey && r.localKey);
228
+ if (opposite) { rel.foreignKey = opposite.foreignKey; rel.localKey = opposite.localKey; }
229
+ }
230
+ }
231
+ }
232
+ }
233
+ }
234
+ }
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Applying a schema to a database: what `db:push` does once the schema is read.
3
+ *
4
+ * Kept out of `push.ts` so the sequence can be run against a real database in a
5
+ * test — the CLI needs a live server, and a test that re-implements the sequence
6
+ * instead of calling it proves only that the copy works.
7
+ *
8
+ * The database is two functions rather than the adapter, which keeps this testable
9
+ * and keeps the driver out of the decision making.
10
+ */
11
+ import { PushDialect } from './dialect';
12
+ import { PushIndex, PushModel, directiveName, qualifiedTableName, safeIdentifierName } from './push-schema';
13
+
14
+ /** The two things this needs from a database connection. */
15
+ export interface PushDatabase {
16
+ /** Runs a query and returns its rows; existence checks are `length > 0`. */
17
+ query(sql: string): Promise<readonly unknown[]>;
18
+ /** Runs one statement. */
19
+ execute(sql: string): Promise<void>;
20
+ /** Progress, so the CLI prints what it is doing. */
21
+ log(message: string): void;
22
+ }
23
+
24
+ export interface ApplyResult {
25
+ /** How many tables were created, and how many altered. */
26
+ tablesCreated: number;
27
+ tablesAltered: number;
28
+ columnsAdded: number;
29
+ indexesCreated: number;
30
+ uniqueConstraintsAdded: number;
31
+ }
32
+
33
+ /**
34
+ * Creates whatever the schema has and the database does not.
35
+ *
36
+ * The order is deliberate: a table first, then missing columns, then unique
37
+ * constraints and indexes — a unique over a column that does not exist yet fails.
38
+ * Everything is checked before it is created, so running it twice changes nothing.
39
+ */
40
+ export async function applySchema(
41
+ models: readonly PushModel[],
42
+ dialect: PushDialect,
43
+ db: PushDatabase,
44
+ ): Promise<ApplyResult> {
45
+ const result: ApplyResult = {
46
+ tablesCreated: 0,
47
+ tablesAltered: 0,
48
+ columnsAdded: 0,
49
+ indexesCreated: 0,
50
+ uniqueConstraintsAdded: 0,
51
+ };
52
+
53
+ for (const model of models) {
54
+ const tableName = qualifiedTableName(model);
55
+ const sqlTableName = dialect.quoteTable(tableName);
56
+ const quoteFields = (fields: readonly string[]) => fields.map((field) => dialect.quote(field));
57
+ db.log(`Processing table ${sqlTableName}...`);
58
+
59
+ const safeName = safeIdentifierName(model.tableName);
60
+ // SQLite has no named unique constraints — a UNIQUE there becomes an index the
61
+ // engine names itself — so the unique index carries our name instead, and that
62
+ // name is what the existence check can look for.
63
+ const compoundUniques = model.compoundUniques.map((directive, idx) => ({
64
+ name: directiveName(directive, model.tableName, 'compound', idx),
65
+ fields: directive.fields,
66
+ directive,
67
+ }));
68
+
69
+ const tableExists = (await db.query(dialect.tableExists(tableName))).length > 0;
70
+
71
+ if (!tableExists) {
72
+ db.log(`Creating table ${sqlTableName}...`);
73
+ const columnDefs = model.fields.map((field) => dialect.columnDefinition(field));
74
+ for (const entry of compoundUniques) {
75
+ if (!dialect.supportsNamedUniqueConstraint) continue;
76
+ const fieldsStr = quoteFields(entry.fields).join(', ');
77
+ columnDefs.push(`CONSTRAINT ${dialect.quote(entry.name)} UNIQUE (${fieldsStr})`);
78
+ }
79
+ await db.execute(dialect.createTable(sqlTableName, columnDefs));
80
+ db.log(`✅ Table ${sqlTableName} created.`);
81
+ result.tablesCreated += 1;
82
+ } else {
83
+ for (const field of model.fields) {
84
+ const columnExists = (await db.query(dialect.columnExists(tableName, field.name))).length > 0;
85
+ if (columnExists) continue;
86
+ db.log(`Adding column ${dialect.quote(field.name)} to table ${sqlTableName}...`);
87
+ await db.execute(dialect.addColumn(sqlTableName, field));
88
+ result.columnsAdded += 1;
89
+ // A new `@unique` column needs its unique too, and on SQLite that cannot
90
+ // ride along with the ADD COLUMN — SQLite refuses to add a UNIQUE column.
91
+ if (field.isUnique && !field.isId && !dialect.supportsUniqueInlineOnAddColumn) {
92
+ const indexName = `UQ_${safeName}_${field.name}`;
93
+ const quoted = dialect.quote(indexName);
94
+ if ((await db.query(dialect.uniqueConstraintExists(tableName, indexName))).length === 0) {
95
+ db.log(`Creating unique index ${quoted} on table ${sqlTableName}...`);
96
+ await db.execute(dialect.createUniqueIndex(quoted, sqlTableName, quoteFields([field.name])));
97
+ result.uniqueConstraintsAdded += 1;
98
+ }
99
+ }
100
+ }
101
+ result.tablesAltered += 1;
102
+ }
103
+
104
+ // Unique constraints that are not part of the column definitions above.
105
+ for (const entry of compoundUniques) {
106
+ if (await hasUniqueConstraint(db, dialect, tableName, entry.name)) continue;
107
+ const quoted = dialect.quote(entry.name);
108
+ if (dialect.supportsNamedUniqueConstraint) {
109
+ db.log(`Adding compound unique constraint ${quoted} to table ${sqlTableName}...`);
110
+ await db.execute(dialect.addUniqueConstraint(quoted, sqlTableName, quoteFields(entry.fields)));
111
+ } else {
112
+ db.log(`Creating unique index ${quoted} on table ${sqlTableName}...`);
113
+ await db.execute(dialect.createUniqueIndex(quoted, sqlTableName, quoteFields(entry.fields)));
114
+ result.indexesCreated += 1;
115
+ result.uniqueConstraintsAdded += 1;
116
+ }
117
+ result.uniqueConstraintsAdded += 1;
118
+ }
119
+
120
+ for (const [idx, directive] of model.indexes.entries()) {
121
+ const name = directiveName(directive, model.tableName, 'index', idx);
122
+ if ((await db.query(dialect.indexExists(tableName, name))).length > 0) continue;
123
+ const quoted = dialect.quote(name);
124
+ db.log(`Creating index ${quoted} on table ${sqlTableName}...`);
125
+ await db.execute(dialect.createIndex(quoted, sqlTableName, quoteFields(directive.fields)));
126
+ result.indexesCreated += 1;
127
+ }
128
+ }
129
+
130
+ return result;
131
+ }
132
+
133
+ /**
134
+ * Whether the unique is already there.
135
+ *
136
+ * A compound unique created inside `CREATE TABLE` has no separate object to look
137
+ * for on the providers that keep them, so it is treated as present once the table
138
+ * exists; the per-column uniques inside a column definition are handled with the
139
+ * column above.
140
+ */
141
+ async function hasUniqueConstraint(
142
+ db: PushDatabase,
143
+ dialect: PushDialect,
144
+ tableName: string,
145
+ name: string,
146
+ ): Promise<boolean> {
147
+ return (await db.query(dialect.uniqueConstraintExists(tableName, name))).length > 0;
148
+ }