@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,546 +1,1053 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DotnetGenerator = void 0;
7
- const fs_1 = __importDefault(require("fs"));
8
- const path_1 = __importDefault(require("path"));
9
- class DotnetGenerator {
10
- constructor(outputDir) {
11
- this.outputDir = outputDir;
12
- if (!fs_1.default.existsSync(this.outputDir)) {
13
- fs_1.default.mkdirSync(this.outputDir, { recursive: true });
14
- }
15
- }
16
- generate(models) {
17
- // 1. Generate individual C# entity class files
18
- for (const model of models) {
19
- this.generateEntityClass(model);
20
- }
21
- // 2. Generate DbContext / Client metadata file
22
- this.generateDbContext(models);
23
- // 3. Generate configuration helper class
24
- this.generateConfigClass();
25
- }
26
- generateConfigClass() {
27
- const content = `// This file is auto-generated. Do not edit directly.
28
- using System;
29
-
30
- namespace An5Orm
31
- {
32
- public static class An5Config
33
- {
34
- public static string ConnectionString { get; set; } = Environment.GetEnvironmentVariable("DATABASE_URL") ?? "Server=localhost;Database=master;Trusted_Connection=True;TrustServerCertificate=True;";
35
- }
36
- }
37
- `;
38
- fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5Config.cs'), content);
39
- }
40
- mapType(fieldType, isOptional) {
41
- let csType = 'string';
42
- const lowerType = fieldType.toLowerCase();
43
- if (['int', 'integer', 'smallint', 'tinyint', 'number'].includes(lowerType)) {
44
- csType = 'int';
45
- }
46
- else if (['bigint', 'long'].includes(lowerType)) {
47
- csType = 'long';
48
- }
49
- else if (['float', 'real', 'double'].includes(lowerType)) {
50
- csType = 'double';
51
- }
52
- else if (['decimal', 'numeric', 'money', 'smallmoney'].includes(lowerType)) {
53
- csType = 'decimal';
54
- }
55
- else if (['bool', 'boolean', 'bit'].includes(lowerType)) {
56
- csType = 'bool';
57
- }
58
- else if (['datetime', 'datetime2', 'smalldatetime', 'date'].includes(lowerType)) {
59
- csType = 'DateTime';
60
- }
61
- else if (lowerType === 'datetimeoffset') {
62
- csType = 'DateTimeOffset';
63
- }
64
- else if (lowerType === 'time') {
65
- csType = 'TimeSpan';
66
- }
67
- else if (['guid', 'uuid', 'uniqueidentifier'].includes(lowerType)) {
68
- csType = 'Guid';
69
- }
70
- else if (['bytes', 'binary', 'varbinary', 'image'].includes(lowerType)) {
71
- csType = 'byte[]';
72
- }
73
- else if (['xml', 'hierarchyid', 'geography', 'geometry', 'sysname', 'sql_variant', 'sqlvariant', 'rowversion', 'variant'].includes(lowerType)) {
74
- csType = 'string';
75
- }
76
- else if (fieldType.endsWith('[]')) {
77
- csType = 'string';
78
- }
79
- if (isOptional && csType !== 'string' && !csType.endsWith('[]')) {
80
- csType += '?';
81
- }
82
- return csType;
83
- }
84
- generateEntityClass(model) {
85
- let content = `// This file is auto-generated. Do not edit directly.
86
- using System;
87
- using System.Collections.Generic;
88
-
89
- namespace An5Orm.Entities
90
- {
91
- public class ${model.name}
92
- {
93
- `;
94
- // Generate fields
95
- for (const field of model.fields) {
96
- const csType = this.mapType(field.type, field.isOptional);
97
- content += ` public ${csType} ${this.capitalize(field.name)} { get; set; }\n`;
98
- }
99
- // Generate relations
100
- if (model.relations.length > 0) {
101
- content += '\n // ── Relations ────────────────────────────────────────────────────────\n';
102
- for (const rel of model.relations) {
103
- if (rel.isArray) {
104
- content += ` public List<${rel.type}> ${this.capitalize(rel.name)} { get; set; } = new List<${rel.type}>();\n`;
105
- }
106
- else {
107
- content += ` public ${rel.type} ${this.capitalize(rel.name)} { get; set; }\n`;
108
- }
109
- }
110
- }
111
- content += ` }
112
- }
113
- `;
114
- fs_1.default.writeFileSync(path_1.default.join(this.outputDir, `${model.name}.cs`), content);
115
- }
116
- generateDbContext(models) {
117
- let content = `// This file is auto-generated. Do not edit directly.
118
- using System;
119
- using System.Collections.Generic;
120
- using System.Data;
121
- using System.Reflection;
122
- using Microsoft.Data.SqlClient;
123
- using An5Orm.Entities;
124
-
125
- namespace An5Orm
126
- {
127
- public class An5DbContext
128
- {
129
- public string ConnectionString { get; }
130
-
131
- [ThreadStatic]
132
- private static SqlConnection _txConn;
133
- [ThreadStatic]
134
- private static SqlTransaction _tx;
135
-
136
- public An5DbContext(string connectionString = null)
137
- {
138
- ConnectionString = connectionString ?? An5Config.ConnectionString;
139
- }
140
-
141
- public An5Transaction BeginTransaction()
142
- {
143
- var conn = new SqlConnection(ConnectionString);
144
- conn.Open();
145
- var tx = conn.BeginTransaction();
146
- _txConn = conn;
147
- _tx = tx;
148
- return new An5Transaction(conn, tx, () => {
149
- _txConn = null;
150
- _tx = null;
151
- });
152
- }
153
-
154
- public static SqlConnection GetActiveConnection(string connectionString, out bool isTx)
155
- {
156
- if (_txConn != null)
157
- {
158
- isTx = true;
159
- return _txConn;
160
- }
161
- isTx = false;
162
- var conn = new SqlConnection(connectionString);
163
- conn.Open();
164
- return conn;
165
- }
166
-
167
- public static SqlTransaction GetActiveTransaction() => _tx;
168
-
169
- // ── Tables / Repositories ──────────────────────────────────────────────
170
- `;
171
- for (const model of models) {
172
- content += ` public TableClient<${model.name}> ${this.capitalize(model.name)}s => new TableClient<${model.name}>(ConnectionString, "${model.schemaName}.${model.tableName}");\n`;
173
- }
174
- content += ` }
175
-
176
- public class An5Transaction : IDisposable
177
- {
178
- private readonly SqlConnection _conn;
179
- private readonly SqlTransaction _tx;
180
- private readonly Action _cleanup;
181
- private bool _completed;
182
-
183
- public An5Transaction(SqlConnection conn, SqlTransaction tx, Action cleanup)
184
- {
185
- _conn = conn;
186
- _tx = tx;
187
- _cleanup = cleanup;
188
- }
189
-
190
- public void Commit()
191
- {
192
- _tx.Commit();
193
- _completed = true;
194
- }
195
-
196
- public void Rollback()
197
- {
198
- _tx.Rollback();
199
- _completed = true;
200
- }
201
-
202
- public void Dispose()
203
- {
204
- if (!_completed)
205
- {
206
- try { _tx.Rollback(); } catch { }
207
- }
208
- _tx.Dispose();
209
- _conn.Dispose();
210
- _cleanup();
211
- }
212
- }
213
-
214
- public class TableClient<T> where T : new()
215
- {
216
- public string ConnectionString { get; }
217
- public string TableName { get; }
218
-
219
- public TableClient(string connectionString, string tableName)
220
- {
221
- ConnectionString = connectionString;
222
- TableName = tableName;
223
- }
224
-
225
- private SqlCommand CreateCommand(SqlConnection conn, string query)
226
- {
227
- var cmd = new SqlCommand(query, conn);
228
- var activeTx = An5DbContext.GetActiveTransaction();
229
- if (activeTx != null)
230
- {
231
- cmd.Transaction = activeTx;
232
- }
233
- return cmd;
234
- }
235
-
236
- public List<T> FindMany(string whereClause = null, Dictionary<string, object> parameters = null)
237
- {
238
- var list = new List<T>();
239
- string query = $"SELECT * FROM {TableName}";
240
- if (!string.IsNullOrEmpty(whereClause))
241
- {
242
- query += $" WHERE {whereClause}";
243
- }
244
-
245
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
246
- try
247
- {
248
- using (var cmd = CreateCommand(conn, query))
249
- {
250
- if (parameters != null)
251
- {
252
- foreach (var kvp in parameters)
253
- {
254
- cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
255
- }
256
- }
257
-
258
- using (var reader = cmd.ExecuteReader())
259
- {
260
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
261
- while (reader.Read())
262
- {
263
- var item = new T();
264
- foreach (var prop in properties)
265
- {
266
- if (HasColumn(reader, prop.Name))
267
- {
268
- var val = reader[prop.Name];
269
- if (val != DBNull.Value)
270
- {
271
- prop.SetValue(item, val);
272
- }
273
- }
274
- }
275
- list.Add(item);
276
- }
277
- }
278
- }
279
- }
280
- finally
281
- {
282
- if (!isTx) conn.Dispose();
283
- }
284
- return list;
285
- }
286
-
287
- public T FindFirst(string whereClause = null, Dictionary<string, object> parameters = null)
288
- {
289
- string query = $"SELECT TOP 1 * FROM {TableName}";
290
- if (!string.IsNullOrEmpty(whereClause))
291
- {
292
- query += $" WHERE {whereClause}";
293
- }
294
-
295
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
296
- try
297
- {
298
- using (var cmd = CreateCommand(conn, query))
299
- {
300
- if (parameters != null)
301
- {
302
- foreach (var kvp in parameters)
303
- {
304
- cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
305
- }
306
- }
307
-
308
- using (var reader = cmd.ExecuteReader())
309
- {
310
- if (reader.Read())
311
- {
312
- var item = new T();
313
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
314
- foreach (var prop in properties)
315
- {
316
- if (HasColumn(reader, prop.Name))
317
- {
318
- var val = reader[prop.Name];
319
- if (val != DBNull.Value)
320
- {
321
- prop.SetValue(item, val);
322
- }
323
- }
324
- }
325
- return item;
326
- }
327
- }
328
- }
329
- }
330
- finally
331
- {
332
- if (!isTx) conn.Dispose();
333
- }
334
- return default;
335
- }
336
-
337
- public T FindUnique(object id)
338
- {
339
- return FindFirst("Id = @id", new Dictionary<string, object> { { "id", id } });
340
- }
341
-
342
- public T Create(T entity)
343
- {
344
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
345
- var columns = new List<string>();
346
- var values = new List<string>();
347
- var sqlParams = new List<SqlParameter>();
348
-
349
- foreach (var prop in properties)
350
- {
351
- var val = prop.GetValue(entity);
352
- if (val != null)
353
- {
354
- columns.Add(prop.Name);
355
- values.Add("@" + prop.Name);
356
- sqlParams.Add(new SqlParameter("@" + prop.Name, val));
357
- }
358
- }
359
-
360
- string query = $"INSERT INTO {TableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
361
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
362
- try
363
- {
364
- using (var cmd = CreateCommand(conn, query))
365
- {
366
- cmd.Parameters.AddRange(sqlParams.ToArray());
367
- cmd.ExecuteNonQuery();
368
- if (!isTx)
369
- {
370
- // Commit standard queries if not in transaction
371
- }
372
- }
373
- }
374
- finally
375
- {
376
- if (!isTx) conn.Dispose();
377
- }
378
- return entity;
379
- }
380
-
381
- public T Update(T entity)
382
- {
383
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
384
- var sets = new List<string>();
385
- var sqlParams = new List<SqlParameter>();
386
- object idVal = null;
387
-
388
- foreach (var prop in properties)
389
- {
390
- var val = prop.GetValue(entity);
391
- if (prop.Name.Equals("Id", StringComparison.OrdinalIgnoreCase))
392
- {
393
- idVal = val;
394
- }
395
- else if (val != null)
396
- {
397
- sets.Add($"{prop.Name} = @{prop.Name}");
398
- sqlParams.Add(new SqlParameter("@" + prop.Name, val));
399
- }
400
- }
401
-
402
- if (idVal == null)
403
- {
404
- throw new InvalidOperationException("Cannot update entity without Id");
405
- }
406
-
407
- sqlParams.Add(new SqlParameter("@id", idVal));
408
- string query = $"UPDATE {TableName} SET {string.Join(", ", sets)} WHERE Id = @id";
409
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
410
- try
411
- {
412
- using (var cmd = CreateCommand(conn, query))
413
- {
414
- cmd.Parameters.AddRange(sqlParams.ToArray());
415
- cmd.ExecuteNonQuery();
416
- }
417
- }
418
- finally
419
- {
420
- if (!isTx) conn.Dispose();
421
- }
422
- return entity;
423
- }
424
-
425
- public bool Delete(object id)
426
- {
427
- string query = $"DELETE FROM {TableName} WHERE Id = @id";
428
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
429
- try
430
- {
431
- using (var cmd = CreateCommand(conn, query))
432
- {
433
- cmd.Parameters.AddWithValue("@id", id);
434
- int affected = cmd.ExecuteNonQuery();
435
- return affected > 0;
436
- }
437
- }
438
- finally
439
- {
440
- if (!isTx) conn.Dispose();
441
- }
442
- }
443
-
444
- public List<T> VectorSearch(List<double> vector, int take = 10, string whereClause = null, Dictionary<string, object> parameters = null, string vectorField = "Embedding", string distanceMetric = "cosine")
445
- {
446
- var rows = FindMany(whereClause, parameters);
447
- var results = new List<Tuple<T, double>>();
448
-
449
- var propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance);
450
- if (propInfo == null)
451
- {
452
- // Fallback case-insensitive
453
- propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
454
- }
455
- if (propInfo == null) return rows;
456
-
457
- foreach (var row in rows)
458
- {
459
- List<double> rowVector = null;
460
- var rawVal = propInfo.GetValue(row);
461
- if (rawVal != null)
462
- {
463
- try
464
- {
465
- if (rawVal is string jsonStr)
466
- {
467
- rowVector = ParseDoubleArray(jsonStr);
468
- }
469
- }
470
- catch { }
471
- }
472
-
473
- if (rowVector != null && rowVector.Count == vector.Count)
474
- {
475
- double sim = CosineSimilarity(vector, rowVector);
476
- double distance = distanceMetric.Equals("cosine", StringComparison.OrdinalIgnoreCase) ? (1.0 - sim) : sim;
477
- results.Add(Tuple.Create(row, distance));
478
- }
479
- }
480
-
481
- results.Sort((a, b) => a.Item2.CompareTo(b.Item2));
482
-
483
- var output = new List<T>();
484
- int limit = Math.Min(take, results.Count);
485
- for (int i = 0; i < limit; i++)
486
- {
487
- // Set the distance property if the model has a public property named Distance
488
- var distanceProp = typeof(T).GetProperty("Distance", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
489
- if (distanceProp != null && distanceProp.PropertyType == typeof(double))
490
- {
491
- distanceProp.SetValue(results[i].Item1, results[i].Item2);
492
- }
493
- output.Add(results[i].Item1);
494
- }
495
- return output;
496
- }
497
-
498
- private static List<double> ParseDoubleArray(string json)
499
- {
500
- var clean = json.Trim('[', ']');
501
- if (string.IsNullOrWhiteSpace(clean)) return new List<double>();
502
-
503
- var parts = clean.Split(',');
504
- var list = new List<double>();
505
- foreach (var p in parts)
506
- {
507
- if (double.TryParse(p.Trim(), out double d))
508
- list.Add(d);
509
- }
510
- return list;
511
- }
512
-
513
- private static double CosineSimilarity(List<double> v1, List<double> v2)
514
- {
515
- double dot = 0.0, m1 = 0.0, m2 = 0.0;
516
- for (int i = 0; i < v1.Count; i++)
517
- {
518
- dot += v1[i] * v2[i];
519
- m1 += v1[i] * v1[i];
520
- m2 += v2[i] * v2[i];
521
- }
522
- if (m1 == 0 || m2 == 0) return 0.0;
523
- return dot / (Math.Sqrt(m1) * Math.Sqrt(m2));
524
- }
525
-
526
- private bool HasColumn(SqlDataReader reader, string columnName)
527
- {
528
- for (int i = 0; i < reader.FieldCount; i++)
529
- {
530
- if (reader.GetName(i).Equals(columnName, StringComparison.OrdinalIgnoreCase))
531
- return true;
532
- }
533
- return false;
534
- }
535
- }
536
- }
537
- `;
538
- fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5DbContext.cs'), content);
539
- }
540
- capitalize(str) {
541
- if (!str)
542
- return '';
543
- return str[0].toUpperCase() + str.slice(1);
544
- }
545
- }
546
- exports.DotnetGenerator = DotnetGenerator;
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DotnetGenerator = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const types_1 = require("./types");
10
+ const type_kinds_1 = require("./type-kinds");
11
+ class DotnetGenerator {
12
+ constructor(outputDir) {
13
+ this.outputDir = outputDir;
14
+ if (!fs_1.default.existsSync(this.outputDir)) {
15
+ fs_1.default.mkdirSync(this.outputDir, { recursive: true });
16
+ }
17
+ }
18
+ generate(models) {
19
+ this.provider = models[0]?.provider;
20
+ // 1. Generate individual C# entity class files
21
+ for (const model of models) {
22
+ this.generateEntityClass(model);
23
+ }
24
+ // 2. Generate per-model ORM types (WhereInput, OrderByInput, FindManyArgs, etc.)
25
+ this.generateOrmTypes(models);
26
+ // 3. Generate DbContext / Client metadata file
27
+ this.generateDbContext(models);
28
+ // 4. Generate configuration helper class
29
+ this.generateConfigClass();
30
+ }
31
+ getCsFilterType(field, isOptional) {
32
+ // From the declared type: a DECIMAL column took the integer filter because it
33
+ // arrived as `number`.
34
+ switch ((0, type_kinds_1.fieldKind)(field, this.provider)) {
35
+ case 'date': return 'DateTimeFilter';
36
+ case 'bool': return 'BoolFilter';
37
+ case 'int':
38
+ case 'bigint': return 'IntFilter';
39
+ case 'float': return 'NumberFilter';
40
+ default: return 'StringFilter';
41
+ }
42
+ }
43
+ generateOrmTypes(models) {
44
+ let content = `// This file is auto-generated. Do not edit directly.
45
+ using System;
46
+ using System.Collections.Generic;
47
+
48
+ namespace An5Orm
49
+ {
50
+ // ── Base Filter Types ──────────────────────────────────────────────────────
51
+
52
+ /// <summary>Type-safe filter for string fields.</summary>
53
+ public class StringFilter
54
+ {
55
+ public new string Equals { get; set; }
56
+ public string Not { get; set; }
57
+ public List<string> In { get; set; }
58
+ public List<string> NotIn { get; set; }
59
+ public string Contains { get; set; }
60
+ public string StartsWith { get; set; }
61
+ public string EndsWith { get; set; }
62
+ public string Gt { get; set; }
63
+ public string Gte { get; set; }
64
+ public string Lt { get; set; }
65
+ public string Lte { get; set; }
66
+ }
67
+
68
+ /// <summary>Type-safe filter for integer fields.</summary>
69
+ public class IntFilter
70
+ {
71
+ public new int? Equals { get; set; }
72
+ public int? Not { get; set; }
73
+ public List<int> In { get; set; }
74
+ public List<int> NotIn { get; set; }
75
+ public int? Gt { get; set; }
76
+ public int? Gte { get; set; }
77
+ public int? Lt { get; set; }
78
+ public int? Lte { get; set; }
79
+ }
80
+
81
+ /// <summary>Type-safe filter for numeric/float fields.</summary>
82
+ public class NumberFilter
83
+ {
84
+ public new double? Equals { get; set; }
85
+ public double? Not { get; set; }
86
+ public List<double> In { get; set; }
87
+ public List<double> NotIn { get; set; }
88
+ public double? Gt { get; set; }
89
+ public double? Gte { get; set; }
90
+ public double? Lt { get; set; }
91
+ public double? Lte { get; set; }
92
+ }
93
+
94
+ /// <summary>Type-safe filter for boolean fields.</summary>
95
+ public class BoolFilter
96
+ {
97
+ public new bool? Equals { get; set; }
98
+ }
99
+
100
+ /// <summary>Type-safe filter for DateTime fields.</summary>
101
+ public class DateTimeFilter
102
+ {
103
+ public new DateTime? Equals { get; set; }
104
+ public DateTime? Not { get; set; }
105
+ public List<DateTime> In { get; set; }
106
+ public List<DateTime> NotIn { get; set; }
107
+ public DateTime? Gt { get; set; }
108
+ public DateTime? Gte { get; set; }
109
+ public DateTime? Lt { get; set; }
110
+ public DateTime? Lte { get; set; }
111
+ }
112
+
113
+ `;
114
+ for (const model of models) {
115
+ const name = this.capitalize(model.name);
116
+ const csType = (f) => this.mapType(f, f.isOptional);
117
+ content += ` // ── ${name} ORM Types ──────────────────────────────────────────────────────\n\n`;
118
+ // WhereInput
119
+ content += ` /// <summary>Type-safe WHERE filter for ${name} queries.</summary>\n`;
120
+ content += ` public class ${name}WhereInput\n {\n`;
121
+ content += ` public List<${name}WhereInput> AND { get; set; }\n`;
122
+ content += ` public List<${name}WhereInput> OR { get; set; }\n`;
123
+ content += ` public ${name}WhereInput NOT { get; set; }\n`;
124
+ for (const f of model.fields) {
125
+ const ft = this.getCsFilterType(f, f.isOptional);
126
+ content += ` public ${ft} ${this.capitalize(f.name)} { get; set; }\n`;
127
+ }
128
+ content += ` }\n\n`;
129
+ // OrderByInput
130
+ content += ` /// <summary>Type-safe ORDER BY for ${name} queries.</summary>\n`;
131
+ content += ` public class ${name}OrderByInput\n {\n`;
132
+ for (const f of model.fields) {
133
+ content += ` public string ${this.capitalize(f.name)} { get; set; } // "asc" or "desc"\n`;
134
+ }
135
+ content += ` }\n\n`;
136
+ // CreateInput
137
+ content += ` /// <summary>Typed data for creating a new ${name} record.</summary>\n`;
138
+ content += ` public class ${name}CreateInput\n {\n`;
139
+ for (const f of model.fields) {
140
+ if (!f.isId) {
141
+ const ct = this.mapType(f, f.isOptional || f.hasDefault);
142
+ content += ` public ${ct} ${this.capitalize(f.name)} { get; set; }\n`;
143
+ }
144
+ }
145
+ content += ` }\n\n`;
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, true); // always nullable for update
152
+ content += ` public ${ut} ${this.capitalize(f.name)} { get; set; }\n`;
153
+ }
154
+ }
155
+ content += ` }\n\n`;
156
+ // FindManyArgs
157
+ content += ` /// <summary>ORM-style args for ${name}.FindMany().</summary>\n`;
158
+ content += ` public class ${name}FindManyArgs\n {\n`;
159
+ content += ` public ${name}WhereInput Where { get; set; }\n`;
160
+ content += ` public ${name}OrderByInput OrderBy { get; set; }\n`;
161
+ content += ` public int? Take { get; set; }\n`;
162
+ content += ` public int? Skip { get; set; }\n`;
163
+ content += ` public List<string> Select { get; set; }\n`;
164
+ content += ` }\n\n`;
165
+ // FindFirstArgs
166
+ content += ` /// <summary>ORM-style args for ${name}.FindFirst().</summary>\n`;
167
+ content += ` public class ${name}FindFirstArgs\n {\n`;
168
+ content += ` public ${name}WhereInput Where { get; set; }\n`;
169
+ content += ` public ${name}OrderByInput OrderBy { get; set; }\n`;
170
+ content += ` public List<string> Select { get; set; }\n`;
171
+ content += ` }\n\n`;
172
+ // FindUniqueArgs
173
+ content += ` /// <summary>ORM-style args for ${name}.FindUnique().</summary>\n`;
174
+ content += ` public class ${name}FindUniqueArgs\n {\n`;
175
+ content += ` public ${name}WhereInput Where { get; set; }\n`;
176
+ content += ` }\n\n`;
177
+ // DeleteManyArgs
178
+ content += ` /// <summary>ORM-style args for ${name}.DeleteMany().</summary>\n`;
179
+ content += ` public class ${name}DeleteManyArgs\n {\n`;
180
+ content += ` public ${name}WhereInput Where { get; set; }\n`;
181
+ content += ` }\n\n`;
182
+ // CountArgs
183
+ content += ` /// <summary>ORM-style args for ${name}.Count().</summary>\n`;
184
+ content += ` public class ${name}CountArgs\n {\n`;
185
+ content += ` public ${name}WhereInput Where { get; set; }\n`;
186
+ content += ` }\n\n`;
187
+ }
188
+ content += `}\n`;
189
+ fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5OrmTypes.cs'), content);
190
+ }
191
+ generateConfigClass() {
192
+ const content = `// This file is auto-generated. Do not edit directly.
193
+ using System;
194
+
195
+ namespace An5Orm
196
+ {
197
+ public static class An5Config
198
+ {
199
+ public static string ConnectionString { get; set; } = Environment.GetEnvironmentVariable("DATABASE_URL") ?? "Server=localhost;Database=master;Trusted_Connection=True;TrustServerCertificate=True;";
200
+ }
201
+ }
202
+ `;
203
+ fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5Config.cs'), content);
204
+ }
205
+ /**
206
+ * The C# type for a field.
207
+ *
208
+ * Driven by the declared type, so a `DECIMAL` column is a `decimal` and a `FLOAT`
209
+ * one a `double`: both arrived as `number` and took the `int` branch.
210
+ */
211
+ mapType(field, isOptional) {
212
+ let csType;
213
+ switch ((0, type_kinds_1.fieldKind)(field, this.provider)) {
214
+ case 'int':
215
+ csType = 'int';
216
+ break;
217
+ case 'bigint':
218
+ csType = 'long';
219
+ break;
220
+ case 'float': {
221
+ // `DECIMAL`/`NUMERIC`/`MONEY` are exact and stay `decimal`; a floating
222
+ // column is a `double`. Both used to arrive as `number` and became `int`.
223
+ const base = (field.sqlType ?? field.type).replace(/\([^)]*\)/g, '').trim().toUpperCase();
224
+ csType = ['DECIMAL', 'NUMERIC', 'MONEY', 'SMALLMONEY'].includes(base) ? 'decimal' : 'double';
225
+ break;
226
+ }
227
+ case 'bool':
228
+ csType = 'bool';
229
+ break;
230
+ case 'date': {
231
+ const base = (field.sqlType ?? field.type).replace(/\([^)]*\)/g, '').trim().toUpperCase();
232
+ csType = base === 'DATETIMEOFFSET' ? 'DateTimeOffset' : base === 'TIME' ? 'TimeSpan' : 'DateTime';
233
+ break;
234
+ }
235
+ case 'bytes':
236
+ csType = 'byte[]';
237
+ break;
238
+ case 'vector':
239
+ csType = 'float[]';
240
+ break;
241
+ // JSON, XML, geometry and the rest stay strings: they are read as text and a
242
+ // Guid column is covered by the string case below via its declared name.
243
+ default: {
244
+ const base = (field.sqlType ?? field.type).replace(/\([^)]*\)/g, '').trim().toUpperCase();
245
+ csType = ['GUID', 'UUID', 'UNIQUEIDENTIFIER'].includes(base) ? 'Guid' : 'string';
246
+ break;
247
+ }
248
+ }
249
+ if (isOptional && csType !== 'string' && !csType.endsWith('[]')) {
250
+ csType += '?';
251
+ }
252
+ return csType;
253
+ }
254
+ generateEntityClass(model) {
255
+ let content = `// This file is auto-generated. Do not edit directly.
256
+ using System;
257
+ using System.Collections.Generic;
258
+
259
+ namespace An5Orm.Entities
260
+ {
261
+ public class ${model.name}
262
+ {
263
+ `;
264
+ // Generate fields
265
+ for (const field of model.fields) {
266
+ const csType = this.mapType(field, field.isOptional);
267
+ content += ` public ${csType} ${this.capitalize(field.name)} { get; set; }\n`;
268
+ }
269
+ // Generate relations
270
+ if (model.relations.length > 0) {
271
+ content += '\n // ── Relations ────────────────────────────────────────────────────────\n';
272
+ for (const rel of model.relations) {
273
+ if (rel.isArray) {
274
+ content += ` public List<${rel.type}> ${this.capitalize(rel.name)} { get; set; } = new List<${rel.type}>();\n`;
275
+ }
276
+ else {
277
+ content += ` public ${rel.type} ${this.capitalize(rel.name)} { get; set; }\n`;
278
+ }
279
+ }
280
+ }
281
+ content += ` }
282
+ }
283
+ `;
284
+ fs_1.default.writeFileSync(path_1.default.join(this.outputDir, `${model.name}.cs`), content);
285
+ }
286
+ generateDbContext(models) {
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.Data.Common;
292
+ using System.Reflection;
293
+ using System.Text.Json;
294
+ using An5Orm.Entities;
295
+
296
+ namespace An5Orm
297
+ {
298
+ /// <summary>SQL dialects this client can talk to.</summary>
299
+ public enum An5Dialect
300
+ {
301
+ Mssql,
302
+ Postgres,
303
+ Sqlite
304
+ }
305
+
306
+ /// <summary>
307
+ /// Picks the ADO.NET provider and rewrites the connection string.
308
+ ///
309
+ /// Everything below works against DbConnection/DbCommand rather than the
310
+ /// SQL Server types, because SqlClient, Npgsql and Sqlite each derive from
311
+ /// those but share no other members. Only the SQL that differs per dialect
312
+ /// is branched on.
313
+ /// </summary>
314
+ internal static class An5Provider
315
+ {
316
+ public static An5Dialect Detect(string connectionString)
317
+ {
318
+ var cs = (connectionString ?? "").Trim().ToLowerInvariant();
319
+ // SQLite first: a bare path or Data Source= would otherwise fall
320
+ // through to SQL Server.
321
+ if (cs.StartsWith("sqlite:") || cs.StartsWith("file:") || cs == ":memory:"
322
+ || cs.Contains("data source=") || cs.Contains("datasource=")
323
+ || cs.EndsWith(".db") || cs.EndsWith(".sqlite") || cs.EndsWith(".sqlite3"))
324
+ return An5Dialect.Sqlite;
325
+ if (cs.StartsWith("postgres://") || cs.StartsWith("postgresql://") || cs.Contains("host="))
326
+ return An5Dialect.Postgres;
327
+ return An5Dialect.Mssql;
328
+ }
329
+
330
+ /// <summary>
331
+ /// Rewrites the accepted SQLite spellings into the one
332
+ /// Microsoft.Data.Sqlite reads, which is Data Source=.
333
+ /// </summary>
334
+ public static string NormalizeSqlite(string connectionString)
335
+ {
336
+ var cs = (connectionString ?? "").Trim();
337
+ if (cs.Length == 0) return "Data Source=:memory:";
338
+ if (cs.IndexOf("Data Source", StringComparison.OrdinalIgnoreCase) >= 0
339
+ || cs.IndexOf("DataSource", StringComparison.OrdinalIgnoreCase) >= 0
340
+ || cs.IndexOf("Mode", StringComparison.OrdinalIgnoreCase) >= 0)
341
+ return cs;
342
+ if (cs == ":memory:") return "Data Source=:memory:";
343
+ if (cs.StartsWith("sqlite://", StringComparison.OrdinalIgnoreCase))
344
+ return "Data Source=" + cs.Substring("sqlite://".Length);
345
+ if (cs.StartsWith("sqlite:", StringComparison.OrdinalIgnoreCase))
346
+ return "Data Source=" + cs.Substring("sqlite:".Length);
347
+ if (cs.StartsWith("file:", StringComparison.OrdinalIgnoreCase)) return cs;
348
+ return "Data Source=" + cs;
349
+ }
350
+
351
+ public static DbConnection Open(string connectionString, An5Dialect dialect)
352
+ {
353
+ DbConnection conn = dialect switch
354
+ {
355
+ An5Dialect.Postgres => new Npgsql.NpgsqlConnection(connectionString),
356
+ An5Dialect.Sqlite => new Microsoft.Data.Sqlite.SqliteConnection(NormalizeSqlite(connectionString)),
357
+ _ => new Microsoft.Data.SqlClient.SqlConnection(connectionString)
358
+ };
359
+ conn.Open();
360
+ if (dialect == An5Dialect.Sqlite)
361
+ {
362
+ // WAL keeps readers off the writer's back, and SQLite leaves
363
+ // foreign keys off even when the schema declares them.
364
+ using var pragma = conn.CreateCommand();
365
+ pragma.CommandText = "PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON;";
366
+ pragma.ExecuteNonQuery();
367
+ }
368
+ return conn;
369
+ }
370
+
371
+ /// <summary>
372
+ /// Adds a parameter. The name is stored without the @ prefix: Npgsql and
373
+ /// Sqlite treat a leading @ as part of the name, while SqlClient adds it
374
+ /// back, so stripping it is the only spelling all three agree on.
375
+ /// </summary>
376
+ public static DbParameter Bind(DbCommand cmd, string name, object value)
377
+ {
378
+ var p = cmd.CreateParameter();
379
+ p.ParameterName = (name ?? "").TrimStart('@');
380
+ p.Value = value ?? DBNull.Value;
381
+ cmd.Parameters.Add(p);
382
+ return p;
383
+ }
384
+
385
+ /// <summary>Quotes an identifier for the dialect.</summary>
386
+ public static string Quote(string name, An5Dialect dialect)
387
+ {
388
+ if (name.StartsWith("[") || name.StartsWith("\\"")) return name;
389
+ if (dialect == An5Dialect.Mssql)
390
+ return "[" + name.Replace("]", "]]") + "]";
391
+ return "\\"" + name.Replace("\\"", "\\"\\"") + "\\"";
392
+ }
393
+
394
+ /// <summary>Schema-less engines have no dbo prefix on the generated table names.</summary>
395
+ public static string TableName(string tableName, An5Dialect dialect)
396
+ {
397
+ if (dialect != An5Dialect.Sqlite) return tableName;
398
+ if (tableName.StartsWith("dbo.", StringComparison.OrdinalIgnoreCase))
399
+ return tableName.Substring(4);
400
+ return tableName;
401
+ }
402
+ }
403
+
404
+ public class An5DbContext
405
+ {
406
+ public string ConnectionString { get; }
407
+ public An5Dialect Dialect { get; }
408
+
409
+ [ThreadStatic]
410
+ private static DbConnection _txConn;
411
+ [ThreadStatic]
412
+ private static DbTransaction _tx;
413
+
414
+ public An5DbContext(string connectionString = null)
415
+ {
416
+ ConnectionString = connectionString ?? An5Config.ConnectionString;
417
+ Dialect = An5Provider.Detect(ConnectionString);
418
+ }
419
+
420
+ public An5Transaction BeginTransaction()
421
+ {
422
+ var conn = An5Provider.Open(ConnectionString, Dialect);
423
+ var tx = conn.BeginTransaction();
424
+ _txConn = conn;
425
+ _tx = tx;
426
+ return new An5Transaction(conn, tx, () => {
427
+ _txConn = null;
428
+ _tx = null;
429
+ });
430
+ }
431
+
432
+ public static DbConnection GetActiveConnection(string connectionString, out bool isTx)
433
+ {
434
+ if (_txConn != null)
435
+ {
436
+ isTx = true;
437
+ return _txConn;
438
+ }
439
+ isTx = false;
440
+ return An5Provider.Open(connectionString, An5Provider.Detect(connectionString));
441
+ }
442
+
443
+ public static DbTransaction GetActiveTransaction() => _tx;
444
+
445
+ // ── Tables / Repositories ──────────────────────────────────────────────
446
+ `;
447
+ for (const model of models) {
448
+ const name = this.capitalize(model.name);
449
+ content += ` public TableClient<${model.name}> ${name}s => new TableClient<${model.name}>(ConnectionString, "${(0, types_1.dottedTableName)(model)}");\n`;
450
+ content += ` public TableClient<${model.name}> ${name} => ${name}s;\n`;
451
+ }
452
+ content += ` }
453
+
454
+ public class An5Transaction : IDisposable
455
+ {
456
+ private readonly DbConnection _conn;
457
+ private readonly DbTransaction _tx;
458
+ private readonly Action _cleanup;
459
+ private bool _completed;
460
+
461
+ public An5Transaction(DbConnection conn, DbTransaction tx, Action cleanup)
462
+ {
463
+ _conn = conn;
464
+ _tx = tx;
465
+ _cleanup = cleanup;
466
+ }
467
+
468
+ public void Commit()
469
+ {
470
+ _tx.Commit();
471
+ _completed = true;
472
+ }
473
+
474
+ public void Rollback()
475
+ {
476
+ _tx.Rollback();
477
+ _completed = true;
478
+ }
479
+
480
+ public void Dispose()
481
+ {
482
+ if (!_completed)
483
+ {
484
+ try { _tx.Rollback(); } catch { }
485
+ }
486
+ _tx.Dispose();
487
+ _conn.Dispose();
488
+ _cleanup();
489
+ }
490
+ }
491
+
492
+ public class TableClient<T> where T : new()
493
+ {
494
+ public string ConnectionString { get; }
495
+ public string TableName { get; }
496
+ public An5Dialect Dialect { get; }
497
+
498
+ public TableClient(string connectionString, string tableName)
499
+ {
500
+ ConnectionString = connectionString;
501
+ Dialect = An5Provider.Detect(connectionString);
502
+ // SQLite has no schemas, so the generated dbo. prefix would be part
503
+ // of the table name and match nothing.
504
+ TableName = An5Provider.TableName(tableName, Dialect);
505
+ }
506
+
507
+ private DbCommand CreateCommand(DbConnection conn, string query)
508
+ {
509
+ var cmd = conn.CreateCommand();
510
+ cmd.CommandText = query;
511
+ var activeTx = An5DbContext.GetActiveTransaction();
512
+ if (activeTx != null)
513
+ {
514
+ cmd.Transaction = activeTx;
515
+ }
516
+ return cmd;
517
+ }
518
+
519
+ public List<T> QueryRaw(string query, Dictionary<string, object> parameters = null)
520
+ {
521
+ var list = new List<T>();
522
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
523
+ try
524
+ {
525
+ using (var cmd = CreateCommand(conn, query))
526
+ {
527
+ if (parameters != null)
528
+ {
529
+ foreach (var kvp in parameters)
530
+ {
531
+ An5Provider.Bind(cmd, kvp.Key, kvp.Value);
532
+ }
533
+ }
534
+
535
+ using (var reader = cmd.ExecuteReader())
536
+ {
537
+ var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
538
+ while (reader.Read())
539
+ {
540
+ var item = new T();
541
+ foreach (var prop in properties)
542
+ {
543
+ if (HasColumn(reader, prop.Name))
544
+ {
545
+ var val = reader[prop.Name];
546
+ if (val != DBNull.Value)
547
+ {
548
+ SetValue(prop, item, val);
549
+ }
550
+ }
551
+ }
552
+ list.Add(item);
553
+ }
554
+ }
555
+ }
556
+ }
557
+ finally
558
+ {
559
+ if (!isTx) conn.Dispose();
560
+ }
561
+ return list;
562
+ }
563
+
564
+ public List<T> FindMany(string whereClause = null, Dictionary<string, object> parameters = null)
565
+ {
566
+ var list = new List<T>();
567
+ string query = $"SELECT * FROM {TableName}";
568
+ if (!string.IsNullOrEmpty(whereClause))
569
+ {
570
+ query += $" WHERE {whereClause}";
571
+ }
572
+
573
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
574
+ try
575
+ {
576
+ using (var cmd = CreateCommand(conn, query))
577
+ {
578
+ if (parameters != null)
579
+ {
580
+ foreach (var kvp in parameters)
581
+ {
582
+ An5Provider.Bind(cmd, kvp.Key, kvp.Value);
583
+ }
584
+ }
585
+
586
+ using (var reader = cmd.ExecuteReader())
587
+ {
588
+ var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
589
+ while (reader.Read())
590
+ {
591
+ var item = new T();
592
+ foreach (var prop in properties)
593
+ {
594
+ if (HasColumn(reader, prop.Name))
595
+ {
596
+ var val = reader[prop.Name];
597
+ if (val != DBNull.Value)
598
+ {
599
+ SetValue(prop, item, val);
600
+ }
601
+ }
602
+ }
603
+ list.Add(item);
604
+ }
605
+ }
606
+ }
607
+ }
608
+ finally
609
+ {
610
+ if (!isTx) conn.Dispose();
611
+ }
612
+ return list;
613
+ }
614
+
615
+ public T FindFirst(string whereClause = null, Dictionary<string, object> parameters = null)
616
+ {
617
+ // TOP goes before the table, LIMIT after the WHERE — appending LIMIT
618
+ // to the SELECT would put it ahead of the predicate.
619
+ string query = Dialect == An5Dialect.Mssql
620
+ ? $"SELECT TOP 1 * FROM {TableName}"
621
+ : $"SELECT * FROM {TableName}";
622
+ if (!string.IsNullOrEmpty(whereClause))
623
+ {
624
+ query += $" WHERE {whereClause}";
625
+ }
626
+ if (Dialect != An5Dialect.Mssql)
627
+ {
628
+ query += " LIMIT 1";
629
+ }
630
+
631
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
632
+ try
633
+ {
634
+ using (var cmd = CreateCommand(conn, query))
635
+ {
636
+ if (parameters != null)
637
+ {
638
+ foreach (var kvp in parameters)
639
+ {
640
+ An5Provider.Bind(cmd, kvp.Key, kvp.Value);
641
+ }
642
+ }
643
+
644
+ using (var reader = cmd.ExecuteReader())
645
+ {
646
+ if (reader.Read())
647
+ {
648
+ var item = new T();
649
+ var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
650
+ foreach (var prop in properties)
651
+ {
652
+ if (HasColumn(reader, prop.Name))
653
+ {
654
+ var val = reader[prop.Name];
655
+ if (val != DBNull.Value)
656
+ {
657
+ SetValue(prop, item, val);
658
+ }
659
+ }
660
+ }
661
+ return item;
662
+ }
663
+ }
664
+ }
665
+ }
666
+ finally
667
+ {
668
+ if (!isTx) conn.Dispose();
669
+ }
670
+ return default;
671
+ }
672
+
673
+ public T FindUnique(object id)
674
+ {
675
+ return FindFirst("Id = @id", new Dictionary<string, object> { { "id", id } });
676
+ }
677
+
678
+ public T Create(T entity)
679
+ {
680
+ var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
681
+ var columns = new List<string>();
682
+ var values = new List<string>();
683
+ // Collected before the command exists; the provider creates the
684
+ // concrete parameter type, so binding has to wait for the command.
685
+ var sqlParams = new List<(string Name, object Value)>();
686
+
687
+ foreach (var prop in properties)
688
+ {
689
+ var val = prop.GetValue(entity);
690
+ if (val != null)
691
+ {
692
+ columns.Add(prop.Name);
693
+ values.Add("@" + prop.Name);
694
+ sqlParams.Add((prop.Name, val));
695
+ }
696
+ }
697
+
698
+ string query = $"INSERT INTO {TableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
699
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
700
+ try
701
+ {
702
+ using (var cmd = CreateCommand(conn, query))
703
+ {
704
+ foreach (var (name, value) in sqlParams) An5Provider.Bind(cmd, name, value);
705
+ cmd.ExecuteNonQuery();
706
+ if (!isTx)
707
+ {
708
+ // Commit standard queries if not in transaction
709
+ }
710
+ }
711
+ }
712
+ finally
713
+ {
714
+ if (!isTx) conn.Dispose();
715
+ }
716
+ return entity;
717
+ }
718
+
719
+ public T Update(T entity)
720
+ {
721
+ var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
722
+ var sets = new List<string>();
723
+ // Collected before the command exists; the provider creates the
724
+ // concrete parameter type, so binding has to wait for the command.
725
+ var sqlParams = new List<(string Name, object Value)>();
726
+ object idVal = null;
727
+
728
+ foreach (var prop in properties)
729
+ {
730
+ var val = prop.GetValue(entity);
731
+ if (prop.Name.Equals("Id", StringComparison.OrdinalIgnoreCase))
732
+ {
733
+ idVal = val;
734
+ }
735
+ else if (val != null)
736
+ {
737
+ sets.Add($"{prop.Name} = @{prop.Name}");
738
+ sqlParams.Add((prop.Name, val));
739
+ }
740
+ }
741
+
742
+ if (idVal == null)
743
+ {
744
+ throw new InvalidOperationException("Cannot update entity without Id");
745
+ }
746
+
747
+ sqlParams.Add(("id", idVal));
748
+ string query = $"UPDATE {TableName} SET {string.Join(", ", sets)} WHERE Id = @id";
749
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
750
+ try
751
+ {
752
+ using (var cmd = CreateCommand(conn, query))
753
+ {
754
+ foreach (var (name, value) in sqlParams) An5Provider.Bind(cmd, name, value);
755
+ cmd.ExecuteNonQuery();
756
+ }
757
+ }
758
+ finally
759
+ {
760
+ if (!isTx) conn.Dispose();
761
+ }
762
+ return entity;
763
+ }
764
+
765
+ public bool Delete(object id)
766
+ {
767
+ string query = $"DELETE FROM {TableName} WHERE Id = @id";
768
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
769
+ try
770
+ {
771
+ using (var cmd = CreateCommand(conn, query))
772
+ {
773
+ An5Provider.Bind(cmd, "id", id);
774
+ int affected = cmd.ExecuteNonQuery();
775
+ return affected > 0;
776
+ }
777
+ }
778
+ finally
779
+ {
780
+ if (!isTx) conn.Dispose();
781
+ }
782
+ }
783
+
784
+ public int Count(string whereClause = null, Dictionary<string, object> parameters = null)
785
+ {
786
+ string query = $"SELECT COUNT(*) FROM {TableName}";
787
+ if (!string.IsNullOrEmpty(whereClause)) query += $" WHERE {whereClause}";
788
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
789
+ try
790
+ {
791
+ using (var cmd = CreateCommand(conn, query))
792
+ {
793
+ if (parameters != null)
794
+ {
795
+ foreach (var kvp in parameters)
796
+ An5Provider.Bind(cmd, kvp.Key, kvp.Value);
797
+ }
798
+ var res = cmd.ExecuteScalar();
799
+ return res != null && res != DBNull.Value ? Convert.ToInt32(res) : 0;
800
+ }
801
+ }
802
+ finally { if (!isTx) conn.Dispose(); }
803
+ }
804
+
805
+ public int CreateMany(IEnumerable<T> entities)
806
+ {
807
+ int count = 0;
808
+ foreach (var entity in entities)
809
+ {
810
+ Create(entity);
811
+ count++;
812
+ }
813
+ return count;
814
+ }
815
+
816
+ public int UpdateMany(string whereClause, Dictionary<string, object> updateData, Dictionary<string, object> parameters = null)
817
+ {
818
+ if (updateData == null || updateData.Count == 0) return 0;
819
+ var sets = new List<string>();
820
+ // Bound after the command exists, so the provider can create the
821
+ // right parameter type; a value tuple carries (name, value) until then.
822
+ var sqlParams = new List<(string Name, object Value)>();
823
+ int pIndex = 0;
824
+ foreach (var kvp in updateData)
825
+ {
826
+ string paramName = "@u_" + pIndex++;
827
+ sets.Add($"{kvp.Key} = {paramName}");
828
+ sqlParams.Add((paramName, kvp.Value));
829
+ }
830
+ string query = $"UPDATE {TableName} SET {string.Join(", ", sets)}";
831
+ if (!string.IsNullOrEmpty(whereClause)) query += $" WHERE {whereClause}";
832
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
833
+ try
834
+ {
835
+ using (var cmd = CreateCommand(conn, query))
836
+ {
837
+ foreach (var (name, value) in sqlParams) An5Provider.Bind(cmd, name, value);
838
+ if (parameters != null)
839
+ {
840
+ foreach (var kvp in parameters)
841
+ An5Provider.Bind(cmd, kvp.Key, kvp.Value);
842
+ }
843
+ return cmd.ExecuteNonQuery();
844
+ }
845
+ }
846
+ finally { if (!isTx) conn.Dispose(); }
847
+ }
848
+
849
+ public int DeleteMany(string whereClause = null, Dictionary<string, object> parameters = null)
850
+ {
851
+ string query = $"DELETE FROM {TableName}";
852
+ if (!string.IsNullOrEmpty(whereClause)) query += $" WHERE {whereClause}";
853
+ var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
854
+ try
855
+ {
856
+ using (var cmd = CreateCommand(conn, query))
857
+ {
858
+ if (parameters != null)
859
+ {
860
+ foreach (var kvp in parameters)
861
+ An5Provider.Bind(cmd, kvp.Key, kvp.Value);
862
+ }
863
+ return cmd.ExecuteNonQuery();
864
+ }
865
+ }
866
+ finally { if (!isTx) conn.Dispose(); }
867
+ }
868
+
869
+ public T Upsert(T entity, string idColumnName = "Id")
870
+ {
871
+ var prop = typeof(T).GetProperty(idColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
872
+ if (prop == null) throw new InvalidOperationException($"Property '{idColumnName}' not found on entity.");
873
+ var idVal = prop.GetValue(entity);
874
+ var existing = idVal != null ? FindUnique(idVal) : default;
875
+ if (existing != null) return Update(entity);
876
+ return Create(entity);
877
+ }
878
+
879
+ public List<T> VectorSearch(List<double> vector, int take = 10, string whereClause = null, Dictionary<string, object> parameters = null, string vectorField = "Embedding", string distanceMetric = "cosine")
880
+ {
881
+ // 1. Primary path: native vector query. SQL Server has VECTOR_DISTANCE
882
+ // and Postgres has pgvector; SQLite has no vector operator, so it is
883
+ // skipped outright rather than issuing SQL that can only fail and
884
+ // cost a round trip before falling through.
885
+ if (Dialect != An5Dialect.Sqlite)
886
+ try
887
+ {
888
+ var dim = vector.Count;
889
+ var vecJson = JsonSerializer.Serialize(vector);
890
+ var field = An5Provider.Quote(vectorField, Dialect);
891
+ string sql;
892
+ if (Dialect == An5Dialect.Postgres)
893
+ {
894
+ var op = distanceMetric.Equals("cosine", StringComparison.OrdinalIgnoreCase) ? "<=>"
895
+ : (distanceMetric.Equals("euclidean", StringComparison.OrdinalIgnoreCase) ? "<->" : "<#>");
896
+ sql = $"SELECT *, ({field} {op} @query_vector::vector) AS distance FROM {TableName}";
897
+ }
898
+ else
899
+ {
900
+ sql = $"SELECT TOP ({take}) *, VECTOR_DISTANCE('{distanceMetric}', CAST({field} AS VECTOR({dim}, float32)), CAST(@query_vector AS VECTOR({dim}, float32))) AS distance FROM {TableName} WITH (NOLOCK)";
901
+ }
902
+
903
+ var p = parameters != null ? new Dictionary<string, object>(parameters) : new Dictionary<string, object>();
904
+ p["query_vector"] = vecJson;
905
+
906
+ if (!string.IsNullOrWhiteSpace(whereClause))
907
+ sql += $" WHERE {field} IS NOT NULL AND ({whereClause})";
908
+ else
909
+ sql += $" WHERE {field} IS NOT NULL";
910
+ sql += " ORDER BY distance ASC";
911
+ if (Dialect == An5Dialect.Postgres) sql += $" LIMIT {take}";
912
+
913
+ var nativeRows = QueryRaw(sql, p);
914
+ if (nativeRows != null) return nativeRows;
915
+ }
916
+ catch
917
+ {
918
+ // Fallback to in-memory similarity computation if the database has no native vector support
919
+ }
920
+
921
+ // 2. Secondary fallback: In-memory similarity computation
922
+ var rows = FindMany(whereClause, parameters);
923
+ var results = new List<Tuple<T, double>>();
924
+
925
+ var propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance);
926
+ if (propInfo == null)
927
+ {
928
+ propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
929
+ }
930
+ if (propInfo == null) return rows;
931
+
932
+ foreach (var row in rows)
933
+ {
934
+ List<double> rowVector = null;
935
+ var rawVal = propInfo.GetValue(row);
936
+ if (rawVal != null)
937
+ {
938
+ try
939
+ {
940
+ if (rawVal is string jsonStr)
941
+ {
942
+ rowVector = ParseDoubleArray(jsonStr);
943
+ }
944
+ }
945
+ catch { }
946
+ }
947
+
948
+ if (rowVector != null && rowVector.Count == vector.Count)
949
+ {
950
+ double sim = CosineSimilarity(vector, rowVector);
951
+ double distance = distanceMetric.Equals("cosine", StringComparison.OrdinalIgnoreCase) ? (1.0 - sim) : sim;
952
+ results.Add(Tuple.Create(row, distance));
953
+ }
954
+ }
955
+
956
+ results.Sort((a, b) => a.Item2.CompareTo(b.Item2));
957
+
958
+ var output = new List<T>();
959
+ int limit = Math.Min(take, results.Count);
960
+ for (int i = 0; i < limit; i++)
961
+ {
962
+ var distanceProp = typeof(T).GetProperty("Distance", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
963
+ if (distanceProp != null && distanceProp.PropertyType == typeof(double))
964
+ {
965
+ distanceProp.SetValue(results[i].Item1, results[i].Item2);
966
+ }
967
+ output.Add(results[i].Item1);
968
+ }
969
+ return output;
970
+ }
971
+
972
+ private static List<double> ParseDoubleArray(string json)
973
+ {
974
+ var clean = json.Trim('[', ']');
975
+ if (string.IsNullOrWhiteSpace(clean)) return new List<double>();
976
+
977
+ var parts = clean.Split(',');
978
+ var list = new List<double>();
979
+ foreach (var p in parts)
980
+ {
981
+ if (double.TryParse(p.Trim(), out double d))
982
+ list.Add(d);
983
+ }
984
+ return list;
985
+ }
986
+
987
+ private static double CosineSimilarity(List<double> v1, List<double> v2)
988
+ {
989
+ double dot = 0.0, m1 = 0.0, m2 = 0.0;
990
+ for (int i = 0; i < v1.Count; i++)
991
+ {
992
+ dot += v1[i] * v2[i];
993
+ m1 += v1[i] * v1[i];
994
+ m2 += v2[i] * v2[i];
995
+ }
996
+ if (m1 == 0 || m2 == 0) return 0.0;
997
+ return dot / (Math.Sqrt(m1) * Math.Sqrt(m2));
998
+ }
999
+
1000
+ /// <summary>
1001
+ /// Assigns a column to a property, converting when the provider's CLR
1002
+ /// type does not match the property.
1003
+ ///
1004
+ /// Required across dialects, not just for SQLite: SQLite hands back
1005
+ /// dates as TEXT and every integer as Int64, so a DateTime or int
1006
+ /// property would otherwise fail to set. A value that cannot be
1007
+ /// converted is skipped rather than aborting the whole read.
1008
+ /// </summary>
1009
+ private static void SetValue(System.Reflection.PropertyInfo prop, object target, object value)
1010
+ {
1011
+ var wanted = prop.PropertyType;
1012
+ if (wanted.IsInstanceOfType(value))
1013
+ {
1014
+ prop.SetValue(target, value);
1015
+ return;
1016
+ }
1017
+ try
1018
+ {
1019
+ var underlying = Nullable.GetUnderlyingType(wanted);
1020
+ if (underlying != null && value == null) { prop.SetValue(target, null); return; }
1021
+ if (underlying != null)
1022
+ {
1023
+ prop.SetValue(target, Convert.ChangeType(value, underlying));
1024
+ return;
1025
+ }
1026
+ if (value is string text && wanted == typeof(Guid)) { prop.SetValue(target, Guid.Parse(text)); return; }
1027
+ if (value is string when && wanted == typeof(DateTime)) { prop.SetValue(target, DateTime.Parse(when, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind)); return; }
1028
+ prop.SetValue(target, Convert.ChangeType(value, wanted));
1029
+ }
1030
+ catch { }
1031
+ }
1032
+
1033
+ private bool HasColumn(DbDataReader reader, string columnName)
1034
+ {
1035
+ for (int i = 0; i < reader.FieldCount; i++)
1036
+ {
1037
+ if (reader.GetName(i).Equals(columnName, StringComparison.OrdinalIgnoreCase))
1038
+ return true;
1039
+ }
1040
+ return false;
1041
+ }
1042
+ }
1043
+ }
1044
+ `;
1045
+ fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5DbContext.cs'), content);
1046
+ }
1047
+ capitalize(str) {
1048
+ if (!str)
1049
+ return '';
1050
+ return str[0].toUpperCase() + str.slice(1);
1051
+ }
1052
+ }
1053
+ exports.DotnetGenerator = DotnetGenerator;