@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.
Files changed (38) hide show
  1. package/README.md +167 -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/errors.d.ts +1 -1
  6. package/dist/errors.js +1 -1
  7. package/dist/generator/src/code-generator.d.ts +14 -13
  8. package/dist/generator/src/code-generator.js +249 -225
  9. package/dist/generator/src/dotnet-generator.d.ts +13 -11
  10. package/dist/generator/src/dotnet-generator.js +872 -546
  11. package/dist/generator/src/index.d.ts +1 -1
  12. package/dist/generator/src/index.js +104 -88
  13. package/dist/generator/src/metadata-generator.d.ts +11 -8
  14. package/dist/generator/src/metadata-generator.js +104 -90
  15. package/dist/generator/src/parser.d.ts +11 -11
  16. package/dist/generator/src/parser.js +206 -206
  17. package/dist/generator/src/python-generator.d.ts +19 -9
  18. package/dist/generator/src/python-generator.js +345 -105
  19. package/dist/generator/src/types.d.ts +27 -27
  20. package/dist/generator/src/types.js +2 -2
  21. package/dist/index.d.ts +3 -2
  22. package/dist/index.js +19 -8
  23. package/dist/logger.js +1 -1
  24. package/dist/migration-core.d.ts +87 -0
  25. package/dist/migration-core.js +692 -0
  26. package/dist/scripts/release-cli.d.ts +2 -2
  27. package/dist/scripts/release-cli.js +115 -115
  28. package/dist/sql-utils.d.ts +3 -1
  29. package/dist/sql-utils.js +94 -24
  30. package/generator/src/code-generator.ts +259 -230
  31. package/generator/src/dotnet-generator.ts +882 -544
  32. package/generator/src/golang-generator.ts +1242 -0
  33. package/generator/src/index.ts +111 -116
  34. package/generator/src/metadata-generator.ts +116 -101
  35. package/generator/src/parser.ts +202 -202
  36. package/generator/src/python-generator.ts +424 -114
  37. package/generator/src/types.ts +29 -29
  38. 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 DbContext / Client metadata file
