@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.
- package/README.md +174 -175
- package/dist/an5Metadata.js +64 -0
- package/dist/an5Orm.d.ts +92 -3
- package/dist/an5Orm.js +697 -206
- package/dist/config.d.ts +9 -1
- package/dist/config.js +13 -18
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/generator/src/api.d.ts +35 -0
- package/dist/generator/src/api.js +58 -0
- package/dist/generator/src/code-generator.d.ts +14 -13
- package/dist/generator/src/code-generator.js +249 -225
- package/dist/generator/src/config.d.ts +162 -0
- package/dist/generator/src/config.js +354 -0
- package/dist/generator/src/dialect.d.ts +88 -0
- package/dist/generator/src/dialect.js +318 -0
- package/dist/generator/src/dotnet-generator.d.ts +21 -11
- package/dist/generator/src/dotnet-generator.js +1053 -546
- package/dist/generator/src/field-types.d.ts +96 -0
- package/dist/generator/src/field-types.js +433 -0
- package/dist/generator/src/golang-generator.d.ts +36 -0
- package/dist/generator/src/golang-generator.js +1229 -0
- package/dist/generator/src/index.d.ts +1 -1
- package/dist/generator/src/index.js +137 -88
- package/dist/generator/src/metadata-generator.d.ts +11 -8
- package/dist/generator/src/metadata-generator.js +105 -90
- package/dist/generator/src/parser.d.ts +37 -11
- package/dist/generator/src/parser.js +208 -206
- package/dist/generator/src/push-apply.d.ts +37 -0
- package/dist/generator/src/push-apply.js +109 -0
- package/dist/generator/src/push-schema.d.ts +93 -0
- package/dist/generator/src/push-schema.js +189 -0
- package/dist/generator/src/python-generator.d.ts +37 -9
- package/dist/generator/src/python-generator.js +428 -105
- package/dist/generator/src/rust-generator.d.ts +38 -0
- package/dist/generator/src/rust-generator.js +971 -0
- package/dist/generator/src/suggest.d.ts +17 -0
- package/dist/generator/src/suggest.js +45 -0
- package/dist/generator/src/type-kinds.d.ts +27 -0
- package/dist/generator/src/type-kinds.js +72 -0
- package/dist/generator/src/types.d.ts +60 -27
- package/dist/generator/src/types.js +41 -2
- package/dist/index.d.ts +3 -2
- package/dist/index.js +19 -8
- package/dist/logger.js +1 -1
- package/dist/migration-core.d.ts +102 -0
- package/dist/migration-core.js +731 -0
- package/dist/orm.d.ts +147 -0
- package/dist/orm.js +1654 -0
- package/dist/provider-support.d.ts +27 -0
- package/dist/provider-support.js +50 -0
- package/dist/scripts/release-cli.d.ts +2 -2
- package/dist/scripts/release-cli.js +115 -115
- package/dist/sql-utils.d.ts +3 -1
- package/dist/sql-utils.js +94 -24
- package/generator/src/api.ts +45 -0
- package/generator/src/code-generator.ts +259 -230
- package/generator/src/config.ts +496 -0
- package/generator/src/dialect.ts +415 -0
- package/generator/src/dotnet-generator.ts +1071 -544
- package/generator/src/field-types.ts +473 -0
- package/generator/src/golang-generator.ts +1267 -0
- package/generator/src/index.ts +146 -116
- package/generator/src/metadata-generator.ts +116 -101
- package/generator/src/parser.ts +234 -202
- package/generator/src/push-apply.ts +148 -0
- package/generator/src/push-schema.ts +250 -0
- package/generator/src/python-generator.ts +480 -114
- package/generator/src/rust-generator.ts +974 -0
- package/generator/src/suggest.ts +41 -0
- package/generator/src/type-kinds.ts +78 -0
- package/generator/src/types.ts +77 -29
- package/package.json +32 -6
package/generator/src/parser.ts
CHANGED
|
@@ -1,202 +1,234 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import { Model, Field, Relation } from './types';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
if (line.startsWith('@@
|
|
123
|
-
const
|
|
124
|
-
if (
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
if (line.startsWith('@@
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
return;
|
|
135
|
-
}
|
|
136
|
-
if (line.startsWith('@@
|
|
137
|
-
const
|
|
138
|
-
if (
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
//
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
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
|
+
}
|