-
Notifications
You must be signed in to change notification settings - Fork 264
/
table.ts
3494 lines (3275 loc) · 109 KB
/
table.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Table Database Access Layer
* @category saltcorn-data
* @module models/table
* @subcategory models
*/
import db from "../db";
import {
sqlsanitize,
mkWhere,
mkSelectOptions,
orderByIsObject,
orderByIsOperator,
} from "@saltcorn/db-common/internal";
import type {
Where,
SelectOptions,
Row,
JoinFields,
JoinOptions,
AggregationOptions,
} from "@saltcorn/db-common/internal";
import Field from "./field";
import type {
AbstractTable,
TableCfg,
TablePack,
} from "@saltcorn/types/model-abstracts/abstract_table";
import type {
ForUserRequest,
AbstractUser,
} from "@saltcorn/types/model-abstracts/abstract_user";
import type { ResultMessage, Type } from "@saltcorn/types/common_types";
import {
instanceOfErrorMsg,
instanceOfType,
} from "@saltcorn/types/common_types";
import Trigger from "./trigger";
import expression from "./expression";
const {
apply_calculated_fields,
apply_calculated_fields_stored,
recalculate_for_stored,
get_expression_function,
eval_expression,
freeVariables,
add_free_variables_to_joinfields,
removeComments,
} = expression;
import type TableConstraint from "./table_constraints";
import csvtojson from "csvtojson";
import moment from "moment";
import { createReadStream } from "fs";
import { stat, readFile } from "fs/promises";
//import { num_between } from "@saltcorn/types/generators";
//import { devNull } from "os";
import utils from "../utils";
const {
prefixFieldsInWhere,
InvalidConfiguration,
InvalidAdminAction,
satisfies,
structuredClone,
getLines,
mergeIntoWhere,
stringToJSON,
isNode,
apply,
applyAsync,
asyncMap,
} = utils;
import tags from "@saltcorn/markup/tags";
const { text } = tags;
import type { AbstractTag } from "@saltcorn/types/model-abstracts/abstract_tag";
import type {
JoinFieldOption,
RelationOption,
} from "@saltcorn/types/base_types";
import { get_formula_examples } from "./internal/table_helper";
import { getAggAndField, process_aggregations } from "./internal/query";
/**
* Transponce Objects
* TODO more detailed explanation
* TODO refactor - move to object util module?
* @param objs
* @returns {object}
*/
const transposeObjects = (objs: any[]): any => {
const keys = new Set<string>();
for (const o of objs) {
Object.keys(o).forEach((k) => keys.add(k));
}
const res: any = {};
keys.forEach((k: string) => {
res[k] = [];
});
for (const o of objs) {
keys.forEach((k: string) => {
res[k].push(o[k]);
});
}
return res;
};
// todo support also other date formats https://momentjs.com/docs/
const dateFormats = [moment.ISO_8601];
// todo refactor - move to separated data utils module?
/**
* Is Valid Date of format moment.ISO_8601,
* example 2010-01-01T05:06:07
*
* @param date
* @returns {boolean}
*/
const isDate = function (date: Date): boolean {
return moment(date, dateFormats, true).isValid();
};
/**
* A class representing database tables and their properties.
*
* Use this to create or delete tables and their properties, or to query
* or change table rows.
*
* To query, update, insert or delete rows in an existing table, first you
* should find the table object with {@link Table.findOne}.
*
* @example
* ```
* Table.findOne({name: "Customers"}) // find the table with name "Customers"
* Table.findOne("Customers") // find the table with name "Customers" (shortcut)
* Table.findOne({ id: 5 }) // find the table with id=5
* Table.findOne(5) // find the table with id=5 (shortcut)
* ```
*
* Table.findOne is synchronous (no need to await), But the functions that
* query and manipulate (such as {@link Table.insertRow}, {@link Table.getRows},
* {@link Table.updateRow}, {@link Table.deleteRows}) rows are mostly asyncronous,
* so you can put the await in front of the
* whole expression
*
* @example
* To count the number of rows in the customer table
* ```
* const nrows = await Table.findOne("Customers").countRows()
* ```
*
* For further examples, see the [Table test suite](https://github.com/saltcorn/saltcorn/blob/master/packages/saltcorn-data/tests/table.test.ts)
*
* ## Querying table rows
*
* There are several methods you can use to retrieve rows in the database:
*
* * {@link Table.countRows} To count the number of rows, optionally matching a criterion
* * {@link Table.getRows} To retrieve multiple rows matching a criterion
* * {@link Table.getRow} To retrieve a single row matching a criterion
* * {@link Table.getJoinedRows} To retrieve rows together with joinfields and aggregations
*
* These functions all take `Where` expressions which are JavaScript objects describing
* the criterion to match to. Some examples:
*
* * `{}`: Match all rows
* * `{ name: "Jim" }`: Match all rows with name="Jim"
* * `{ name: { ilike: "im"} }`: Match all rows where name contains "im" (case insensitive)
* * `{ name: /im/ }`: Match all rows with name matching regular expression "im"
* * `{ age: { lt: 18 } }`: Match all rows with age<18
* * `{ age: { lt: 18, equal: true } }`: Match all rows with age<=18
* * `{ age: { gt: 18, lt: 65} }`: Match all rows with 18<age<65
* * `{ name: { or: ["Harry", "Sally"] } }`: Match all rows with name="Harry" or "Sally"
* * `{ or: [{ name: "Joe"}, { age: 37 }] }`: Match all rows with name="Joe" or age=37
* * `{ not: { id: 5 } }`: All rows except id=5
* * `{ id: { in: [1, 2, 3] } }`: Rows with id 1, 2, or 3
* * `{ id: { not: { in: [1, 2, 3] } } }`: Rows with id any value except 1, 2, or 3
*
* For further examples, see the [mkWhere test suite](https://github.com/saltcorn/saltcorn/blob/master/packages/db-common/internal.test.js)
*
* ## Updating a Row
*
* There are two nearly identical functions for updating rows depending on how you want
* failures treated
*
* * {@link Table.updateRow} Update a row, throws an exception if update is invalid
* * {@link Table.tryUpdateRow} Update a row, return an error message if update is invalid
*
* ## Inserting a new Row
*
* There are two nearly identical functions for inserting a new row depending on how you want
* failures treated
*
* * {@link Table.insertRow} insert a row, throws an exception if it is invalid
* * {@link Table.tryInsertRow} insert a row, return an error message if it is invalid
*
* ## Deleting rows
*
* Use {@link Table.deleteRows} to delete any number (zero, one or many) of rows matching a criterion. It uses
* the same `where` expression as the functions for querying rows
*
*
* @category saltcorn-data
*/
class Table implements AbstractTable {
/** The table name */
name: string;
/** The table ID */
id?: number;
/** Minimum role to read */
min_role_read: number;
/** Minimum role to write */
min_role_write: number;
/** The ID of the ownership field*/
ownership_field_id?: string;
/** A formula to denote ownership. This is a JavaScript expression which
* must evaluate to true if the user is the owner*/
ownership_formula?: string;
/** Version history enabled for this table */
versioned: boolean;
/** Whether sync info for mobile apps is enabled for this table */
has_sync_info: boolean;
/** If true this is an external table (not a database table) */
external: boolean;
/** A description of the purpose of the table */
description?: string;
/** An array of {@link Field}s in this table */
fields: Field[];
/** An array of {@link TableConstraint}s for this table */
constraints: TableConstraint[];
/** Is this a user group? If yes it will appear as options in the ownership dropdown */
is_user_group: boolean;
/** Name of the table provider for this table (not a database table) */
provider_name?: string;
/** Configuration for the table provider for this table */
provider_cfg?: any;
/**
* Table constructor
* @param {object} o
*/
constructor(o: TableCfg) {
this.name = o.name;
this.id = o.id;
this.min_role_read = o.min_role_read;
this.min_role_write = o.min_role_write;
this.ownership_field_id = o.ownership_field_id;
this.ownership_formula = o.ownership_formula;
this.versioned = !!o.versioned;
this.has_sync_info = !!o.has_sync_info;
this.is_user_group = !!o.is_user_group;
this.external = false;
this.description = o.description;
this.constraints = o.constraints || [];
this.provider_cfg = stringToJSON(o.provider_cfg);
this.provider_name = o.provider_name;
this.fields = o.fields.map((f) => new Field(f));
}
get to_json() {
return {
name: this.name,
id: this.id,
min_role_read: this.min_role_read,
min_role_write: this.min_role_write,
provider_name: this.provider_name,
ownership_formula: this.ownership_formula,
ownership_field_id: this.ownership_field_id,
provider_cfg: this.provider_cfg,
external: this.external,
versioned: this.versioned,
fields: this.fields.map((f) => f.toJson),
};
}
to_provided_table() {
const tbl = this;
if (!tbl.provider_name) return this;
const { getState } = require("../db/state");
const provider = getState().table_providers[tbl.provider_name];
const { getRows } = provider.get_table(tbl.provider_cfg, tbl);
const { json_list_to_external_table } = require("../plugin-helper");
const t = json_list_to_external_table(getRows, tbl.fields);
delete t.min_role_read; //it is a getter
Object.assign(t, tbl);
t.update = async (upd_rec: any) => {
const { fields, constraints, ...updDB } = upd_rec;
await db.update("_sc_tables", updDB, tbl.id);
await require("../db/state").getState().refresh_tables();
};
t.delete = async (upd_rec: any) => {
const schema = db.getTenantSchemaPrefix();
await db.deleteWhere("_sc_tag_entries", { table_id: this.id });
await db.query(`delete FROM ${schema}_sc_tables WHERE id = $1`, [tbl.id]);
await require("../db/state").getState().refresh_tables();
};
return t;
}
/**
*
* Find one Table
*
* @param where - where condition
* @returns {*|Table|null} table or null
*/
static findOne(where: Where | Table | number | string): Table | null {
if (
where &&
((where.constructor && where.constructor.name === "Table") ||
(where as any).getRows)
)
return <Table>where;
// todo add string & number as possible types for where
if (typeof where === "string") return Table.findOne({ name: where });
if (typeof where === "number") return Table.findOne({ id: where });
const { getState } = require("../db/state");
// it works because external table hasn't id so can be found only by name
if (where?.name) {
const extTable = getState().external_tables[where.name];
if (extTable) return extTable;
}
const tbl = getState().tables.find(
where?.id
? (v: TableCfg) => v.id === +where.id
: where?.name
? (v: TableCfg) => v.name === where.name
: satisfies(where)
);
if (tbl?.provider_name) {
return new Table(structuredClone(tbl)).to_provided_table();
} else return tbl ? new Table(structuredClone(tbl)) : null;
}
/**
* Find Tables
* @param where - where condition
* @param selectopts - options
* @returns {Promise<Table[]>} table list
*/
static async find(
where?: Where,
selectopts: SelectOptions = { orderBy: "name", nocase: true }
): Promise<Table[]> {
if (selectopts.cached) {
const { getState } = require("../db/state");
return getState()
.tables.map((t: TableCfg) => new Table(structuredClone(t)))
.filter(satisfies(where || {}));
}
if (where?.name) {
const { getState } = require("../db/state");
const extTable = getState().external_tables[where.name];
if (extTable) return [extTable];
}
const tbls = await db.select("_sc_tables", where, selectopts);
const flds = await db.select(
"_sc_fields",
db.isSQLite ? {} : { table_id: { in: tbls.map((t: TableCfg) => t.id) } },
selectopts
);
const _TableConstraint = (await import("./table_constraints")).default;
const constraints = await _TableConstraint.find(
db.isSQLite ? {} : { table_id: { in: tbls.map((t: TableCfg) => t.id) } }
);
return await asyncMap(tbls, async (t: TableCfg) => {
if (t.provider_name) {
const { getState } = require("../db/state");
const provider = getState().table_providers[t.provider_name];
t.fields = await applyAsync(provider.fields, t.provider_cfg);
} else
t.fields = flds
.filter((f: any) => f.table_id === t.id)
.map((f: any) => new Field(f));
t.constraints = constraints
.filter((f: any) => f.table_id === t.id)
.map((f: any) => new _TableConstraint(f));
const tbl = new Table(t);
return tbl.to_provided_table();
});
}
/**
* Find Tables including external tables
* @param where0
* @param selectopts
* @returns {Promise<object[]>}
*/
static async find_with_external(
where0: Where = {},
selectopts: SelectOptions = { orderBy: "name", nocase: true }
): Promise<Table[]> {
const { external, ...where } = where0;
let externals: any[] = [],
dbs = [];
if (external !== false) {
//do include externals
const { getState } = require("../db/state");
externals = Object.values(getState().external_tables);
}
if (external !== true) {
//do include db tables
const tbls = await db.select("_sc_tables", where, selectopts);
const flds = await db.select(
"_sc_fields",
db.isSQLite
? {}
: { table_id: { in: tbls.map((t: TableCfg) => t.id) } },
selectopts
);
dbs = tbls.map((t: TableCfg) => {
t.fields = flds
.filter((f: any) => f.table_id === t.id)
.map((f: any) => new Field(f));
return new Table(t);
});
}
return [...dbs, ...externals];
}
/**
* Get Models
* tbd why this function in this file - needs to models
* @param opts
*/
async get_models(opts?: any) {
const Model = require("./model");
if (typeof opts === "string")
return await Model.find({ name: opts, table_id: this.id });
else return await Model.find({ ...(opts || {}), table_id: this.id });
}
/**
* Get owner column name
* @param fields - fields list
* @returns {null|*} null or owner column name
*/
owner_fieldname_from_fields(
fields?: Field[] | null
): string | null | undefined {
if (!this.ownership_field_id || !fields) return null;
const field = fields.find((f: Field) => f.id === this.ownership_field_id);
return field?.name;
}
/**
* Get owner column name
* @returns {Promise<string|null|*>}
*/
owner_fieldname(): string | null | undefined {
if (this.name === "users") return "id";
if (!this.ownership_field_id) return null;
return this.owner_fieldname_from_fields(this.fields);
}
/**
* Check if user is owner of row
* @param user - user
* @param row - table row
* @returns {Promise<string|null|*|boolean>}
*/
is_owner(user: any, row: Row): boolean {
if (!user) return false;
if (this.ownership_formula && this.fields) {
const f = get_expression_function(this.ownership_formula, this.fields);
return !!f(row, user);
}
const field_name = this.owner_fieldname();
// users are owners of their own row in users table
if (this.name === "users" && !field_name)
return user.id && `${row?.id}` === `${user.id}`;
return typeof field_name === "string" && row[field_name] === user.id;
}
/**
* get Ownership options
* user interface...
*/
async ownership_options(): Promise<{ label: string; value: string }[]> {
const fields = this.fields;
//start with userfields
const opts: { label: string; value: string }[] = fields
.filter((f) => f.reftable_name === "users")
.map((f) => ({ value: `${f.id}`, label: f.name }));
const users = Table.findOne({ name: "users" });
for (const ufield of users?.fields || []) {
if (ufield.is_fkey && ufield.reftable_name === this.name) {
opts.push({
label: `users.${ufield.label} [Key to ${this.name}]`,
value: `Fml:user.${ufield.name}===id /* users.${ufield.label} */`,
});
}
}
// inherit from all my fks if table has ownership
for (const field of fields) {
if (field.is_fkey && field.reftable_name) {
const refTable = Table.findOne({ name: field.reftable_name });
if (refTable?.ownership_field_id) {
//todo find in table.fields so we dont hit db
const ofield = await Field.findOne({
id: refTable?.ownership_field_id,
});
if (ofield)
opts.push({
label: `Inherit ${field.label}`,
value: `Fml:${field.name}?.${ofield.name}===user.id /* Inherit ${field.label} */`,
});
}
if (refTable?.ownership_formula) {
const refFml = removeComments(refTable.ownership_formula);
if (refFml.startsWith("user.") && !refFml.includes(".includes(")) {
for (const ufield of users?.fields || []) {
if (
ufield.is_fkey &&
refFml.startsWith(`user.${ufield.name}===`)
) {
const sides = refFml.split("===");
const newFml = `${sides[0]}===${field.name}.${sides[1]}`;
opts.push({
label: `Inherit ${field.label}`,
value: `Fml:${newFml} /* Inherit ${field.label} */`,
});
}
}
}
if (refFml.endsWith("==user.id")) {
const path = refTable.ownership_formula
.replace("===user.id", "")
.replace("==user.id", "")
.split(".");
const fldNms = new Set((refTable?.fields || []).map((f) => f.name));
if (fldNms.has(path[0])) {
opts.push({
label: `Inherit ${field.label}`,
value: `Fml:${field.name}?.${refFml} /* Inherit ${field.label} */`,
});
}
}
if (refFml.startsWith("user.") && refFml.includes(".includes(")) {
const [_pre, post] = refFml.split(").includes(");
const ref = post.substring(0, post.length - 1);
if (ref === this.pk_name) {
const fml = refFml.replace(
`.includes(${this.pk_name})`,
`.includes(${field.name})`
);
opts.push({
label: `Inherit ${field.label}`,
value: `Fml:${fml} /* Inherit ${field.label} */`,
});
} else {
const fml = refFml.replace(
`.includes(${ref})`,
`.includes(${field.name}?.${ref})`
);
opts.push({
label: `Inherit ${field.label}`,
value: `Fml:${fml} /* Inherit ${field.label} */`,
});
}
}
}
}
}
// get user groups
const tables = await Table.find({}, { cached: true });
for (const ugtable of tables) {
if (ugtable.is_user_group) {
// /user.usergroups_by_user.map(g=>g.group).includes(group)
const ugfields = await ugtable.getFields();
const ug_to_user = ugfields.find((f) => f.reftable_name === "users");
if (!ug_to_user) continue;
// direct field from user group to me
const ug_to_me = ugfields.find((f) => f.reftable_name === this.name);
if (ug_to_me) {
opts.push({
label: `In ${ugtable.name} user group by ${ug_to_me.label}`,
value: `Fml:user.${sqlsanitize(ugtable.name)}_by_${
ug_to_user.name
}.map(g=>g.${ug_to_me.name}).includes(${
this.pk_name
}) /* User group ${ugtable.name} */`,
});
}
// there is a field from this table to user group
for (const field of fields) {
if (field.is_fkey && field.reftable_name === ugtable.name) {
//const to_me = ugfields.find((f) => f.reftable_name === "users");
opts.push({
label: `In ${ugtable.name} user group by ${field.label}`,
value: `Fml:user.${ugtable.name}_by_${ug_to_user.name}.map(g=>g.${ugtable.pk_name}).includes(${field.name})`,
});
}
}
}
}
return opts;
}
/**
* get sanitized name of table
*/
get santized_name() {
return sqlsanitize(this.name);
}
/**
* Create table
* @param name - table name
* @param options - table fields
* @param id - optional id, if set, no '_sc_tables' entry is inserted
* @returns {Promise<Table>} table
*/
static async create(
name: string,
options: SelectOptions | TablePack = {}, //TODO not selectoptions
id?: number
): Promise<Table> {
let pk_type: string = "Integer";
let pk_sql_type = db.isSQLite ? "integer" : "serial";
if (options?.fields && Array.isArray(options.fields)) {
const pk_field = (options.fields as any).find?.(
(f: Field) => typeof f !== "string" && f?.primary_key
);
pk_type =
(typeof pk_field === "string"
? pk_field
: typeof pk_field?.type === "string"
? pk_field?.type
: pk_field?.type?.name) || "Integer";
}
if (pk_type !== "Integer") {
const { getState } = require("../db/state");
const type = getState().types[pk_type];
pk_sql_type = type.sql_name;
if (type.primaryKey?.default_sql)
pk_sql_type = `${type.sql_name} default ${type.primaryKey?.default_sql}`;
}
const schema = db.getTenantSchemaPrefix();
// create table in database
if (!options.provider_name)
await db.query(
`create table ${schema}"${sqlsanitize(
name
)}" (id ${pk_sql_type} primary key)`
);
// populate table definition row
const tblrow: any = {
name,
versioned: options.versioned || false,
has_sync_info: options.has_sync_info || false,
min_role_read: options.min_role_read || 1,
min_role_write: options.min_role_write || 1,
ownership_field_id: options.ownership_field_id,
ownership_formula: options.ownership_formula,
description: options.description || "",
provider_name: options.provider_name,
provider_cfg: options.provider_cfg,
};
let pk_fld_id;
if (!id) {
// insert table definition into _sc_tables
id = await db.insert("_sc_tables", tblrow);
// add primary key column ID
if (!options.provider_name) {
const insfldres = await db.query(
`insert into ${schema}_sc_fields(table_id, name, label, type, attributes, required, is_unique,primary_key)
values($1,'id','ID','${pk_type}', '{}', true, true, true) returning id`,
[id]
);
pk_fld_id = insfldres.rows[0].id;
}
}
// create table
//const provider = getState().table_providers[tbl.provider_name];
//provider.get_table(tbl.provider_cfg, tbl);
const fields = options?.provider_name
? [] //TODO look up
: [
new Field({
type: pk_type,
name: "id",
label: "ID",
primary_key: true,
required: true,
is_unique: true,
table_id: id,
id: pk_fld_id,
}),
];
const table = new Table({
...tblrow,
id,
fields,
});
// create table history
if (table?.versioned) await table.create_history_table();
// create sync info
if (table.has_sync_info) await table.create_sync_info_table();
// refresh tables cache
await require("../db/state").getState().refresh_tables();
return table;
}
/**
* Drop current table
* @param only_forget boolean - if true that only
* @returns {Promise<void>}
*/
// tbd check all other tables related to table description
async delete(only_forget: boolean = false): Promise<void> {
const schema = db.getTenantSchemaPrefix();
const is_sqlite = db.isSQLite;
await this.update({ ownership_field_id: null });
const client = is_sqlite ? db : await db.getClient();
await client.query(`BEGIN`);
try {
// drop table
if (!only_forget)
await client.query(
`drop table if exists ${schema}"${sqlsanitize(this.name)}"`
);
// delete tag entries from _sc_tag_entries
await db.deleteWhere("_sc_tag_entries", { table_id: this.id });
// delete fields
await client.query(
`delete FROM ${schema}_sc_fields WHERE table_id = $1`,
[this.id]
);
// delete table description
await client.query(`delete FROM ${schema}_sc_tables WHERE id = $1`, [
this.id,
]);
// delete versioned table
if (this.versioned)
await client.query(
`drop table if exists ${schema}"${sqlsanitize(this.name)}__history"`
);
await client.query(`COMMIT`);
} catch (e) {
await client.query(`ROLLBACK`);
if (!is_sqlite) client.release(true);
throw e;
}
if (!is_sqlite) client.release(true);
await require("../db/state").getState().refresh_tables();
}
/***
* Get Table SQL Name
* @type {string}
*/
get sql_name(): string {
return `${db.getTenantSchemaPrefix()}"${sqlsanitize(this.name)}"`;
}
/**
* Reset Sequence
*/
async resetSequence() {
const fields = this.fields;
const pk = fields.find((f) => f.primary_key);
if (!pk) {
throw new Error("Unable to find a field with a primary key.");
}
if (
db.reset_sequence &&
instanceOfType(pk.type) &&
pk.type.name === "Integer"
)
await db.reset_sequence(this.name);
}
/**
* update Where with Ownership
* @param where
* @param fields
* @param user
* @param forRead
*/
private updateWhereWithOwnership(
where: Where,
fields: Field[],
user?: Row,
forRead?: boolean
): { notAuthorized?: boolean } | undefined {
const role = user?.role_id;
const min_role = forRead ? this.min_role_read : this.min_role_write;
if (
role &&
role > min_role &&
((!this.ownership_field_id && !this.ownership_formula) || role === 100)
)
return { notAuthorized: true };
if (user && role < 100 && role > min_role && this.ownership_field_id) {
const owner_field = fields.find((f) => f.id === this.ownership_field_id);
if (!owner_field)
throw new Error(`Owner field in table ${this.name} not found`);
mergeIntoWhere(where, {
[owner_field.name]: user.id,
});
}
}
private async addDeleteSyncInfo(ids: Row[], timestamp: Date): Promise<void> {
if (ids.length > 0) {
const schema = db.getTenantSchemaPrefix();
const pkName = this.pk_name || "id";
if (isNode()) {
await db.query(
`delete from ${schema}"${db.sqlsanitize(
this.name
)}_sync_info" where ref in (
${ids.map((row) => row[pkName]).join(",")})`
);
await db.query(
`insert into ${schema}"${db.sqlsanitize(
this.name
)}_sync_info" values ${ids
.map(
(row) =>
`(${row[pkName]}, date_trunc('milliseconds', to_timestamp( ${
timestamp.valueOf() / 1000.0
} ) ), true)`
)
.join(",")}`
);
} else {
await db.query(
`update "${db.sqlsanitize(this.name)}_sync_info"
set deleted = true, modified_local = true
where ref in (${ids.map((row) => row[pkName]).join(",")})`
);
}
}
}
/**
* Delete rows from table. The first argument is a where expression indicating the conditions for the rows to be deleted
*
* @example
* ```
* // delete all books where author = "Friedrich Nietzsche"
* await Table.findOne({name: "books"}).deleteRows({author: "Friedrich Nietzsche"})
* ```
*
* @param where - condition
* @param user - optional user, if null then no authorization will be checked
* @returns
*/
async deleteRows(where: Where, user?: Row, noTrigger?: boolean) {
// get triggers on delete
const triggers = await Trigger.getTableTriggers("Delete", this);
const fields = this.fields;
if (this.updateWhereWithOwnership(where, fields, user)?.notAuthorized) {
const state = require("../db/state").getState();
state.log(4, `Not authorized to deleteRows in table ${this.name}.`);
return;
}
let rows;
if (user && user.role_id > this.min_role_write && this.ownership_formula) {
rows = await this.getJoinedRows({
where,
forUser: user,
});
}
const deleteFileFields = fields.filter(
(f) => f.type === "File" && f.attributes?.also_delete_file
);
const deleteFiles = [];
if ((triggers.length > 0 || deleteFileFields.length > 0) && !noTrigger) {
const File = require("./file");
if (!rows)
rows = await this.getJoinedRows({
where,
});
for (const trigger of triggers) {
for (const row of rows) {
// run triggers on delete
await trigger.run!(row);
}
}
if (isNode()) {
for (const deleteFile of deleteFileFields) {
for (const row of rows) {
if (row[deleteFile.name]) {
const file = await File.findOne({
filename: row[deleteFile.name],
});
deleteFiles.push(file);
}
}
}
}
}
if (rows) {
const delIds = rows.map((r) => r[this.pk_name]);
if (!db.isSQLite) {
await db.deleteWhere(this.name, {
[this.pk_name]: { in: delIds },
});
} else {
await db.query(
`delete from "${db.sqlsanitize(this.name)}" where "${db.sqlsanitize(
this.pk_name
)}" in (${delIds.join(",")})`
);
}
if (this.has_sync_info) {
const dbTime = await db.time();
await this.addDeleteSyncInfo(rows, dbTime);
}
} else {
const delIds = this.has_sync_info
? await db.select(this.name, where, {
fields: [this.pk_name],
})
: null;
await db.deleteWhere(this.name, where);
if (this.has_sync_info) {
const dbTime = await db.time();
await this.addDeleteSyncInfo(delIds, dbTime);
}
}
//if (fields.find((f) => f.primary_key)) await this.resetSequence();
for (const file of deleteFiles) {
await file.delete();
}
}
/**
* Returns row with only fields that can be read from db (readFromDB flag)
* @param row
* @returns {*}
*/
private readFromDB(row: Row): any {
if (this.fields) {
for (const f of this.fields) {
if (f.type && instanceOfType(f.type) && f.type.readFromDB)
row[f.name] = f.type.readFromDB(row[f.name]);
}
}
return row;
}
/**
* Get one row from the table in the database. The matching row will be returned in a promise - use await to read the value.
* If no matching rule can be found, null will be returned. If more than one row matches, the first found row
* will be returned.
*
* The first argument to get row is a where-expression With the conditions the returned row should match.
*