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