@an5/orm 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/an5Orm.js +2 -2
- package/dist/cleanup.js +3 -3
- package/dist/cli.js +64 -0
- package/dist/generator/src/code-generator.d.ts +13 -0
- package/dist/generator/src/code-generator.js +225 -0
- package/dist/generator/src/dotnet-generator.d.ts +11 -0
- package/dist/generator/src/dotnet-generator.js +546 -0
- package/dist/generator/src/index.d.ts +1 -0
- package/dist/generator/src/index.js +85 -0
- package/dist/generator/src/metadata-generator.d.ts +8 -0
- package/dist/generator/src/metadata-generator.js +72 -0
- package/dist/generator/src/parser.d.ts +11 -0
- package/dist/generator/src/parser.js +206 -0
- package/dist/generator/src/python-generator.d.ts +9 -0
- package/dist/generator/src/python-generator.js +85 -0
- package/dist/generator/src/types.d.ts +27 -0
- package/dist/generator/src/types.js +2 -0
- package/dist/migrate.js +3 -3
- package/dist/pull.js +3 -3
- package/dist/push.js +3 -3
- package/generator/src/index.ts +1 -1
- package/package.json +5 -1
|
@@ -0,0 +1,546 @@
|
|
|
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;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,85 @@
|
|
|
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
|
+
const path_1 = __importDefault(require("path"));
|
|
7
|
+
const parser_1 = require("./parser");
|
|
8
|
+
const code_generator_1 = require("./code-generator");
|
|
9
|
+
const metadata_generator_1 = require("./metadata-generator");
|
|
10
|
+
const python_generator_1 = require("./python-generator");
|
|
11
|
+
const dotnet_generator_1 = require("./dotnet-generator");
|
|
12
|
+
const fs_1 = __importDefault(require("fs"));
|
|
13
|
+
function clearGeneratedFiles(outputDir, extension) {
|
|
14
|
+
if (!fs_1.default.existsSync(outputDir)) {
|
|
15
|
+
fs_1.default.mkdirSync(outputDir, { recursive: true });
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
for (const entry of fs_1.default.readdirSync(outputDir)) {
|
|
19
|
+
const fullPath = path_1.default.join(outputDir, entry);
|
|
20
|
+
const stat = fs_1.default.statSync(fullPath);
|
|
21
|
+
if (stat.isDirectory())
|
|
22
|
+
continue;
|
|
23
|
+
if (entry.endsWith(extension)) {
|
|
24
|
+
fs_1.default.unlinkSync(fullPath);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function main() {
|
|
29
|
+
const rootDir = process.cwd();
|
|
30
|
+
let config = {};
|
|
31
|
+
try {
|
|
32
|
+
const configPath = path_1.default.join(rootDir, 'an5Orm.config.js');
|
|
33
|
+
if (fs_1.default.existsSync(configPath)) {
|
|
34
|
+
config = require(configPath);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
catch (err) {
|
|
38
|
+
console.warn('⚠️ Could not load an5Orm.config.js, using defaults.', err);
|
|
39
|
+
}
|
|
40
|
+
const schemaDir = path_1.default.resolve(rootDir, config.schemaDir || 'an5Schema');
|
|
41
|
+
const outputTypesDir = path_1.default.resolve(rootDir, config.outputs?.typescript?.outputDir || 'an5Client/typescript');
|
|
42
|
+
const outputMetadataPath = path_1.default.resolve(rootDir, config.outputs?.typescript?.metadataFile || 'an5Client/typescript/an5Metadata.ts');
|
|
43
|
+
const outputPythonMetadataPath = path_1.default.resolve(rootDir, config.outputs?.python?.metadataFile || 'an5Client/python/an5_metadata.py');
|
|
44
|
+
const outputDotnetDir = path_1.default.resolve(rootDir, config.outputs?.dotnet?.outputDir || 'an5Client/dotnet');
|
|
45
|
+
console.log('🚀 Starting ORM generation...');
|
|
46
|
+
try {
|
|
47
|
+
clearGeneratedFiles(outputTypesDir, '.ts');
|
|
48
|
+
clearGeneratedFiles(outputDotnetDir, '.cs');
|
|
49
|
+
if (fs_1.default.existsSync(outputMetadataPath)) {
|
|
50
|
+
fs_1.default.unlinkSync(outputMetadataPath);
|
|
51
|
+
}
|
|
52
|
+
if (fs_1.default.existsSync(outputPythonMetadataPath)) {
|
|
53
|
+
fs_1.default.unlinkSync(outputPythonMetadataPath);
|
|
54
|
+
}
|
|
55
|
+
const parser = new parser_1.SchemaParser(schemaDir);
|
|
56
|
+
const models = await parser.parse();
|
|
57
|
+
console.log(`📦 Parsed ${models.length} models from schema.`);
|
|
58
|
+
const codeGen = new code_generator_1.CodeGenerator(outputTypesDir);
|
|
59
|
+
codeGen.generate(models);
|
|
60
|
+
console.log(`✨ Generated modular types in ${outputTypesDir}`);
|
|
61
|
+
const metadataDir = path_1.default.dirname(outputMetadataPath);
|
|
62
|
+
if (!fs_1.default.existsSync(metadataDir)) {
|
|
63
|
+
fs_1.default.mkdirSync(metadataDir, { recursive: true });
|
|
64
|
+
}
|
|
65
|
+
const metadataGen = new metadata_generator_1.MetadataGenerator(outputMetadataPath);
|
|
66
|
+
metadataGen.generate(models);
|
|
67
|
+
console.log(`✨ Generated metadata in ${outputMetadataPath}`);
|
|
68
|
+
const pythonDir = path_1.default.dirname(outputPythonMetadataPath);
|
|
69
|
+
if (!fs_1.default.existsSync(pythonDir)) {
|
|
70
|
+
fs_1.default.mkdirSync(pythonDir, { recursive: true });
|
|
71
|
+
}
|
|
72
|
+
const pythonGen = new python_generator_1.PythonGenerator(outputPythonMetadataPath);
|
|
73
|
+
pythonGen.generate(models);
|
|
74
|
+
console.log(`✨ Generated Python metadata in ${outputPythonMetadataPath}`);
|
|
75
|
+
const dotnetGen = new dotnet_generator_1.DotnetGenerator(outputDotnetDir);
|
|
76
|
+
dotnetGen.generate(models);
|
|
77
|
+
console.log(`✨ Generated .NET models in ${outputDotnetDir}`);
|
|
78
|
+
console.log('✅ ORM generation completed successfully.');
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
console.error('❌ ORM generation failed:', error);
|
|
82
|
+
process.exit(1);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
main();
|