19
- this.generateDbContext(models);
20
-
21
- // 3. Generate configuration helper class
22
- this.generateConfigClass();
23
- }
24
-
25
- private generateConfigClass() {
26
- const content = `// This file is auto-generated. Do not edit directly.
27
- using System;
28
-
29
- namespace An5Orm
30
- {
31
- public static class An5Config
32
- {
33
- public static string ConnectionString { get; set; } = Environment.GetEnvironmentVariable("DATABASE_URL") ?? "Server=localhost;Database=master;Trusted_Connection=True;TrustServerCertificate=True;";
34
- }
35
- }
36
- `;
37
- fs.writeFileSync(path.join(this.outputDir, 'An5Config.cs'), content);
38
- }
39
-
40
- private mapType(fieldType: string, isOptional: boolean): string {
41
- let csType = 'string';
42
- const lowerType = fieldType.toLowerCase();
43
-
44
- if (['int', 'integer', 'smallint', 'tinyint', 'number'].includes(lowerType)) {
45
- csType = 'int';
46
- } else if (['bigint', 'long'].includes(lowerType)) {
47
- csType = 'long';
48
- } else if (['float', 'real', 'double'].includes(lowerType)) {
49
- csType = 'double';
50
- } else if (['decimal', 'numeric', 'money', 'smallmoney'].includes(lowerType)) {
51
- csType = 'decimal';
52
- } else if (['bool', 'boolean', 'bit'].includes(lowerType)) {
53
- csType = 'bool';
54
- } else if (['datetime', 'datetime2', 'smalldatetime', 'date'].includes(lowerType)) {
55
- csType = 'DateTime';
56
- } else if (lowerType === 'datetimeoffset') {
57
- csType = 'DateTimeOffset';
58
- } else if (lowerType === 'time') {
59
- csType = 'TimeSpan';
60
- } else if (['guid', 'uuid', 'uniqueidentifier'].includes(lowerType)) {
61
- csType = 'Guid';
62
- } else if (['bytes', 'binary', 'varbinary', 'image'].includes(lowerType)) {
63
- csType = 'byte[]';
64
- } else if (['xml', 'hierarchyid', 'geography', 'geometry', 'sysname', 'sql_variant', 'sqlvariant', 'rowversion', 'variant'].includes(lowerType)) {
65
- csType = 'string';
66
- } else if (fieldType.endsWith('[]')) {
67
- csType = 'string';
68
- }
69
-
70
- if (isOptional && csType !== 'string' && !csType.endsWith('[]')) {
71
- csType += '?';
72
- }
73
- return csType;
74
- }
75
-
76
- private generateEntityClass(model: Model) {
77
- let content = `// This file is auto-generated. Do not edit directly.
78
- using System;
79
- using System.Collections.Generic;
80
-
81
- namespace An5Orm.Entities
82
- {
83
- public class ${model.name}
84
- {
85
- `;
86
-
87
- // Generate fields
88
- for (const field of model.fields) {
89
- const csType = this.mapType(field.type, field.isOptional);
90
- content += ` public ${csType} ${this.capitalize(field.name)} { get; set; }\n`;
91
- }
92
-
93
- // Generate relations
94
- if (model.relations.length > 0) {
95
- content += '\n // ── Relations ────────────────────────────────────────────────────────\n';
96
- for (const rel of model.relations) {
97
- if (rel.isArray) {
98
- content += ` public List<${rel.type}> ${this.capitalize(rel.name)} { get; set; } = new List<${rel.type}>();\n`;
99
- } else {
100
- content += ` public ${rel.type} ${this.capitalize(rel.name)} { get; set; }\n`;
101
- }
102
- }
103
- }
104
-
105
- content += ` }
106
- }
107
- `;
108
-
109
- fs.writeFileSync(path.join(this.outputDir, `${model.name}.cs`), content);
110
- }
111
-
112
- private generateDbContext(models: Model[]) {
113
- let content = `// This file is auto-generated. Do not edit directly.
114
- using System;
115
- using System.Collections.Generic;
116
- using System.Data;
117
- using System.Reflection;
118
- using Microsoft.Data.SqlClient;
119
- using An5Orm.Entities;
120
-
121
- namespace An5Orm
122
- {
123
- public class An5DbContext
124
- {
125
- public string ConnectionString { get; }
126
-
127
- [ThreadStatic]
128
- private static SqlConnection _txConn;
129
- [ThreadStatic]
130
- private static SqlTransaction _tx;
131
-
132
- public An5DbContext(string connectionString = null)
133
- {
134
- ConnectionString = connectionString ?? An5Config.ConnectionString;
135
- }
136
-
137
- public An5Transaction BeginTransaction()
138
- {
139
- var conn = new SqlConnection(ConnectionString);
140
- conn.Open();
141
- var tx = conn.BeginTransaction();
142
- _txConn = conn;
143
- _tx = tx;
144
- return new An5Transaction(conn, tx, () => {
145
- _txConn = null;
146
- _tx = null;
147
- });
148
- }
149
-
150
- public static SqlConnection GetActiveConnection(string connectionString, out bool isTx)
151
- {
152
- if (_txConn != null)
153
- {
154
- isTx = true;
155
- return _txConn;
156
- }
157
- isTx = false;
158
- var conn = new SqlConnection(connectionString);
159
- conn.Open();
160
- return conn;
161
- }
162
-
163
- public static SqlTransaction GetActiveTransaction() => _tx;
164
-
165
- // ── Tables / Repositories ──────────────────────────────────────────────
166
- `;
167
-
168
- for (const model of models) {
169
- content += ` public TableClient<${model.name}> ${this.capitalize(model.name)}s => new TableClient<${model.name}>(ConnectionString, "${model.schemaName}.${model.tableName}");\n`;
170
- }
171
-
172
- content += ` }
173
-
174
- public class An5Transaction : IDisposable
175
- {
176
- private readonly SqlConnection _conn;
177
- private readonly SqlTransaction _tx;
178
- private readonly Action _cleanup;
179
- private bool _completed;
180
-
181
- public An5Transaction(SqlConnection conn, SqlTransaction tx, Action cleanup)
182
- {
183
- _conn = conn;
184
- _tx = tx;
185
- _cleanup = cleanup;
186
- }
187
-
188
- public void Commit()
189
- {
190
- _tx.Commit();
191
- _completed = true;
192
- }
193
-
194
- public void Rollback()
195
- {
196
- _tx.Rollback();
197
- _completed = true;
198
- }
199
-
200
- public void Dispose()
201
- {
202
- if (!_completed)
203
- {
204
- try { _tx.Rollback(); } catch { }
205
- }
206
- _tx.Dispose();
207
- _conn.Dispose();
208
- _cleanup();
209
- }
210
- }
211
-
212
- public class TableClient<T> where T : new()
213
- {
214
- public string ConnectionString { get; }
215
- public string TableName { get; }
216
-
217
- public TableClient(string connectionString, string tableName)
218
- {
219
- ConnectionString = connectionString;
220
- TableName = tableName;
221
- }
222
-
223
- private SqlCommand CreateCommand(SqlConnection conn, string query)
224
- {
225
- var cmd = new SqlCommand(query, conn);
226
- var activeTx = An5DbContext.GetActiveTransaction();
227
- if (activeTx != null)
228
- {
229
- cmd.Transaction = activeTx;
230
- }
231
- return cmd;
232
- }
233
-
234
- public List<T> FindMany(string whereClause = null, Dictionary<string, object> parameters = null)
235
- {
236
- var list = new List<T>();
237
- string query = $"SELECT * FROM {TableName}";
238
- if (!string.IsNullOrEmpty(whereClause))
239
- {
240
- query += $" WHERE {whereClause}";
241
- }
242
-
243
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
244
- try
245
- {
246
- using (var cmd = CreateCommand(conn, query))
247
- {
248
- if (parameters != null)
249
- {
250
- foreach (var kvp in parameters)
251
- {
252
- cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
253
- }
254
- }
255
-
256
- using (var reader = cmd.ExecuteReader())
257
- {
258
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
259
- while (reader.Read())
260
- {
261
- var item = new T();
262
- foreach (var prop in properties)
263
- {
264
- if (HasColumn(reader, prop.Name))
265
- {
266
- var val = reader[prop.Name];
267
- if (val != DBNull.Value)
268
- {
269
- prop.SetValue(item, val);
270
- }
271
- }
272
- }
273
- list.Add(item);
274
- }
275
- }
276
- }
277
- }
278
- finally
279
- {
280
- if (!isTx) conn.Dispose();
281
- }
282
- return list;
283
- }
284
-
285
- public T FindFirst(string whereClause = null, Dictionary<string, object> parameters = null)
286
- {
287
- string query = $"SELECT TOP 1 * FROM {TableName}";
288
- if (!string.IsNullOrEmpty(whereClause))
289
- {
290
- query += $" WHERE {whereClause}";
291
- }
292
-
293
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
294
- try
295
- {
296
- using (var cmd = CreateCommand(conn, query))
297
- {
298
- if (parameters != null)
299
- {
300
- foreach (var kvp in parameters)
301
- {
302
- cmd.Parameters.AddWithValue(kvp.Key.StartsWith("@") ? kvp.Key : "@" + kvp.Key, kvp.Value ?? DBNull.Value);
303
- }
304
- }
305
-
306
- using (var reader = cmd.ExecuteReader())
307
- {
308
- if (reader.Read())
309
- {
310
- var item = new T();
311
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
312
- foreach (var prop in properties)
313
- {
314
- if (HasColumn(reader, prop.Name))
315
- {
316
- var val = reader[prop.Name];
317
- if (val != DBNull.Value)
318
- {
319
- prop.SetValue(item, val);
320
- }
321
- }
322
- }
323
- return item;
324
- }
325
- }
326
- }
327
- }
328
- finally
329
- {
330
- if (!isTx) conn.Dispose();
331
- }
332
- return default;
333
- }
334
-
335
- public T FindUnique(object id)
336
- {
337
- return FindFirst("Id = @id", new Dictionary<string, object> { { "id", id } });
338
- }
339
-
340
- public T Create(T entity)
341
- {
342
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
343
- var columns = new List<string>();
344
- var values = new List<string>();
345
- var sqlParams = new List<SqlParameter>();
346
-
347
- foreach (var prop in properties)
348
- {
349
- var val = prop.GetValue(entity);
350
- if (val != null)
351
- {
352
- columns.Add(prop.Name);
353
- values.Add("@" + prop.Name);
354
- sqlParams.Add(new SqlParameter("@" + prop.Name, val));
355
- }
356
- }
357
-
358
- string query = $"INSERT INTO {TableName} ({string.Join(", ", columns)}) VALUES ({string.Join(", ", values)})";
359
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
360
- try
361
- {
362
- using (var cmd = CreateCommand(conn, query))
363
- {
364
- cmd.Parameters.AddRange(sqlParams.ToArray());
365
- cmd.ExecuteNonQuery();
366
- if (!isTx)
367
- {
368
- // Commit standard queries if not in transaction
369
- }
370
- }
371
- }
372
- finally
373
- {
374
- if (!isTx) conn.Dispose();
375
- }
376
- return entity;
377
- }
378
-
379
- public T Update(T entity)
380
- {
381
- var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
382
- var sets = new List<string>();
383
- var sqlParams = new List<SqlParameter>();
384
- object idVal = null;
385
-
386
- foreach (var prop in properties)
387
- {
388
- var val = prop.GetValue(entity);
389
- if (prop.Name.Equals("Id", StringComparison.OrdinalIgnoreCase))
390
- {
391
- idVal = val;
392
- }
393
- else if (val != null)
394
- {
395
- sets.Add($"{prop.Name} = @{prop.Name}");
396
- sqlParams.Add(new SqlParameter("@" + prop.Name, val));
397
- }
398
- }
399
-
400
- if (idVal == null)
401
- {
402
- throw new InvalidOperationException("Cannot update entity without Id");
403
- }
404
-
405
- sqlParams.Add(new SqlParameter("@id", idVal));
406
- string query = $"UPDATE {TableName} SET {string.Join(", ", sets)} WHERE Id = @id";
407
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
408
- try
409
- {
410
- using (var cmd = CreateCommand(conn, query))
411
- {
412
- cmd.Parameters.AddRange(sqlParams.ToArray());
413
- cmd.ExecuteNonQuery();
414
- }
415
- }
416
- finally
417
- {
418
- if (!isTx) conn.Dispose();
419
- }
420
- return entity;
421
- }
422
-
423
- public bool Delete(object id)
424
- {
425
- string query = $"DELETE FROM {TableName} WHERE Id = @id";
426
- var conn = An5DbContext.GetActiveConnection(ConnectionString, out bool isTx);
427
- try
428
- {
429
- using (var cmd = CreateCommand(conn, query))
430
- {
431
- cmd.Parameters.AddWithValue("@id", id);
432
- int affected = cmd.ExecuteNonQuery();
433
- return affected > 0;
434
- }
435
- }
436
- finally
437
- {
438
- if (!isTx) conn.Dispose();
439
- }
440
- }
441
-
442
- public List<T> VectorSearch(List<double> vector, int take = 10, string whereClause = null, Dictionary<string, object> parameters = null, string vectorField = "Embedding", string distanceMetric = "cosine")
443
- {
444
- var rows = FindMany(whereClause, parameters);
445
- var results = new List<Tuple<T, double>>();
446
-
447
- var propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance);
448
- if (propInfo == null)
449
- {
450
- // Fallback case-insensitive
451
- propInfo = typeof(T).GetProperty(vectorField, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
452
- }
453
- if (propInfo == null) return rows;
454
-
455
- foreach (var row in rows)
456
- {
457
- List<double> rowVector = null;
458
- var rawVal = propInfo.GetValue(row);
459
- if (rawVal != null)
460
- {
461
- try
462
- {
463
- if (rawVal is string jsonStr)
464
- {
465
- rowVector = ParseDoubleArray(jsonStr);
466
- }
467
- }
468
- catch { }
469
- }
470
-
471
- if (rowVector != null && rowVector.Count == vector.Count)
472
- {
473
- double sim = CosineSimilarity(vector, rowVector);
474
- double distance = distanceMetric.Equals("cosine", StringComparison.OrdinalIgnoreCase) ? (1.0 - sim) : sim;
475
- results.Add(Tuple.Create(row, distance));
476
- }
477
- }
478
-
479
- results.Sort((a, b) => a.Item2.CompareTo(b.Item2));
480
-
481
- var output = new List<T>();
482
- int limit = Math.Min(take, results.Count);
483
- for (int i = 0; i < limit; i++)
484
- {
485
- // Set the distance property if the model has a public property named Distance
486
- var distanceProp = typeof(T).GetProperty("Distance", BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
487
- if (distanceProp != null && distanceProp.PropertyType == typeof(double))
488
- {
489
- distanceProp.SetValue(results[i].Item1, results[i].Item2);
490
- }
491
- output.Add(results[i].Item1);
492
- }
493
- return output;
494
- }
495
-
496
- private static List<double> ParseDoubleArray(string json)
497
- {
498
- var clean = json.Trim('[', ']');
499
- if (string.IsNullOrWhiteSpace(clean)) return new List<double>();
500
-
501
- var parts = clean.Split(',');
502
- var list = new List<double>();
503
- foreach (var p in parts)
504
- {
505
- if (double.TryParse(p.Trim(), out double d))
506
- list.Add(d);
507
- }
508
- return list;
509
- }
510
-
511
- private static double CosineSimilarity(List<double> v1, List<double> v2)
512
- {
513
- double dot = 0.0, m1 = 0.0, m2 = 0.0;
514
- for (int i = 0; i < v1.Count; i++)
515
- {
516
- dot += v1[i] * v2[i];
517
- m1 += v1[i] * v1[i];
518
- m2 += v2[i] * v2[i];
519
- }
520
- if (m1 == 0 || m2 == 0) return 0.0;
521
- return dot / (Math.Sqrt(m1) * Math.Sqrt(m2));
522
- }
523
-
524
- private bool HasColumn(SqlDataReader reader, string columnName)
525
- {
526
- for (int i = 0; i < reader.FieldCount; i++)
527
- {
528
- if (reader.GetName(i).Equals(columnName, StringComparison.OrdinalIgnoreCase))
529
- return true;
530
- }
531
- return false;
532
- }
533
- }
534
- }
535
- `;
536
-
537
- fs.writeFileSync(path.join(this.outputDir, 'An5DbContext.cs'), content);
538
- }
539
-
540
- private capitalize(str: string): string {
541
- if (!str) return '';
542
- return str[0].toUpperCase() + str.slice(1);
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
+ }