@an5/orm 1.0.8 → 1.0.9
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 +167 -175
- package/dist/an5Metadata.js +64 -0
- package/dist/an5Orm.d.ts +92 -3
- package/dist/an5Orm.js +697 -206
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/generator/src/code-generator.d.ts +14 -13
- package/dist/generator/src/code-generator.js +249 -225
- package/dist/generator/src/dotnet-generator.d.ts +13 -11
- package/dist/generator/src/dotnet-generator.js +872 -546
- package/dist/generator/src/index.d.ts +1 -1
- package/dist/generator/src/index.js +104 -88
- package/dist/generator/src/metadata-generator.d.ts +11 -8
- package/dist/generator/src/metadata-generator.js +104 -90
- package/dist/generator/src/parser.d.ts +11 -11
- package/dist/generator/src/parser.js +206 -206
- package/dist/generator/src/python-generator.d.ts +19 -9
- package/dist/generator/src/python-generator.js +345 -105
- package/dist/generator/src/types.d.ts +27 -27
- package/dist/generator/src/types.js +2 -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 +87 -0
- package/dist/migration-core.js +692 -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/code-generator.ts +259 -230
- package/generator/src/dotnet-generator.ts +882 -544
- package/generator/src/golang-generator.ts +1242 -0
- package/generator/src/index.ts +111 -116
- package/generator/src/metadata-generator.ts +116 -101
- package/generator/src/parser.ts +202 -202
- package/generator/src/python-generator.ts +424 -114
- package/generator/src/types.ts +29 -29
- package/package.json +12 -6
|
@@ -1,544 +1,882 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import { Model, Field, Relation } from './types';
|
|
4
|
-
|
|
5
|
-
export class DotnetGenerator {
|
|
6
|
-
constructor(private outputDir: string) {
|
|
7
|
-
if (!fs.existsSync(this.outputDir)) {
|
|
8
|
-
fs.mkdirSync(this.outputDir, { recursive: true });
|
|
9
|
-
}
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
public generate(models: Model[]) {
|
|
13
|
-
// 1. Generate individual C# entity class files
|
|
14
|
-
for (const model of models) {
|
|
15
|
-
this.generateEntityClass(model);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// 2. Generate
|
|
19
|
-
this.
|
|
20
|
-
|
|
21
|
-
// 3. Generate
|
|
22
|
-
this.
|
|
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
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
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
|
-
public
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
content += `
|
|
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
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
}
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { Model, Field, Relation } from './types';
|
|
4
|
+
|
|
5
|
+
export class DotnetGenerator {
|
|
6
|
+
constructor(private outputDir: string) {
|
|
7
|
+
if (!fs.existsSync(this.outputDir)) {
|
|
8
|
+
fs.mkdirSync(this.outputDir, { recursive: true });
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
public generate(models: Model[]) {
|
|
13
|
+
// 1. Generate individual C# entity class files
|
|
14
|
+
for (const model of models) {
|
|
15
|
+
this.generateEntityClass(model);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// 2. Generate per-model ORM types (WhereInput, OrderByInput, FindManyArgs, etc.)
|
|
19
|
+
this.generateOrmTypes(models);
|
|
20
|
+
|
|
21
|
+
// 3. Generate DbContext / Client metadata file
|
|
22
|
+
this.generateDbContext(models);
|
|
23
|
+
|
|
24
|
+
// 4. Generate configuration helper class
|
|
25
|
+
this.generateConfigClass();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
private getCsFilterType(fieldType: string, isOptional: boolean): string {
|
|
29
|
+
const lower = fieldType.toLowerCase();
|
|
30
|
+
if (['datetime', 'datetime2', 'smalldatetime', 'date', 'datetimeoffset'].includes(lower)) return 'DateTimeFilter';
|
|
31
|
+
if (['bool', 'boolean', 'bit'].includes(lower)) return 'BoolFilter';
|
|
32
|
+
if (['int', 'integer', 'smallint', 'tinyint', 'number'].includes(lower)) return 'IntFilter';
|
|
33
|
+
if (['bigint', 'long', 'float', 'real', 'double', 'decimal', 'numeric', 'money', 'smallmoney'].includes(lower)) return 'NumberFilter';
|
|
34
|
+
return 'StringFilter';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private generateOrmTypes(models: Model[]) {
|
|
38
|
+
let content = `// This file is auto-generated. Do not edit directly.
|
|
39
|
+
using System;
|
|
40
|
+
using System.Collections.Generic;
|
|
41
|
+
|
|
42
|
+
namespace An5Orm
|
|
43
|
+
{
|
|
44
|
+
// ── Base Filter Types ──────────────────────────────────────────────────────
|
|
45
|
+
|
|
46
|
+
/// <summary>Type-safe filter for string fields.</summary>
|
|
47
|
+
public class StringFilter
|
|
48
|
+
{
|
|
49
|
+
public new string Equals { get; set; }
|
|
50
|
+
public string Not { get; set; }
|
|
51
|
+
public List<string> In { get; set; }
|
|
52
|
+
public List<string> NotIn { get; set; }
|
|
53
|
+
public string Contains { get; set; }
|
|
54
|
+
public string StartsWith { get; set; }
|
|
55
|
+
public string EndsWith { get; set; }
|
|
56
|
+
public string Gt { get; set; }
|
|
57
|
+
public string Gte { get; set; }
|
|
58
|
+
public string Lt { get; set; }
|
|
59
|
+
public string Lte { get; set; }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/// <summary>Type-safe filter for integer fields.</summary>
|
|
63
|
+
public class IntFilter
|
|
64
|
+
{
|
|
65
|
+
public new int? Equals { get; set; }
|
|
66
|
+
public int? Not { get; set; }
|
|
67
|
+
public List<int> In { get; set; }
|
|
68
|
+
public List<int> NotIn { get; set; }
|
|
69
|
+
public int? Gt { get; set; }
|
|
70
|
+
public int? Gte { get; set; }
|
|
71
|
+
public int? Lt { get; set; }
|
|
72
|
+
public int? Lte { get; set; }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/// <summary>Type-safe filter for numeric/float fields.</summary>
|
|
76
|
+
public class NumberFilter
|
|
77
|
+
{
|
|
78
|
+
public new double? Equals { get; set; }
|
|
79
|
+
public double? Not { get; set; }
|
|
80
|
+
public List<double> In { get; set; }
|
|
81
|
+
public List<double> NotIn { get; set; }
|
|
82
|
+
public double? Gt { get; set; }
|
|
83
|
+
public double? Gte { get; set; }
|
|
84
|
+
public double? Lt { get; set; }
|
|
85
|
+
public double? Lte { get; set; }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/// <summary>Type-safe filter for boolean fields.</summary>
|
|
89
|
+
public class BoolFilter
|
|
90
|
+
{
|
|
91
|
+
public new bool? Equals { get; set; }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/// <summary>Type-safe filter for DateTime fields.</summary>
|
|
95
|
+
public class DateTimeFilter
|
|
96
|
+
{
|
|
97
|
+
public new DateTime? Equals { get; set; }
|
|
98
|
+
public DateTime? Not { get; set; }
|
|
99
|
+
public List<DateTime> In { get; set; }
|
|
100
|
+
public List<DateTime> NotIn { get; set; }
|
|
101
|
+
public DateTime? Gt { get; set; }
|
|
102
|
+
public DateTime? Gte { get; set; }
|
|
103
|
+
public DateTime? Lt { get; set; }
|
|
104
|
+
public DateTime? Lte { get; set; }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
`;
|
|
108
|
+
|
|
109
|
+
for (const model of models) {
|
|
110
|
+
const name = this.capitalize(model.name);
|
|
111
|
+
const csType = (f: { type: string; isOptional: boolean }) => this.mapType(f.type, f.isOptional);
|
|
112
|
+
|
|
113
|
+
content += ` // ── ${name} ORM Types ──────────────────────────────────────────────────────\n\n`;
|
|
114
|
+
|
|
115
|
+
// WhereInput
|
|
116
|
+
content += ` /// <summary>Type-safe WHERE filter for ${name} queries.</summary>\n`;
|
|
117
|
+
content += ` public class ${name}WhereInput\n {\n`;
|
|
118
|
+
content += ` public List<${name}WhereInput> AND { get; set; }\n`;
|
|
119
|
+
content += ` public List<${name}WhereInput> OR { get; set; }\n`;
|
|
120
|
+
content += ` public ${name}WhereInput NOT { get; set; }\n`;
|
|
121
|
+
for (const f of model.fields) {
|
|
122
|
+
const ft = this.getCsFilterType(f.type, f.isOptional);
|
|
123
|
+
content += ` public ${ft} ${this.capitalize(f.name)} { get; set; }\n`;
|
|
124
|
+
}
|
|
125
|
+
content += ` }\n\n`;
|
|
126
|
+
|
|
127
|
+
// OrderByInput
|
|
128
|
+
content += ` /// <summary>Type-safe ORDER BY for ${name} queries.</summary>\n`;
|
|
129
|
+
content += ` public class ${name}OrderByInput\n {\n`;
|
|
130
|
+
for (const f of model.fields) {
|
|
131
|
+
content += ` public string ${this.capitalize(f.name)} { get; set; } // "asc" or "desc"\n`;
|
|
132
|
+
}
|
|
133
|
+
content += ` }\n\n`;
|
|
134
|
+
|
|
135
|
+
// CreateInput
|
|
136
|
+
content += ` /// <summary>Typed data for creating a new ${name} record.</summary>\n`;
|
|
137
|
+
content += ` public class ${name}CreateInput\n {\n`;
|
|
138
|
+
for (const f of model.fields) {
|
|
139
|
+
if (!f.isId) {
|
|
140
|
+
const ct = this.mapType(f.type, f.isOptional || f.hasDefault);
|
|
141
|
+
content += ` public ${ct} ${this.capitalize(f.name)} { get; set; }\n`;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
content += ` }\n\n`;
|
|
145
|
+
|
|
146
|
+
// UpdateInput
|
|
147
|
+
content += ` /// <summary>Typed data for updating an existing ${name} record.</summary>\n`;
|
|
148
|
+
content += ` public class ${name}UpdateInput\n {\n`;
|
|
149
|
+
for (const f of model.fields) {
|
|
150
|
+
if (!f.isId) {
|
|
151
|
+
const ut = this.mapType(f.type, true); // always nullable for update
|
|
152
|
+
content += ` public ${ut} ${this.capitalize(f.name)} { get; set; }\n`;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
content += ` }\n\n`;
|
|
156
|
+
|
|
157
|
+
// FindManyArgs
|
|
158
|
+
content += ` /// <summary>ORM-style args for ${name}.FindMany().</summary>\n`;
|
|
159
|
+
content += ` public class ${name}FindManyArgs\n {\n`;
|
|
160
|
+
content += ` public ${name}WhereInput Where { get; set; }\n`;
|
|
161
|
+
content += ` public ${name}OrderByInput OrderBy { get; set; }\n`;
|
|
162
|
+
content += ` public int? Take { get; set; }\n`;
|
|
163
|
+
content += ` public int? Skip { get; set; }\n`;
|
|
164
|
+
content += ` public List<string> Select { get; set; }\n`;
|
|
165
|
+
content += ` }\n\n`;
|
|
166
|
+
|
|
167
|
+
// FindFirstArgs
|
|
168
|
+
content += ` /// <summary>ORM-style args for ${name}.FindFirst().</summary>\n`;
|
|
169
|
+
content += ` public class ${name}FindFirstArgs\n {\n`;
|
|
170
|
+
content += ` public ${name}WhereInput Where { get; set; }\n`;
|
|
171
|
+
content += ` public ${name}OrderByInput OrderBy { get; set; }\n`;
|
|
172
|
+
content += ` public List<string> Select { get; set; }\n`;
|
|
173
|
+
content += ` }\n\n`;
|
|
174
|
+
|
|
175
|
+
// FindUniqueArgs
|
|
176
|
+
content += ` /// <summary>ORM-style args for ${name}.FindUnique().</summary>\n`;
|
|
177
|
+
content += ` public class ${name}FindUniqueArgs\n {\n`;
|
|
178
|
+
content += ` public ${name}WhereInput Where { get; set; }\n`;
|
|
179
|
+
content += ` }\n\n`;
|
|
180
|
+
|
|
181
|
+
// DeleteManyArgs
|
|
182
|
+
content += ` /// <summary>ORM-style args for ${name}.DeleteMany().</summary>\n`;
|
|
183
|
+
content += ` public class ${name}DeleteManyArgs\n {\n`;
|
|
184
|
+
content += ` public ${name}WhereInput Where { get; set; }\n`;
|
|
185
|
+
content += ` }\n\n`;
|
|
186
|
+
|
|
187
|
+
// CountArgs
|
|
188
|
+
content += ` /// <summary>ORM-style args for ${name}.Count().</summary>\n`;
|
|
189
|
+
content += ` public class ${name}CountArgs\n {\n`;
|
|
190
|
+
content += ` public ${name}WhereInput Where { get; set; }\n`;
|
|
191
|
+
content += ` }\n\n`;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
content += `}\n`;
|
|
195
|
+
|
|
196
|
+
fs.writeFileSync(path.join(this.outputDir, 'An5OrmTypes.cs'), content);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
private generateConfigClass() {
|
|
200
|
+
const content = `// This file is auto-generated. Do not edit directly.
|
|
201
|
+
using System;
|
|
202
|
+
|
|
203
|
+
namespace An5Orm
|
|
204
|
+
{
|
|
205
|
+
public static class An5Config
|
|
206
|
+
{
|
|
207
|
+
public static string ConnectionString { get; set; } = Environment.GetEnvironmentVariable("DATABASE_URL") ?? "Server=localhost;Database=master;Trusted_Connection=True;TrustServerCertificate=True;";
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
`;
|
|
211
|
+
fs.writeFileSync(path.join(this.outputDir, 'An5Config.cs'), content);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
private mapType(fieldType: string, isOptional: boolean): string {
|
|
215
|
+
let csType = 'string';
|
|
216
|
+
const lowerType = fieldType.toLowerCase();
|
|
217
|
+
|
|
218
|
+
if (['int', 'integer', 'smallint', 'tinyint', 'number'].includes(lowerType)) {
|
|
219
|
+
csType = 'int';
|
|
220
|
+
} else if (['bigint', 'long'].includes(lowerType)) {
|
|
221
|
+
csType = 'long';
|
|
222
|
+
} else if (['float', 'real', 'double'].includes(lowerType)) {
|
|
223
|
+
csType = 'double';
|
|
224
|
+
} else if (['decimal', 'numeric', 'money', 'smallmoney'].includes(lowerType)) {
|
|
225
|
+
csType = 'decimal';
|
|
226
|
+
} else if (['bool', 'boolean', 'bit'].includes(lowerType)) {
|
|
227
|
+
csType = 'bool';
|
|
228
|
+
} else if (['datetime', 'datetime2', 'smalldatetime', 'date'].includes(lowerType)) {
|
|
229
|
+
csType = 'DateTime';
|
|
230
|
+
} else if (lowerType === 'datetimeoffset') {
|
|
231
|
+
csType = 'DateTimeOffset';
|
|
232
|
+
} else if (lowerType === 'time') {
|
|
233
|
+
csType = 'TimeSpan';
|
|
234
|
+
} else if (['guid', 'uuid', 'uniqueidentifier'].includes(lowerType)) {
|
|
235
|
+
csType = 'Guid';
|
|
236
|
+
} else if (['bytes', 'binary', 'varbinary', 'image'].includes(lowerType)) {
|
|
237
|
+
csType = 'byte[]';
|
|
238
|
+
} else if (['xml', 'hierarchyid', 'geography', 'geometry', 'sysname', 'sql_variant', 'sqlvariant', 'rowversion', 'variant'].includes(lowerType)) {
|
|
239
|
+
csType = 'string';
|
|
240
|
+
} else if (fieldType.endsWith('[]')) {
|
|
241
|
+
csType = 'string';
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (isOptional && csType !== 'string' && !csType.endsWith('[]')) {
|
|
245
|
+
csType += '?';
|
|
246
|
+
}
|
|
247
|
+
return csType;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
private generateEntityClass(model: Model) {
|
|
251
|
+
let content = `// This file is auto-generated. Do not edit directly.
|
|
252
|
+
using System;
|
|
253
|
+
using System.Collections.Generic;
|
|
254
|
+
|
|
255
|
+
namespace An5Orm.Entities
|
|
256
|
+
{
|
|
257
|
+
public class ${model.name}
|
|
258
|
+
{
|
|
259
|
+
`;
|
|
260
|
+
|
|
261
|
+
// Generate fields
|
|
262
|
+
for (const field of model.fields) {
|
|
263
|
+
const csType = this.mapType(field.type, field.isOptional);
|
|
264
|
+
content += ` public ${csType} ${this.capitalize(field.name)} { get; set; }\n`;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Generate relations
|
|
268
|
+
if (model.relations.length > 0) {
|
|
269
|
+
content += '\n // ── Relations ────────────────────────────────────────────────────────\n';
|
|
270
|
+
for (const rel of model.relations) {
|
|
271
|
+
if (rel.isArray) {
|
|
272
|
+
content += ` public List<${rel.type}> ${this.capitalize(rel.name)} { get; set; } = new List<${rel.type}>();\n`;
|
|
273
|
+
} else {
|
|
274
|
+
content += ` public ${rel.type} ${this.capitalize(rel.name)} { get; set; }\n`;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
content += ` }
|
|
280
|
+
}
|
|
281
|
+
`;
|
|
282
|
+
|
|
283
|
+
fs.writeFileSync(path.join(this.outputDir, `${model.name}.cs`), content);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private generateDbContext(models: Model[]) {
|
|
287
|
+
let content = `// This file is auto-generated. Do not edit directly.
|
|
288
|
+
using System;
|
|
289
|
+
using System.Collections.Generic;
|
|
290
|
+
using System.Data;
|
|
291
|
+
using System.Reflection;
|
|
292
|
+
using System.Text.Json;
|
|
293
|
+
using Microsoft.Data.SqlClient;
|
|
294
|
+
using An5Orm.Entities;
|
|
295
|
+
|
|
296
|
+
namespace An5Orm
|
|
297
|
+
{
|
|
298
|
+
public class An5DbContext
|
|
299
|
+
{
|
|
300
|
+
public string ConnectionString { get; }
|
|
301
|
+
|
|
302
|
+
[ThreadStatic]
|
|
303
|
+
private static SqlConnection _txConn;
|
|
304
|
+
[ThreadStatic]
|
|
305
|
+
private static SqlTransaction _tx;
|
|
306
|
+
|
|
307
|
+
public An5DbContext(string connectionString = null)
|
|
308
|
+
{
|
|
309
|
+
ConnectionString = connectionString ?? An5Config.ConnectionString;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
public An5Transaction BeginTransaction()
|
|
313
|
+
{
|
|
314
|
+
var conn = new SqlConnection(ConnectionString);
|
|
315
|
+
conn.Open();
|
|
316
|
+
var tx = conn.BeginTransaction();
|
|
317
|
+
_txConn = conn;
|
|
318
|
+
_tx = tx;
|
|
319
|
+
return new An5Transaction(conn, tx, () => {
|
|
320
|
+
_txConn = null;
|
|
321
|
+
_tx = null;
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
public static SqlConnection GetActiveConnection(string connectionString, out bool isTx)
|
|
326
|
+
{
|
|
327
|
+
if (_txConn != null)
|
|
328
|
+
{
|
|
329
|
+
isTx = true;
|
|
330
|
+
return _txConn;
|
|
331
|
+
}
|
|
332
|
+
isTx = false;
|
|
333
|
+
var conn = new SqlConnection(connectionString);
|
|
334
|
+
conn.Open();
|
|
335
|
+
return conn;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
public static SqlTransaction GetActiveTransaction() => _tx;
|
|
339
|
+
|
|
340
|
+
// ── Tables / Repositories ──────────────────────────────────────────────
|
|
341
|
+
`;
|
|
342
|
+
|
|
343
|
+
for (const model of models) {
|
|
344
|
+
const name = this.capitalize(model.name);
|
|
345
|
+
content += ` public TableClient<${model.name}> ${name}s => new TableClient<${model.name}>(ConnectionString, "${model.schemaName}.${model.tableName}");\n`;
|
|
346
|
+
content += ` public TableClient<${model.name}> ${name} => ${name}s;\n`;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
content += ` }
|
|
350
|
+
|
|
351
|
+
public class An5Transaction : IDisposable
|
|
352
|
+
{
|
|
353
|
+
private readonly SqlConnection _conn;
|
|
354
|
+
private readonly SqlTransaction _tx;
|
|
355
|
+
private readonly Action _cleanup;
|
|
356
|
+
private bool _completed;
|
|
357
|
+
|
|
358
|
+
public An5Transaction(SqlConnection conn, SqlTransaction tx, Action cleanup)
|
|
359
|
+
{
|
|
360
|
+
_conn = conn;
|
|
361
|
+
_tx = tx;
|
|
362
|
+
_cleanup = cleanup;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
public void Commit()
|
|
366
|
+
{
|
|
367
|
+
_tx.Commit();
|
|
368
|
+
_completed = true;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
public void Rollback()
|
|
372
|
+
{
|
|
373
|
+
_tx.Rollback();
|
|
374
|
+
_completed = true;
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
public void Dispose()
|
|
378
|
+
{
|
|
379
|
+
if (!_completed)
|
|
380
|
+
{
|
|
381
|
+
try { _tx.Rollback(); } catch { }
|
|
382
|
+
}
|
|
383
|
+
_tx.Dispose();
|
|
384
|
+
_conn.Dispose();
|
|
385
|
+
_cleanup();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
public class TableClient<T> where T : new()
|
|
390
|
+
{
|
|
391
|
+
public string ConnectionString { get; }
|
|
392
|
+
public string TableName { get; }
|
|
393
|
+
|
|
394
|
+
public TableClient(string connectionString, string tableName)
|
|
395
|
+
{
|
|
396
|
+
ConnectionString = connectionString;
|
|
397
|
+
TableName = tableName;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
private SqlCommand CreateCommand(SqlConnection conn, string query)
|
|
401
|
+
{
|
|
402
|
+
var cmd = new SqlCommand(query, conn);
|
|
403
|
+
var activeTx = An5DbContext.GetActiveTransaction();
|
|
404
|
+
if (activeTx != null)
|
|
405
|
+
{
|
|
406
|
+
cmd.Transaction = activeTx;
|
|
407
|
+
}
|
|
408
|
+
return cmd;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
public List<T> QueryRaw(string query, Dictionary<string, object> parameters = null)
|
|
412
|
+
{
|
|
413
|
+
var list = new List<T>();
|
|
414
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
415
|
+
try
|
|
416
|
+
{
|
|
417
|
+
using (var cmd = CreateCommand(conn, query))
|
|
418
|
+
{
|
|
419
|
+
if (parameters != null)
|
|
420
|
+
{
|
|
421
|
+
foreach (var kvp in parameters)
|
|
422
|
+
{
|
|
423
|
+
cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
using (var reader = cmd.ExecuteReader())
|
|
428
|
+
{
|
|
429
|
+
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
|
430
|
+
while (reader.Read())
|
|
431
|
+
{
|
|
432
|
+
var item = new T();
|
|
433
|
+
foreach (var prop in properties)
|
|
434
|
+
{
|
|
435
|
+
if (HasColumn(reader, prop.Name))
|
|
436
|
+
{
|
|
437
|
+
var val = reader[prop.Name];
|
|
438
|
+
if (val != DBNull.Value)
|
|
439
|
+
{
|
|
440
|
+
prop.SetValue(item, val);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
list.Add(item);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
finally
|
|
450
|
+
{
|
|
451
|
+
if (!isTx) conn.Dispose();
|
|
452
|
+
}
|
|
453
|
+
return list;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
public List<T> FindMany(string whereClause = null, Dictionary<string, object> parameters = null)
|
|
457
|
+
{
|
|
458
|
+
var list = new List<T>();
|
|
459
|
+
string query = $"SELECT * FROM {TableName}";
|
|
460
|
+
if (!string.IsNullOrEmpty(whereClause))
|
|
461
|
+
{
|
|
462
|
+
query += $" WHERE {whereClause}";
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
466
|
+
try
|
|
467
|
+
{
|
|
468
|
+
using (var cmd = CreateCommand(conn, query))
|
|
469
|
+
{
|
|
470
|
+
if (parameters != null)
|
|
471
|
+
{
|
|
472
|
+
foreach (var kvp in parameters)
|
|
473
|
+
{
|
|
474
|
+
cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
using (var reader = cmd.ExecuteReader())
|
|
479
|
+
{
|
|
480
|
+
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
|
481
|
+
while (reader.Read())
|
|
482
|
+
{
|
|
483
|
+
var item = new T();
|
|
484
|
+
foreach (var prop in properties)
|
|
485
|
+
{
|
|
486
|
+
if (HasColumn(reader, prop.Name))
|
|
487
|
+
{
|
|
488
|
+
var val = reader[prop.Name];
|
|
489
|
+
if (val != DBNull.Value)
|
|
490
|
+
{
|
|
491
|
+
prop.SetValue(item, val);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
list.Add(item);
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
finally
|
|
501
|
+
{
|
|
502
|
+
if (!isTx) conn.Dispose();
|
|
503
|
+
}
|
|
504
|
+
return list;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
public T FindFirst(string whereClause = null, Dictionary<string, object> parameters = null)
|
|
508
|
+
{
|
|
509
|
+
string query = $"SELECT TOP 1 * FROM {TableName}";
|
|
510
|
+
if (!string.IsNullOrEmpty(whereClause))
|
|
511
|
+
{
|
|
512
|
+
query += $" WHERE {whereClause}";
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
516
|
+
try
|
|
517
|
+
{
|
|
518
|
+
using (var cmd = CreateCommand(conn, query))
|
|
519
|
+
{
|
|
520
|
+
if (parameters != null)
|
|
521
|
+
{
|
|
522
|
+
foreach (var kvp in parameters)
|
|
523
|
+
{
|
|
524
|
+
cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
using (var reader = cmd.ExecuteReader())
|
|
529
|
+
{
|
|
530
|
+
if (reader.Read())
|
|
531
|
+
{
|
|
532
|
+
var item = new T();
|
|
533
|
+
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
|
534
|
+
foreach (var prop in properties)
|
|
535
|
+
{
|
|
536
|
+
if (HasColumn(reader, prop.Name))
|
|
537
|
+
{
|
|
538
|
+
var val = reader[prop.Name];
|
|
539
|
+
if (val != DBNull.Value)
|
|
540
|
+
{
|
|
541
|
+
prop.SetValue(item, val);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return item;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
finally
|
|
551
|
+
{
|
|
552
|
+
if (!isTx) conn.Dispose();
|
|
553
|
+
}
|
|
554
|
+
return default;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
public T FindUnique(object id)
|
|
558
|
+
{
|
|
559
|
+
return FindFirst("Id = @id", new Dictionary<string, object> { { "id", id } });
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
public T Create(T entity)
|
|
563
|
+
{
|
|
564
|
+
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
|
565
|
+
var columns = new List<string>();
|
|
566
|
+
var values = new List<string>();
|
|
567
|
+
var sqlParams = new List<SqlParameter>();
|
|
568
|
+
|
|
569
|
+
foreach (var prop in properties)
|
|
570
|
+
{
|
|
571
|
+
var val = prop.GetValue(entity);
|
|
572
|
+
if (val != null)
|
|
573
|
+
{
|
|
574
|
+
columns.Add(prop.Name);
|
|
575
|
+
values.Add("@" + prop.Name);
|
|
576
|
+
sqlParams.Add(new SqlParameter("@" + prop.Name, val));
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
string query = $"INSERT INTO {TableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
|
|
581
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
582
|
+
try
|
|
583
|
+
{
|
|
584
|
+
using (var cmd = CreateCommand(conn, query))
|
|
585
|
+
{
|
|
586
|
+
cmd.Parameters.AddRange(sqlParams.ToArray());
|
|
587
|
+
cmd.ExecuteNonQuery();
|
|
588
|
+
if (!isTx)
|
|
589
|
+
{
|
|
590
|
+
// Commit standard queries if not in transaction
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
finally
|
|
595
|
+
{
|
|
596
|
+
if (!isTx) conn.Dispose();
|
|
597
|
+
}
|
|
598
|
+
return entity;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
public T Update(T entity)
|
|
602
|
+
{
|
|
603
|
+
var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
|
|
604
|
+
var sets = new List<string>();
|
|
605
|
+
var sqlParams = new List<SqlParameter>();
|
|
606
|
+
object idVal = null;
|
|
607
|
+
|
|
608
|
+
foreach (var prop in properties)
|
|
609
|
+
{
|
|
610
|
+
var val = prop.GetValue(entity);
|
|
611
|
+
if (prop.Name.Equals("Id", StringComparison.OrdinalIgnoreCase))
|
|
612
|
+
{
|
|
613
|
+
idVal = val;
|
|
614
|
+
}
|
|
615
|
+
else if (val != null)
|
|
616
|
+
{
|
|
617
|
+
sets.Add($"{prop.Name} = @{prop.Name}");
|
|
618
|
+
sqlParams.Add(new SqlParameter("@" + prop.Name, val));
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
if (idVal == null)
|
|
623
|
+
{
|
|
624
|
+
throw new InvalidOperationException("Cannot update entity without Id");
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
sqlParams.Add(new SqlParameter("@id", idVal));
|
|
628
|
+
string query = $"UPDATE {TableName} SET {string.Join(", ", sets)} WHERE Id = @id";
|
|
629
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
630
|
+
try
|
|
631
|
+
{
|
|
632
|
+
using (var cmd = CreateCommand(conn, query))
|
|
633
|
+
{
|
|
634
|
+
cmd.Parameters.AddRange(sqlParams.ToArray());
|
|
635
|
+
cmd.ExecuteNonQuery();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
finally
|
|
639
|
+
{
|
|
640
|
+
if (!isTx) conn.Dispose();
|
|
641
|
+
}
|
|
642
|
+
return entity;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
public bool Delete(object id)
|
|
646
|
+
{
|
|
647
|
+
string query = $"DELETE FROM {TableName} WHERE Id = @id";
|
|
648
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
649
|
+
try
|
|
650
|
+
{
|
|
651
|
+
using (var cmd = CreateCommand(conn, query))
|
|
652
|
+
{
|
|
653
|
+
cmd.Parameters.AddWithValue("@id", id);
|
|
654
|
+
int affected = cmd.ExecuteNonQuery();
|
|
655
|
+
return affected > 0;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
finally
|
|
659
|
+
{
|
|
660
|
+
if (!isTx) conn.Dispose();
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
public int Count(string whereClause = null, Dictionary<string, object> parameters = null)
|
|
665
|
+
{
|
|
666
|
+
string query = $"SELECT COUNT(*) FROM {TableName}";
|
|
667
|
+
if (!string.IsNullOrEmpty(whereClause)) query += $" WHERE {whereClause}";
|
|
668
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
669
|
+
try
|
|
670
|
+
{
|
|
671
|
+
using (var cmd = CreateCommand(conn, query))
|
|
672
|
+
{
|
|
673
|
+
if (parameters != null)
|
|
674
|
+
{
|
|
675
|
+
foreach (var kvp in parameters)
|
|
676
|
+
cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
|
|
677
|
+
}
|
|
678
|
+
var res = cmd.ExecuteScalar();
|
|
679
|
+
return res != null && res != DBNull.Value ? Convert.ToInt32(res) : 0;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
finally { if (!isTx) conn.Dispose(); }
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
public int CreateMany(IEnumerable<T> entities)
|
|
686
|
+
{
|
|
687
|
+
int count = 0;
|
|
688
|
+
foreach (var entity in entities)
|
|
689
|
+
{
|
|
690
|
+
Create(entity);
|
|
691
|
+
count++;
|
|
692
|
+
}
|
|
693
|
+
return count;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
public int UpdateMany(string whereClause, Dictionary<string, object> updateData, Dictionary<string, object> parameters = null)
|
|
697
|
+
{
|
|
698
|
+
if (updateData == null || updateData.Count == 0) return 0;
|
|
699
|
+
var sets = new List<string>();
|
|
700
|
+
var sqlParams = new List<SqlParameter>();
|
|
701
|
+
int pIndex = 0;
|
|
702
|
+
foreach (var kvp in updateData)
|
|
703
|
+
{
|
|
704
|
+
string paramName = "@u_" + pIndex++;
|
|
705
|
+
sets.Add($"{kvp.Key} = {paramName}");
|
|
706
|
+
sqlParams.Add(new SqlParameter(paramName, kvp.Value ?? DBNull.Value));
|
|
707
|
+
}
|
|
708
|
+
string query = $"UPDATE {TableName} SET {string.Join(", ", sets)}";
|
|
709
|
+
if (!string.IsNullOrEmpty(whereClause)) query += $" WHERE {whereClause}";
|
|
710
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
711
|
+
try
|
|
712
|
+
{
|
|
713
|
+
using (var cmd = CreateCommand(conn, query))
|
|
714
|
+
{
|
|
715
|
+
cmd.Parameters.AddRange(sqlParams.ToArray());
|
|
716
|
+
if (parameters != null)
|
|
717
|
+
{
|
|
718
|
+
foreach (var kvp in parameters)
|
|
719
|
+
cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
|
|
720
|
+
}
|
|
721
|
+
return cmd.ExecuteNonQuery();
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
finally { if (!isTx) conn.Dispose(); }
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
public int DeleteMany(string whereClause = null, Dictionary<string, object> parameters = null)
|
|
728
|
+
{
|
|
729
|
+
string query = $"DELETE FROM {TableName}";
|
|
730
|
+
if (!string.IsNullOrEmpty(whereClause)) query += $" WHERE {whereClause}";
|
|
731
|
+
var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
|
|
732
|
+
try
|
|
733
|
+
{
|
|
734
|
+
using (var cmd = CreateCommand(conn, query))
|
|
735
|
+
{
|
|
736
|
+
if (parameters != null)
|
|
737
|
+
{
|
|
738
|
+
foreach (var kvp in parameters)
|
|
739
|
+
cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
|
|
740
|
+
}
|
|
741
|
+
return cmd.ExecuteNonQuery();
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
finally { if (!isTx) conn.Dispose(); }
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
public T Upsert(T entity, string idColumnName = "Id")
|
|
748
|
+
{
|
|
749
|
+
var prop = typeof(T).GetProperty(idColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
|
750
|
+
if (prop == null) throw new InvalidOperationException($"Property '{idColumnName}' not found on entity.");
|
|
751
|
+
var idVal = prop.GetValue(entity);
|
|
752
|
+
var existing = idVal != null ? FindUnique(idVal) : default;
|
|
753
|
+
if (existing != null) return Update(entity);
|
|
754
|
+
return Create(entity);
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
public List<T> VectorSearch(List<double> vector, int take = 10, string whereClause = null, Dictionary<string, object> parameters = null, string vectorField = "Embedding", string distanceMetric = "cosine")
|
|
758
|
+
{
|
|
759
|
+
// 1. Primary path: Native database SQL vector query execution (VECTOR_DISTANCE)
|
|
760
|
+
try
|
|
761
|
+
{
|
|
762
|
+
var dim = vector.Count;
|
|
763
|
+
var vecJson = JsonSerializer.Serialize(vector);
|
|
764
|
+
var sql = $"SELECT TOP ({take}) *, VECTOR_DISTANCE('{distanceMetric}', CAST([{vectorField}] AS VECTOR({dim}, float32)), CAST(@query_vector AS VECTOR({dim}, float32))) AS distance FROM {TableName} WITH (NOLOCK)";
|
|
765
|
+
|
|
766
|
+
var p = parameters != null ? new Dictionary<string, object>(parameters) : new Dictionary<string, object>();
|
|
767
|
+
p["query_vector"] = vecJson;
|
|
768
|
+
|
|
769
|
+
if (!string.IsNullOrWhiteSpace(whereClause))
|
|
770
|
+
sql += $" WHERE [{vectorField}] IS NOT NULL AND ({whereClause})";
|
|
771
|
+
else
|
|
772
|
+
sql += $" WHERE [{vectorField}] IS NOT NULL";
|
|
773
|
+
sql += " ORDER BY distance ASC";
|
|
774
|
+
|
|
775
|
+
var nativeRows = QueryRaw(sql, p);
|
|
776
|
+
if (nativeRows != null) return nativeRows;
|
|
777
|
+
}
|
|
778
|
+
catch
|
|
779
|
+
{
|
|
780
|
+
// Fallback to in-memory similarity computation if DB instance lacks native VECTOR_DISTANCE
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// 2. Secondary fallback: In-memory similarity computation
|
|
784
|
+
var rows = FindMany(whereClause, parameters);
|
|
785
|
+
var results = new List<Tuple<T, double>>();
|
|
786
|
+
|
|
787
|
+
var propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance);
|
|
788
|
+
if (propInfo == null)
|
|
789
|
+
{
|
|
790
|
+
propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
|
791
|
+
}
|
|
792
|
+
if (propInfo == null) return rows;
|
|
793
|
+
|
|
794
|
+
foreach (var row in rows)
|
|
795
|
+
{
|
|
796
|
+
List<double> rowVector = null;
|
|
797
|
+
var rawVal = propInfo.GetValue(row);
|
|
798
|
+
if (rawVal != null)
|
|
799
|
+
{
|
|
800
|
+
try
|
|
801
|
+
{
|
|
802
|
+
if (rawVal is string jsonStr)
|
|
803
|
+
{
|
|
804
|
+
rowVector = ParseDoubleArray(jsonStr);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
catch { }
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
if (rowVector != null && rowVector.Count == vector.Count)
|
|
811
|
+
{
|
|
812
|
+
double sim = CosineSimilarity(vector, rowVector);
|
|
813
|
+
double distance = distanceMetric.Equals("cosine", StringComparison.OrdinalIgnoreCase) ? (1.0 - sim) : sim;
|
|
814
|
+
results.Add(Tuple.Create(row, distance));
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
results.Sort((a, b) => a.Item2.CompareTo(b.Item2));
|
|
819
|
+
|
|
820
|
+
var output = new List<T>();
|
|
821
|
+
int limit = Math.Min(take, results.Count);
|
|
822
|
+
for (int i = 0; i < limit; i++)
|
|
823
|
+
{
|
|
824
|
+
var distanceProp = typeof(T).GetProperty("Distance", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
|
825
|
+
if (distanceProp != null && distanceProp.PropertyType == typeof(double))
|
|
826
|
+
{
|
|
827
|
+
distanceProp.SetValue(results[i].Item1, results[i].Item2);
|
|
828
|
+
}
|
|
829
|
+
output.Add(results[i].Item1);
|
|
830
|
+
}
|
|
831
|
+
return output;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
private static List<double> ParseDoubleArray(string json)
|
|
835
|
+
{
|
|
836
|
+
var clean = json.Trim('[', ']');
|
|
837
|
+
if (string.IsNullOrWhiteSpace(clean)) return new List<double>();
|
|
838
|
+
|
|
839
|
+
var parts = clean.Split(',');
|
|
840
|
+
var list = new List<double>();
|
|
841
|
+
foreach (var p in parts)
|
|
842
|
+
{
|
|
843
|
+
if (double.TryParse(p.Trim(), out double d))
|
|
844
|
+
list.Add(d);
|
|
845
|
+
}
|
|
846
|
+
return list;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
private static double CosineSimilarity(List<double> v1, List<double> v2)
|
|
850
|
+
{
|
|
851
|
+
double dot = 0.0, m1 = 0.0, m2 = 0.0;
|
|
852
|
+
for (int i = 0; i < v1.Count; i++)
|
|
853
|
+
{
|
|
854
|
+
dot += v1[i] * v2[i];
|
|
855
|
+
m1 += v1[i] * v1[i];
|
|
856
|
+
m2 += v2[i] * v2[i];
|
|
857
|
+
}
|
|
858
|
+
if (m1 == 0 || m2 == 0) return 0.0;
|
|
859
|
+
return dot / (Math.Sqrt(m1) * Math.Sqrt(m2));
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
private bool HasColumn(SqlDataReader reader, string columnName)
|
|
863
|
+
{
|
|
864
|
+
for (int i = 0; i < reader.FieldCount; i++)
|
|
865
|
+
{
|
|
866
|
+
if (reader.GetName(i).Equals(columnName, StringComparison.OrdinalIgnoreCase))
|
|
867
|
+
return true;
|
|
868
|
+
}
|
|
869
|
+
return false;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
`;
|
|
874
|
+
|
|
875
|
+
fs.writeFileSync(path.join(this.outputDir, 'An5DbContext.cs'), content);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
private capitalize(str: string): string {
|
|
879
|
+
if (!str) return '';
|
|
880
|
+
return str[0].toUpperCase() + str.slice(1);
|
|
881
|
+
}
|
|
882
|
+
}
|