@an5/orm 1.0.4 → 1.0.6

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.
@@ -24,16 +24,16 @@ class DotnetGenerator {
24
24
  this.generateConfigClass();
25
25
  }
26
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
- }
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
37
  `;
38
38
  fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5Config.cs'), content);
39
39
  }
@@ -82,14 +82,14 @@ namespace An5Orm
82
82
  return csType;
83
83
  }
84
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
- {
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
93
  `;
94
94
  // Generate fields
95
95
  for (const field of model.fields) {
@@ -108,432 +108,432 @@ namespace An5Orm.Entities
108
108
  }
109
109
  }
110
110
  }
111
- content += ` }
112
- }
111
+ content += ` }
112
+ }
113
113
  `;
114
114
  fs_1.default.writeFileSync(path_1.default.join(this.outputDir, `${model.name}.cs`), content);
115
115
  }
116
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 ──────────────────────────────────────────────
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
170
  `;
171
171
  for (const model of models) {
172
172
  content += ` public TableClient<${model.name}> ${this.capitalize(model.name)}s => new TableClient<${model.name}>(ConnectionString, "${model.schemaName}.${model.tableName}");\n`;
173
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
- }
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
537
  `;
538
538
  fs_1.default.writeFileSync(path_1.default.join(this.outputDir, 'An5DbContext.cs'), content);
539
539
  }