@syntropix/database 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1226 @@
1
+ 'use strict';
2
+
3
+ require('reflect-metadata');
4
+ var axios = require('axios');
5
+ var bson = require('bson');
6
+
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var axios__default = /*#__PURE__*/_interopDefault(axios);
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
13
+
14
+ // src/types/model/filter.ts
15
+ var SortType = {
16
+ Descending: "Descending",
17
+ Ascending: "Ascending"
18
+ };
19
+ var AggregateFunction = /* @__PURE__ */ (function(AggregateFunction2) {
20
+ AggregateFunction2["Count"] = "Count";
21
+ AggregateFunction2["Sum"] = "Sum";
22
+ AggregateFunction2["Avg"] = "Avg";
23
+ AggregateFunction2["Min"] = "Min";
24
+ AggregateFunction2["Max"] = "Max";
25
+ AggregateFunction2["CountDistinct"] = "CountDistinct";
26
+ return AggregateFunction2;
27
+ })({});
28
+ var FilterOperation = /* @__PURE__ */ (function(FilterOperation2) {
29
+ FilterOperation2["LT"] = "LT";
30
+ FilterOperation2["LTE"] = "LTE";
31
+ FilterOperation2["GT"] = "GT";
32
+ FilterOperation2["GTE"] = "GTE";
33
+ FilterOperation2["EQ"] = "EQ";
34
+ FilterOperation2["NEQ"] = "NEQ";
35
+ FilterOperation2["Between"] = "Between";
36
+ FilterOperation2["In"] = "In";
37
+ FilterOperation2["Contains"] = "Contains";
38
+ FilterOperation2["Overlap"] = "Overlap";
39
+ FilterOperation2["NotIn"] = "NotIn";
40
+ FilterOperation2["Like"] = "Like";
41
+ FilterOperation2["NotLike"] = "NotLike";
42
+ FilterOperation2["ILike"] = "ILike";
43
+ FilterOperation2["NotILike"] = "NotILike";
44
+ FilterOperation2["IsNull"] = "IsNull";
45
+ FilterOperation2["IsNotNull"] = "IsNotNull";
46
+ FilterOperation2["Similarity"] = "Similarity";
47
+ FilterOperation2["SimilarityDistance"] = "SimilarityDistance";
48
+ FilterOperation2["WordSimilarity"] = "WordSimilarity";
49
+ FilterOperation2["WordSimilarityDistance"] = "WordSimilarityDistance";
50
+ FilterOperation2["StrictWordSimilarity"] = "StrictWordSimilarity";
51
+ FilterOperation2["StrictWordSimilarityDistance"] = "StrictWordSimilarityDistance";
52
+ FilterOperation2["EuclideanDistance"] = "EuclideanDistance";
53
+ FilterOperation2["NegativeInnerProduct"] = "NegativeInnerProduct";
54
+ FilterOperation2["CosineDistance"] = "CosineDistance";
55
+ return FilterOperation2;
56
+ })({});
57
+
58
+ // src/types/model/foreign-key.ts
59
+ var ForeignKeyAction = {
60
+ Cascade: "Cascade",
61
+ Restrict: "Restrict",
62
+ SetNull: "SetNull",
63
+ NoAction: "NoAction",
64
+ SetDefault: "SetDefault"
65
+ };
66
+
67
+ // src/types/model/shared.ts
68
+ var AccessType = {
69
+ None: "None",
70
+ Read: "Read",
71
+ Write: "Write",
72
+ Admin: "Admin"
73
+ };
74
+ function handleError(error) {
75
+ const axiosErr = error;
76
+ if (axiosErr.response?.data?.status === "error") {
77
+ throw new Error(axiosErr.response.data.message);
78
+ }
79
+ throw new Error(axiosErr.message);
80
+ }
81
+ __name(handleError, "handleError");
82
+ var BaseClient = class {
83
+ static {
84
+ __name(this, "BaseClient");
85
+ }
86
+ config;
87
+ constructor(config) {
88
+ this.config = config;
89
+ }
90
+ headers() {
91
+ return {
92
+ "Content-Type": "application/json",
93
+ Authorization: this.config.apiKey || ""
94
+ };
95
+ }
96
+ url(path) {
97
+ if (path.startsWith("/")) {
98
+ path = path.slice(1);
99
+ }
100
+ return `${this.config.baseUrl}${path}`;
101
+ }
102
+ async get(path, data = {}) {
103
+ try {
104
+ const response = await axios__default.default.get(this.url(path), {
105
+ headers: this.headers(),
106
+ params: data
107
+ });
108
+ const content = bson.EJSON.parse(JSON.stringify(response.data));
109
+ if (content.status !== "success") {
110
+ throw new Error(content.message);
111
+ }
112
+ return content.data;
113
+ } catch (error) {
114
+ if (axios__default.default.isAxiosError(error)) {
115
+ handleError(error);
116
+ }
117
+ console.error(error);
118
+ throw new Error("Failed to get data: Unknown error");
119
+ }
120
+ }
121
+ async post(path, data = {}) {
122
+ try {
123
+ const response = await axios__default.default.post(this.url(path), data, {
124
+ headers: this.headers()
125
+ });
126
+ const content = bson.EJSON.parse(JSON.stringify(response.data));
127
+ if (content.status !== "success") {
128
+ throw new Error(content.message);
129
+ }
130
+ return content.data;
131
+ } catch (error) {
132
+ if (axios__default.default.isAxiosError(error)) {
133
+ handleError(error);
134
+ }
135
+ console.error(error);
136
+ throw new Error("Failed to post data: Unknown error");
137
+ }
138
+ }
139
+ };
140
+
141
+ // src/core/config.ts
142
+ var ClientConfig = class {
143
+ static {
144
+ __name(this, "ClientConfig");
145
+ }
146
+ apiKey;
147
+ baseUrl;
148
+ timeout;
149
+ retries;
150
+ constructor(config) {
151
+ this.apiKey = config?.apiKey || process.env.SYNTROPIX_API_KEY;
152
+ this.baseUrl = config?.baseUrl || process.env.SYNTROPIX_API_URL;
153
+ this.timeout = config?.timeout || process.env.SYNTROPIX_API_TIMEOUT;
154
+ this.retries = config?.retries || process.env.SYNTROPIX_API_RETRIES;
155
+ if (!this.apiKey || !this.baseUrl) {
156
+ throw new Error("API key and base URL are required");
157
+ }
158
+ if (!this.timeout) {
159
+ this.timeout = 1e4;
160
+ }
161
+ if (!this.retries) {
162
+ this.retries = 3;
163
+ }
164
+ if (!this.baseUrl.endsWith("/")) {
165
+ this.baseUrl += "/";
166
+ }
167
+ }
168
+ };
169
+
170
+ // src/core/filter-builder.ts
171
+ var AND = /* @__PURE__ */ __name((...conditions) => conditions, "AND");
172
+ var OR = /* @__PURE__ */ __name((...conditions) => conditions, "OR");
173
+ var EQ = /* @__PURE__ */ __name((field, value) => ({
174
+ columnName: field,
175
+ operator: FilterOperation.EQ,
176
+ staticValue: value
177
+ }), "EQ");
178
+ var NE = /* @__PURE__ */ __name((field, value) => ({
179
+ columnName: field,
180
+ operator: FilterOperation.NEQ,
181
+ staticValue: value
182
+ }), "NE");
183
+ var GT = /* @__PURE__ */ __name((field, value) => ({
184
+ columnName: field,
185
+ operator: FilterOperation.GT,
186
+ staticValue: value
187
+ }), "GT");
188
+ var GTE = /* @__PURE__ */ __name((field, value) => ({
189
+ columnName: field,
190
+ operator: FilterOperation.GTE,
191
+ staticValue: value
192
+ }), "GTE");
193
+ var LT = /* @__PURE__ */ __name((field, value) => ({
194
+ columnName: field,
195
+ operator: FilterOperation.LT,
196
+ staticValue: value
197
+ }), "LT");
198
+ var LTE = /* @__PURE__ */ __name((field, value) => ({
199
+ columnName: field,
200
+ operator: FilterOperation.LTE,
201
+ staticValue: value
202
+ }), "LTE");
203
+ var IN = /* @__PURE__ */ __name((field, values) => ({
204
+ columnName: field,
205
+ operator: FilterOperation.In,
206
+ staticValue: values
207
+ }), "IN");
208
+ var CONTAINS = /* @__PURE__ */ __name((field, value) => ({
209
+ columnName: field,
210
+ operator: FilterOperation.Contains,
211
+ staticValue: value
212
+ }), "CONTAINS");
213
+ var OVERLAP = /* @__PURE__ */ __name((field, value) => ({
214
+ columnName: field,
215
+ operator: FilterOperation.Overlap,
216
+ staticValue: value
217
+ }), "OVERLAP");
218
+ var I_LIKE = /* @__PURE__ */ __name((field, pattern) => ({
219
+ columnName: field,
220
+ operator: FilterOperation.ILike,
221
+ staticValue: pattern
222
+ }), "I_LIKE");
223
+ var NOT_I_LIKE = /* @__PURE__ */ __name((field, pattern) => ({
224
+ columnName: field,
225
+ operator: FilterOperation.NotILike,
226
+ staticValue: pattern
227
+ }), "NOT_I_LIKE");
228
+ var NOT_IN = /* @__PURE__ */ __name((field, values) => ({
229
+ columnName: field,
230
+ operator: FilterOperation.NotIn,
231
+ staticValue: values
232
+ }), "NOT_IN");
233
+ var LIKE = /* @__PURE__ */ __name((field, pattern) => ({
234
+ columnName: field,
235
+ operator: FilterOperation.Like,
236
+ staticValue: pattern
237
+ }), "LIKE");
238
+ var NOT_LIKE = /* @__PURE__ */ __name((field, pattern) => ({
239
+ columnName: field,
240
+ operator: FilterOperation.NotLike,
241
+ staticValue: pattern
242
+ }), "NOT_LIKE");
243
+ var IS_NULL = /* @__PURE__ */ __name((field) => ({
244
+ columnName: field,
245
+ operator: FilterOperation.IsNull
246
+ }), "IS_NULL");
247
+ var IS_NOT_NULL = /* @__PURE__ */ __name((field) => ({
248
+ columnName: field,
249
+ operator: FilterOperation.IsNotNull
250
+ }), "IS_NOT_NULL");
251
+ var BETWEEN = /* @__PURE__ */ __name((field, min, max) => ({
252
+ columnName: field,
253
+ operator: FilterOperation.Between,
254
+ staticValue: [
255
+ min,
256
+ max
257
+ ]
258
+ }), "BETWEEN");
259
+ var EQ_COL = /* @__PURE__ */ __name((field, otherField) => ({
260
+ columnName: field,
261
+ operator: FilterOperation.EQ,
262
+ columnValue: otherField
263
+ }), "EQ_COL");
264
+ var NE_COL = /* @__PURE__ */ __name((field, otherField) => ({
265
+ columnName: field,
266
+ operator: FilterOperation.NEQ,
267
+ columnValue: otherField
268
+ }), "NE_COL");
269
+ var GT_COL = /* @__PURE__ */ __name((field, otherField) => ({
270
+ columnName: field,
271
+ operator: FilterOperation.GT,
272
+ columnValue: otherField
273
+ }), "GT_COL");
274
+ var GTE_COL = /* @__PURE__ */ __name((field, otherField) => ({
275
+ columnName: field,
276
+ operator: FilterOperation.GTE,
277
+ columnValue: otherField
278
+ }), "GTE_COL");
279
+ var LT_COL = /* @__PURE__ */ __name((field, otherField) => ({
280
+ columnName: field,
281
+ operator: FilterOperation.LT,
282
+ columnValue: otherField
283
+ }), "LT_COL");
284
+ var LTE_COL = /* @__PURE__ */ __name((field, otherField) => ({
285
+ columnName: field,
286
+ operator: FilterOperation.LTE,
287
+ columnValue: otherField
288
+ }), "LTE_COL");
289
+ var SIMILARITY = /* @__PURE__ */ __name((field, value, options) => ({
290
+ columnName: field,
291
+ operator: FilterOperation.Similarity,
292
+ staticValue: value,
293
+ simiarityOptions: options
294
+ }), "SIMILARITY");
295
+ var SIMILARITY_DISTANCE = /* @__PURE__ */ __name((field, value, options) => ({
296
+ columnName: field,
297
+ operator: FilterOperation.SimilarityDistance,
298
+ staticValue: value,
299
+ simiarityOptions: options
300
+ }), "SIMILARITY_DISTANCE");
301
+ var WORD_SIMILARITY = /* @__PURE__ */ __name((field, value, options) => ({
302
+ columnName: field,
303
+ operator: FilterOperation.WordSimilarity,
304
+ staticValue: value,
305
+ simiarityOptions: options
306
+ }), "WORD_SIMILARITY");
307
+ var WORD_SIMILARITY_DISTANCE = /* @__PURE__ */ __name((field, value, options) => ({
308
+ columnName: field,
309
+ operator: FilterOperation.WordSimilarityDistance,
310
+ staticValue: value,
311
+ simiarityOptions: options
312
+ }), "WORD_SIMILARITY_DISTANCE");
313
+ var STRICT_WORD_SIMILARITY = /* @__PURE__ */ __name((field, value, options) => ({
314
+ columnName: field,
315
+ operator: FilterOperation.StrictWordSimilarity,
316
+ staticValue: value,
317
+ simiarityOptions: options
318
+ }), "STRICT_WORD_SIMILARITY");
319
+ var STRICT_WORD_SIMILARITY_DISTANCE = /* @__PURE__ */ __name((field, value, options) => ({
320
+ columnName: field,
321
+ operator: FilterOperation.StrictWordSimilarityDistance,
322
+ staticValue: value,
323
+ simiarityOptions: options
324
+ }), "STRICT_WORD_SIMILARITY_DISTANCE");
325
+ var EUCLIDEAN_DISTANCE = /* @__PURE__ */ __name((field, value, options) => ({
326
+ columnName: field,
327
+ operator: FilterOperation.EuclideanDistance,
328
+ staticValue: value,
329
+ simiarityOptions: options
330
+ }), "EUCLIDEAN_DISTANCE");
331
+ var NEGATIVE_INNER_PRODUCT = /* @__PURE__ */ __name((field, value, options) => ({
332
+ columnName: field,
333
+ operator: FilterOperation.NegativeInnerProduct,
334
+ staticValue: value,
335
+ simiarityOptions: options
336
+ }), "NEGATIVE_INNER_PRODUCT");
337
+ var COSINE_DISTANCE = /* @__PURE__ */ __name((field, value, options) => ({
338
+ columnName: field,
339
+ operator: FilterOperation.CosineDistance,
340
+ staticValue: value,
341
+ simiarityOptions: options
342
+ }), "COSINE_DISTANCE");
343
+ var Value = /* @__PURE__ */ __name((value) => value, "Value");
344
+ function FilterWrapper(filter) {
345
+ if (filter === void 0) {
346
+ return void 0;
347
+ }
348
+ if (!Array.isArray(filter)) {
349
+ return OR(AND(filter));
350
+ } else if (!filter.every((item) => Array.isArray(item))) {
351
+ return OR(filter);
352
+ } else {
353
+ return filter;
354
+ }
355
+ }
356
+ __name(FilterWrapper, "FilterWrapper");
357
+
358
+ // src/core/client/data-client.ts
359
+ var DataClient = class {
360
+ static {
361
+ __name(this, "DataClient");
362
+ }
363
+ client;
364
+ constructor(config = new ClientConfig()) {
365
+ this.client = new BaseClient(config);
366
+ }
367
+ async insertData(data) {
368
+ return await this.client.post("/insert", data);
369
+ }
370
+ async insertOne(data) {
371
+ return await this.client.post("/insert/one", data);
372
+ }
373
+ async updateByPrimaryKey(pk, data) {
374
+ return await this.client.post(`/update/${pk}`, data);
375
+ }
376
+ async queryOne(data, model) {
377
+ data.query.filter = FilterWrapper(data.query.filter);
378
+ const response = await this.client.post("/query", {
379
+ One: data
380
+ });
381
+ if (model !== void 0) {
382
+ return new model(response);
383
+ }
384
+ return response;
385
+ }
386
+ async queryMany(data, model) {
387
+ data.query.filter = FilterWrapper(data.query.filter);
388
+ const response = await this.client.post("/query", {
389
+ Many: data
390
+ });
391
+ if (model !== void 0) {
392
+ return response.map((item) => new model(item));
393
+ }
394
+ return response;
395
+ }
396
+ async updateData(data) {
397
+ return await this.client.post("/update", data);
398
+ }
399
+ async deleteData(data) {
400
+ return await this.client.post("/delete", data);
401
+ }
402
+ };
403
+
404
+ // src/core/client/table-client.ts
405
+ var TableClient = class {
406
+ static {
407
+ __name(this, "TableClient");
408
+ }
409
+ client;
410
+ constructor(config = new ClientConfig()) {
411
+ this.client = new BaseClient(config);
412
+ }
413
+ async createTable(data) {
414
+ return await this.client.post("/table/create", data);
415
+ }
416
+ async dropTable(data) {
417
+ return await this.client.post("/table/drop", data);
418
+ }
419
+ async renameTable(data) {
420
+ return await this.client.post("/table/rename", data);
421
+ }
422
+ async truncateTable(data) {
423
+ return await this.client.post("/table/truncate", data);
424
+ }
425
+ async addColumn(data) {
426
+ return await this.client.post("/table/column/add", data);
427
+ }
428
+ async dropColumn(data) {
429
+ return await this.client.post("/table/column/drop", data);
430
+ }
431
+ async modifyColumn(data) {
432
+ return await this.client.post("/table/column/modify", data);
433
+ }
434
+ async getTableSchema(data) {
435
+ return await this.client.get("/table/schema", data);
436
+ }
437
+ async getTableList(data) {
438
+ return await this.client.get("/table/list", data);
439
+ }
440
+ };
441
+
442
+ // src/core/client/syntropix-client.ts
443
+ var SyntropixClient = class {
444
+ static {
445
+ __name(this, "SyntropixClient");
446
+ }
447
+ config;
448
+ _tableClient;
449
+ _dataClient;
450
+ constructor(config = new ClientConfig()) {
451
+ this.config = config;
452
+ }
453
+ get table() {
454
+ if (!this._tableClient) {
455
+ this._tableClient = new TableClient(this.config);
456
+ }
457
+ return this._tableClient;
458
+ }
459
+ get data() {
460
+ if (!this._dataClient) {
461
+ this._dataClient = new DataClient(this.config);
462
+ }
463
+ return this._dataClient;
464
+ }
465
+ };
466
+
467
+ // src/core/data-type.ts
468
+ var ArrayDataType = {
469
+ String: /* @__PURE__ */ __name((maxLength) => ({
470
+ String: maxLength
471
+ }), "String"),
472
+ Decimal: /* @__PURE__ */ __name((precision, scale) => ({
473
+ Decimal: precision && scale ? [
474
+ precision,
475
+ scale
476
+ ] : null
477
+ }), "Decimal"),
478
+ Text: "Text",
479
+ Integer: "Integer",
480
+ BigInteger: "BigInteger",
481
+ Double: "Double",
482
+ DateTime: "DateTime",
483
+ Timestamp: "Timestamp",
484
+ Date: "Date",
485
+ Boolean: "Boolean",
486
+ Money: /* @__PURE__ */ __name((precision, scale) => ({
487
+ Money: precision && scale ? [
488
+ precision,
489
+ scale
490
+ ] : null
491
+ }), "Money"),
492
+ Uuid: "Uuid",
493
+ Enum: /* @__PURE__ */ __name((name, variants) => ({
494
+ Enum: {
495
+ name,
496
+ variants
497
+ }
498
+ }), "Enum"),
499
+ Json: "Json"
500
+ };
501
+ var ColumnDataType = {
502
+ Integer: "Integer",
503
+ String: /* @__PURE__ */ __name((maxLength) => ({
504
+ String: maxLength
505
+ }), "String"),
506
+ Text: "Text",
507
+ Boolean: "Boolean",
508
+ DateTime: "DateTime",
509
+ Timestamp: "Timestamp",
510
+ Date: "Date",
511
+ Json: "Json",
512
+ Uuid: "Uuid",
513
+ Double: "Double",
514
+ Vector: /* @__PURE__ */ __name((dimensions) => ({
515
+ Vector: dimensions
516
+ }), "Vector"),
517
+ Array: /* @__PURE__ */ __name((dataType) => ({
518
+ Array: dataType
519
+ }), "Array"),
520
+ Enum: /* @__PURE__ */ __name((name, variants) => ({
521
+ Enum: {
522
+ name,
523
+ variants
524
+ }
525
+ }), "Enum"),
526
+ Money: /* @__PURE__ */ __name((precision, scale) => ({
527
+ Money: precision && scale ? [
528
+ precision,
529
+ scale
530
+ ] : null
531
+ }), "Money"),
532
+ Decimal: /* @__PURE__ */ __name((precision, scale) => ({
533
+ Decimal: precision && scale ? [
534
+ precision,
535
+ scale
536
+ ] : null
537
+ }), "Decimal")
538
+ };
539
+
540
+ // src/core/field.ts
541
+ var Field = class {
542
+ static {
543
+ __name(this, "Field");
544
+ }
545
+ name = "";
546
+ displayName = "";
547
+ description = "";
548
+ columnType;
549
+ isPrimaryKey = false;
550
+ isNullable = false;
551
+ autoIncrement = false;
552
+ default;
553
+ defaultAccess;
554
+ constructor(columnType, options = {}) {
555
+ this.columnType = columnType;
556
+ this.name = options.name?.toLowerCase() || "";
557
+ this.displayName = options.displayName || "";
558
+ this.description = options.description || "";
559
+ this.isPrimaryKey = options.isPrimaryKey || false;
560
+ this.isNullable = options.isNullable || false;
561
+ this.autoIncrement = options.autoIncrement || false;
562
+ this.default = options.default;
563
+ this.defaultAccess = options.defaultAccess;
564
+ }
565
+ intoColumnCreateDto() {
566
+ return {
567
+ name: this.name,
568
+ displayName: this.displayName,
569
+ columnType: this.columnType,
570
+ description: this.description,
571
+ isPrimaryKey: this.isPrimaryKey,
572
+ isNullable: this.isNullable,
573
+ autoIncrement: this.autoIncrement,
574
+ default: this.default,
575
+ defaultAccess: this.defaultAccess
576
+ };
577
+ }
578
+ };
579
+ var ForeignKeyField = class extends Field {
580
+ static {
581
+ __name(this, "ForeignKeyField");
582
+ }
583
+ tableName;
584
+ columnName;
585
+ onDelete;
586
+ onUpdate;
587
+ constructor(columnType, tableName, columnName, options = {}) {
588
+ super(columnType, options);
589
+ this.tableName = tableName;
590
+ this.columnName = columnName;
591
+ this.onDelete = options.onDelete || ForeignKeyAction.Cascade;
592
+ this.onUpdate = options.onUpdate || ForeignKeyAction.Cascade;
593
+ }
594
+ };
595
+ var StringField = class extends Field {
596
+ static {
597
+ __name(this, "StringField");
598
+ }
599
+ constructor(maxLength, options = {}) {
600
+ super(ColumnDataType.String(maxLength), options);
601
+ }
602
+ };
603
+ var TextField = class extends Field {
604
+ static {
605
+ __name(this, "TextField");
606
+ }
607
+ constructor(options = {}) {
608
+ super(ColumnDataType.Text, options);
609
+ }
610
+ };
611
+ var IntegerField = class extends Field {
612
+ static {
613
+ __name(this, "IntegerField");
614
+ }
615
+ constructor(options = {}) {
616
+ super(ColumnDataType.Integer, options);
617
+ }
618
+ };
619
+ var BooleanField = class extends Field {
620
+ static {
621
+ __name(this, "BooleanField");
622
+ }
623
+ constructor(options = {}) {
624
+ super(ColumnDataType.Boolean, options);
625
+ }
626
+ };
627
+ var DateTimeField = class extends Field {
628
+ static {
629
+ __name(this, "DateTimeField");
630
+ }
631
+ constructor(options = {}) {
632
+ super(ColumnDataType.DateTime, options);
633
+ }
634
+ };
635
+ var TimestampField = class extends Field {
636
+ static {
637
+ __name(this, "TimestampField");
638
+ }
639
+ constructor(options = {}) {
640
+ super(ColumnDataType.Timestamp, options);
641
+ }
642
+ };
643
+ var DateField = class extends Field {
644
+ static {
645
+ __name(this, "DateField");
646
+ }
647
+ constructor(options = {}) {
648
+ super(ColumnDataType.Date, options);
649
+ }
650
+ };
651
+ var JsonField = class extends Field {
652
+ static {
653
+ __name(this, "JsonField");
654
+ }
655
+ constructor(options = {}) {
656
+ super(ColumnDataType.Json, options);
657
+ }
658
+ };
659
+ var UuidField = class extends Field {
660
+ static {
661
+ __name(this, "UuidField");
662
+ }
663
+ constructor(options = {}) {
664
+ super(ColumnDataType.Uuid, options);
665
+ }
666
+ };
667
+ var VectorField = class extends Field {
668
+ static {
669
+ __name(this, "VectorField");
670
+ }
671
+ constructor(dimensions, options = {}) {
672
+ super(ColumnDataType.Vector(dimensions), options);
673
+ }
674
+ };
675
+ var ArrayField = class extends Field {
676
+ static {
677
+ __name(this, "ArrayField");
678
+ }
679
+ constructor(dataType, options = {}) {
680
+ super(ColumnDataType.Array(dataType), options);
681
+ }
682
+ };
683
+ var EnumField = class extends Field {
684
+ static {
685
+ __name(this, "EnumField");
686
+ }
687
+ constructor(name, variants, options = {}) {
688
+ super(ColumnDataType.Enum(name, variants), options);
689
+ }
690
+ };
691
+ var MoneyField = class extends Field {
692
+ static {
693
+ __name(this, "MoneyField");
694
+ }
695
+ constructor(precision, scale, options = {}) {
696
+ super(ColumnDataType.Money(precision, scale), options);
697
+ }
698
+ };
699
+ var DecimalField = class extends Field {
700
+ static {
701
+ __name(this, "DecimalField");
702
+ }
703
+ constructor(precision, scale, options = {}) {
704
+ super(ColumnDataType.Decimal(precision, scale), options);
705
+ }
706
+ };
707
+ var DoubleField = class extends Field {
708
+ static {
709
+ __name(this, "DoubleField");
710
+ }
711
+ constructor(options = {}) {
712
+ super(ColumnDataType.Double, options);
713
+ }
714
+ };
715
+
716
+ // src/core/base-model.ts
717
+ var FIELDS_KEY = Symbol("fields");
718
+ var TABLE_NAME_KEY = Symbol("tableName");
719
+ var TABLE_DISPLAY_NAME_KEY = Symbol("displayTableName");
720
+ var DESCRIPTION_KEY = Symbol("description");
721
+ var INDEXES_KEY = Symbol("indexes");
722
+ function Column(options = {}) {
723
+ return function(target, propertyKey) {
724
+ const fields = Reflect.getMetadata(FIELDS_KEY, target.constructor) || {};
725
+ const fieldName = options.name || propertyKey.toLowerCase();
726
+ const columnType = options.type || ColumnDataType.Text;
727
+ const field = new class extends Field {
728
+ constructor() {
729
+ super(columnType, {
730
+ name: fieldName,
731
+ displayName: options.displayName,
732
+ description: options.description,
733
+ isPrimaryKey: options.primary,
734
+ isNullable: options.nullable,
735
+ autoIncrement: options.autoIncrement,
736
+ default: options.default,
737
+ defaultAccess: options.defaultAccess
738
+ });
739
+ }
740
+ }();
741
+ fields[propertyKey] = field;
742
+ Reflect.defineMetadata(FIELDS_KEY, fields, target.constructor);
743
+ };
744
+ }
745
+ __name(Column, "Column");
746
+ function Description(description) {
747
+ return function(target) {
748
+ Reflect.defineMetadata(DESCRIPTION_KEY, description, target);
749
+ };
750
+ }
751
+ __name(Description, "Description");
752
+ function ForeignKey(tableName, columnName, options = {}) {
753
+ return function(target, propertyKey) {
754
+ const fields = Reflect.getMetadata(FIELDS_KEY, target.constructor) || {};
755
+ const field = new ForeignKeyField(options.type || ColumnDataType.Integer, tableName, columnName, {
756
+ displayName: options.displayName,
757
+ description: options.description,
758
+ isNullable: options.nullable,
759
+ default: options.default,
760
+ onDelete: options.onDelete,
761
+ onUpdate: options.onUpdate
762
+ });
763
+ field.name = options.name || propertyKey.toLowerCase();
764
+ fields[propertyKey] = field;
765
+ Reflect.defineMetadata(FIELDS_KEY, fields, target.constructor);
766
+ };
767
+ }
768
+ __name(ForeignKey, "ForeignKey");
769
+ var BaseModel = class {
770
+ static {
771
+ __name(this, "BaseModel");
772
+ }
773
+ _client;
774
+ _extra = {};
775
+ constructor(data = {}) {
776
+ const fields = this.getFields();
777
+ const columnToPropertyMap = {};
778
+ for (const [propertyName, field] of Object.entries(fields)) {
779
+ columnToPropertyMap[field.name] = propertyName;
780
+ }
781
+ for (const [key, value] of Object.entries(data)) {
782
+ if (key in fields) {
783
+ this[key] = value;
784
+ } else if (key in columnToPropertyMap) {
785
+ this[columnToPropertyMap[key]] = value;
786
+ } else {
787
+ this._extra[key] = value;
788
+ }
789
+ }
790
+ }
791
+ // Static metadata getters
792
+ static getTableName() {
793
+ const tableName = Reflect.getMetadata(TABLE_NAME_KEY, this);
794
+ if (tableName) return tableName;
795
+ if ("tableName" in this && typeof this.tableName === "string") {
796
+ return this.tableName;
797
+ }
798
+ return this.name.toLowerCase();
799
+ }
800
+ static getDisplayName() {
801
+ const displayName = Reflect.getMetadata(TABLE_DISPLAY_NAME_KEY, this);
802
+ if (displayName) return displayName;
803
+ if ("displayName" in this && typeof this.displayName === "string") {
804
+ return this.displayName;
805
+ }
806
+ return this.name;
807
+ }
808
+ static getDescription() {
809
+ const metadataDescription = Reflect.getMetadata(DESCRIPTION_KEY, this);
810
+ if (metadataDescription) return metadataDescription;
811
+ if ("description" in this && typeof this.description === "string") {
812
+ return this.description;
813
+ }
814
+ return "";
815
+ }
816
+ static getIndexes() {
817
+ return Reflect.getMetadata(INDEXES_KEY, this) || [];
818
+ }
819
+ static getFields() {
820
+ const fields = Reflect.getMetadata(FIELDS_KEY, this) || {};
821
+ let hasPrimaryKey = false;
822
+ for (const field of Object.values(fields)) {
823
+ if (field.isPrimaryKey) {
824
+ hasPrimaryKey = true;
825
+ field.isNullable = false;
826
+ break;
827
+ }
828
+ }
829
+ if (!hasPrimaryKey && !("id" in fields)) {
830
+ fields["id"] = new IntegerField({
831
+ isPrimaryKey: true,
832
+ isNullable: false,
833
+ autoIncrement: true,
834
+ description: "Primary key"
835
+ });
836
+ fields["id"].name = "id";
837
+ }
838
+ return fields;
839
+ }
840
+ static getPrimaryKeyName() {
841
+ const fields = this.getFields();
842
+ for (const [key, field] of Object.entries(fields)) {
843
+ if (field.isPrimaryKey) {
844
+ return field.name;
845
+ }
846
+ }
847
+ return "id";
848
+ }
849
+ static getAssociations() {
850
+ const fields = this.getFields();
851
+ return Object.values(fields).filter((f) => f instanceof ForeignKeyField);
852
+ }
853
+ // Instance metadata getters
854
+ getFields() {
855
+ return this.constructor.getFields();
856
+ }
857
+ getTableName() {
858
+ return this.constructor.getTableName();
859
+ }
860
+ getDisplayName() {
861
+ return this.constructor.getDisplayName();
862
+ }
863
+ getPrimaryKeyName() {
864
+ return this.constructor.getPrimaryKeyName();
865
+ }
866
+ getPrimaryKey() {
867
+ const fields = this.getFields();
868
+ for (const field of Object.values(fields)) {
869
+ if (field.isPrimaryKey) {
870
+ return field;
871
+ }
872
+ }
873
+ return void 0;
874
+ }
875
+ // Client getter
876
+ get client() {
877
+ if (!this._client) {
878
+ this._client = new SyntropixClient();
879
+ }
880
+ return this._client;
881
+ }
882
+ // Table operations
883
+ static async createTable(client = new SyntropixClient()) {
884
+ const fields = this.getFields();
885
+ const columns = Object.values(fields).map((f) => f.intoColumnCreateDto());
886
+ const foreignKeys = this.getAssociations().map((f) => ({
887
+ fromTableName: this.getTableName(),
888
+ fromColumnName: f.name,
889
+ toTableName: f.tableName,
890
+ toColumnName: f.columnName,
891
+ onDelete: f.onDelete,
892
+ onUpdate: f.onUpdate
893
+ }));
894
+ const indexes = this.getIndexes();
895
+ return await client.table.createTable({
896
+ name: this.getTableName(),
897
+ displayName: this.getDisplayName(),
898
+ description: this.getDescription() || "No description",
899
+ columns,
900
+ foreignKeys,
901
+ indexes
902
+ });
903
+ }
904
+ static async dropTable(client = new SyntropixClient()) {
905
+ return await client.table.dropTable({
906
+ tableName: this.getTableName()
907
+ });
908
+ }
909
+ static async renameTable(newName, client = new SyntropixClient()) {
910
+ return await client.table.renameTable({
911
+ tableName: this.getTableName(),
912
+ newTableName: newName
913
+ });
914
+ }
915
+ static async truncateTable(client = new SyntropixClient()) {
916
+ return await client.table.truncateTable({
917
+ tableName: this.getTableName()
918
+ });
919
+ }
920
+ static async getTableSchema(client = new SyntropixClient()) {
921
+ return await client.table.getTableSchema({
922
+ tableName: this.getTableName()
923
+ });
924
+ }
925
+ // Data operations
926
+ static async create(data, client = new SyntropixClient()) {
927
+ const model = this;
928
+ const fields = model.getFields();
929
+ const columns = [];
930
+ const values = [];
931
+ for (const [key, value] of Object.entries(data)) {
932
+ if (key in fields) {
933
+ columns.push(fields[key].name);
934
+ values.push(value);
935
+ } else {
936
+ throw new Error(`Invalid field: ${key}`);
937
+ }
938
+ }
939
+ return client.data.insertOne({
940
+ tableName: model.getTableName(),
941
+ data: {
942
+ columns,
943
+ values: [
944
+ values
945
+ ]
946
+ }
947
+ });
948
+ }
949
+ async save(client = new SyntropixClient()) {
950
+ const pk = this.getPrimaryKey();
951
+ const pkValue = this[this.getPrimaryKeyName()];
952
+ const fields = this.getFields();
953
+ if (pkValue === null || pkValue === void 0) {
954
+ const data = {};
955
+ for (const [key, field] of Object.entries(fields)) {
956
+ data[key] = this[key];
957
+ }
958
+ return this.constructor.create(data, client);
959
+ }
960
+ const columns = [];
961
+ const values = [];
962
+ for (const [key, field] of Object.entries(fields)) {
963
+ if (field.name !== pk?.name) {
964
+ columns.push(field.name);
965
+ values.push(this[key]);
966
+ }
967
+ }
968
+ return client || this.client.data.updateByPrimaryKey(pkValue, {
969
+ tableName: this.getTableName(),
970
+ payload: {
971
+ filter: [
972
+ []
973
+ ],
974
+ columns,
975
+ values
976
+ }
977
+ });
978
+ }
979
+ async remove(filter, _client) {
980
+ const pk = this.getPrimaryKey();
981
+ const pkValue = this[this.getPrimaryKeyName()];
982
+ const finalFilter = filter || OR(AND(EQ(pk?.name || "id", pkValue)));
983
+ return _client || this.client.data.deleteData({
984
+ tableName: this.getTableName(),
985
+ payload: {
986
+ filter: finalFilter
987
+ }
988
+ });
989
+ }
990
+ static async bulkCreate(datas, batchSize = 32, _client) {
991
+ if (!datas.length) return 0;
992
+ if (batchSize <= 0) throw new Error("Batch size must be greater than 0");
993
+ const model = this;
994
+ const fields = model.getFields();
995
+ let cnt = 0;
996
+ batchSize = Math.min(batchSize, 128);
997
+ const columns = Object.keys(datas[0]);
998
+ const columnsSet = new Set(columns);
999
+ for (const col of columns) {
1000
+ if (!(col in fields)) {
1001
+ throw new Error(`Invalid field: ${col}`);
1002
+ }
1003
+ }
1004
+ let values = [];
1005
+ const client = _client || new SyntropixClient();
1006
+ for (const data of datas) {
1007
+ if (columnsSet.size !== new Set(Object.keys(data)).size || !columns.every((c) => c in data)) {
1008
+ throw new Error("All data must have the same columns");
1009
+ }
1010
+ values.push(columns.map((c) => data[c]));
1011
+ if (values.length === batchSize) {
1012
+ cnt += await client.data.insertData({
1013
+ tableName: model.getTableName(),
1014
+ data: {
1015
+ columns: columns.map((c) => fields[c].name),
1016
+ values
1017
+ }
1018
+ });
1019
+ values = [];
1020
+ }
1021
+ }
1022
+ if (values.length > 0) {
1023
+ cnt += await client.data.insertData({
1024
+ tableName: model.getTableName(),
1025
+ data: {
1026
+ columns: columns.map((c) => fields[c].name),
1027
+ values
1028
+ }
1029
+ });
1030
+ }
1031
+ return cnt;
1032
+ }
1033
+ static async update(filter, data, _client) {
1034
+ const model = this;
1035
+ const fields = model.getFields();
1036
+ const columns = Object.keys(data);
1037
+ if (!columns.length) {
1038
+ throw new Error("No columns to update");
1039
+ }
1040
+ for (const col of columns) {
1041
+ if (!(col in fields)) {
1042
+ throw new Error(`Invalid field: ${col}`);
1043
+ }
1044
+ }
1045
+ const values = columns.map((c) => data[c]);
1046
+ const client = _client || new SyntropixClient();
1047
+ return client.data.updateData({
1048
+ tableName: model.getTableName(),
1049
+ payload: {
1050
+ filter,
1051
+ columns: columns.map((c) => fields[c].name),
1052
+ values
1053
+ }
1054
+ });
1055
+ }
1056
+ static async delete(filter, _client) {
1057
+ const model = this;
1058
+ const client = _client || new SyntropixClient();
1059
+ return client.data.deleteData({
1060
+ tableName: model.getTableName(),
1061
+ payload: {
1062
+ filter
1063
+ }
1064
+ });
1065
+ }
1066
+ static async get(filter, select, _client) {
1067
+ const model = this;
1068
+ const fields = model.getFields();
1069
+ const client = _client || new SyntropixClient();
1070
+ const data = await client.data.queryOne({
1071
+ tableName: model.getTableName(),
1072
+ query: {
1073
+ filter,
1074
+ select: select || Object.values(fields).map((f) => f.name),
1075
+ limit: 1
1076
+ }
1077
+ });
1078
+ return new this(data);
1079
+ }
1080
+ static async filter(options) {
1081
+ const model = this;
1082
+ const client = options._client || new SyntropixClient();
1083
+ const data = await client.data.queryMany({
1084
+ tableName: model.getTableName(),
1085
+ query: {
1086
+ filter: options.filter,
1087
+ sort: options.sort,
1088
+ aggregate: options.aggregate,
1089
+ join: options.join ? [
1090
+ options.join
1091
+ ] : void 0,
1092
+ limit: options.limit,
1093
+ offset: options.offset,
1094
+ groupBy: options.groupBy,
1095
+ select: options.select
1096
+ }
1097
+ });
1098
+ return data.map((item) => new this(item));
1099
+ }
1100
+ static async count(options = {}) {
1101
+ const model = this;
1102
+ const client = options._client || new SyntropixClient();
1103
+ const data = await client.data.queryMany({
1104
+ tableName: model.getTableName(),
1105
+ query: {
1106
+ filter: options.filter || [
1107
+ [
1108
+ GTE("id", Value(0))
1109
+ ]
1110
+ ],
1111
+ aggregate: [
1112
+ {
1113
+ column: "id",
1114
+ function: AggregateFunction.Count,
1115
+ alias: "count"
1116
+ }
1117
+ ],
1118
+ join: options.join ? [
1119
+ options.join
1120
+ ] : void 0,
1121
+ limit: 1,
1122
+ offset: 0,
1123
+ groupBy: options.groupBy,
1124
+ select: [
1125
+ "count"
1126
+ ]
1127
+ }
1128
+ });
1129
+ return data.length > 0 ? data[0].count : 0;
1130
+ }
1131
+ toString() {
1132
+ const fields = this.getFields();
1133
+ const data = {};
1134
+ for (const key of Object.keys(fields)) {
1135
+ const value = this[key];
1136
+ if (!(value instanceof Field)) {
1137
+ data[key] = value;
1138
+ }
1139
+ }
1140
+ data._extra = this._extra;
1141
+ return `${this.constructor.name}(${JSON.stringify(data).slice(1, -1)})`;
1142
+ }
1143
+ toJSON() {
1144
+ const fields = this.getFields();
1145
+ const data = {};
1146
+ for (const key of Object.keys(fields)) {
1147
+ data[key] = this[key];
1148
+ }
1149
+ return {
1150
+ ...data,
1151
+ ...this._extra
1152
+ };
1153
+ }
1154
+ };
1155
+
1156
+ exports.AND = AND;
1157
+ exports.AccessType = AccessType;
1158
+ exports.AggregateFunction = AggregateFunction;
1159
+ exports.ArrayDataType = ArrayDataType;
1160
+ exports.ArrayField = ArrayField;
1161
+ exports.BETWEEN = BETWEEN;
1162
+ exports.BaseClient = BaseClient;
1163
+ exports.BaseModel = BaseModel;
1164
+ exports.BooleanField = BooleanField;
1165
+ exports.CONTAINS = CONTAINS;
1166
+ exports.COSINE_DISTANCE = COSINE_DISTANCE;
1167
+ exports.ClientConfig = ClientConfig;
1168
+ exports.Column = Column;
1169
+ exports.ColumnDataType = ColumnDataType;
1170
+ exports.DataClient = DataClient;
1171
+ exports.DateField = DateField;
1172
+ exports.DateTimeField = DateTimeField;
1173
+ exports.DecimalField = DecimalField;
1174
+ exports.Description = Description;
1175
+ exports.DoubleField = DoubleField;
1176
+ exports.EQ = EQ;
1177
+ exports.EQ_COL = EQ_COL;
1178
+ exports.EUCLIDEAN_DISTANCE = EUCLIDEAN_DISTANCE;
1179
+ exports.EnumField = EnumField;
1180
+ exports.Field = Field;
1181
+ exports.FilterOperation = FilterOperation;
1182
+ exports.FilterWrapper = FilterWrapper;
1183
+ exports.ForeignKey = ForeignKey;
1184
+ exports.ForeignKeyAction = ForeignKeyAction;
1185
+ exports.ForeignKeyField = ForeignKeyField;
1186
+ exports.GT = GT;
1187
+ exports.GTE = GTE;
1188
+ exports.GTE_COL = GTE_COL;
1189
+ exports.GT_COL = GT_COL;
1190
+ exports.IN = IN;
1191
+ exports.IS_NOT_NULL = IS_NOT_NULL;
1192
+ exports.IS_NULL = IS_NULL;
1193
+ exports.I_LIKE = I_LIKE;
1194
+ exports.IntegerField = IntegerField;
1195
+ exports.JsonField = JsonField;
1196
+ exports.LIKE = LIKE;
1197
+ exports.LT = LT;
1198
+ exports.LTE = LTE;
1199
+ exports.LTE_COL = LTE_COL;
1200
+ exports.LT_COL = LT_COL;
1201
+ exports.MoneyField = MoneyField;
1202
+ exports.NE = NE;
1203
+ exports.NEGATIVE_INNER_PRODUCT = NEGATIVE_INNER_PRODUCT;
1204
+ exports.NE_COL = NE_COL;
1205
+ exports.NOT_IN = NOT_IN;
1206
+ exports.NOT_I_LIKE = NOT_I_LIKE;
1207
+ exports.NOT_LIKE = NOT_LIKE;
1208
+ exports.OR = OR;
1209
+ exports.OVERLAP = OVERLAP;
1210
+ exports.SIMILARITY = SIMILARITY;
1211
+ exports.SIMILARITY_DISTANCE = SIMILARITY_DISTANCE;
1212
+ exports.STRICT_WORD_SIMILARITY = STRICT_WORD_SIMILARITY;
1213
+ exports.STRICT_WORD_SIMILARITY_DISTANCE = STRICT_WORD_SIMILARITY_DISTANCE;
1214
+ exports.SortType = SortType;
1215
+ exports.StringField = StringField;
1216
+ exports.SyntropixClient = SyntropixClient;
1217
+ exports.TableClient = TableClient;
1218
+ exports.TextField = TextField;
1219
+ exports.TimestampField = TimestampField;
1220
+ exports.UuidField = UuidField;
1221
+ exports.Value = Value;
1222
+ exports.VectorField = VectorField;
1223
+ exports.WORD_SIMILARITY = WORD_SIMILARITY;
1224
+ exports.WORD_SIMILARITY_DISTANCE = WORD_SIMILARITY_DISTANCE;
1225
+ //# sourceMappingURL=index.cjs.map
1226
+ //# sourceMappingURL=index.cjs.map