sedentary 0.0.42 → 0.0.43

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/README.md CHANGED
@@ -52,7 +52,7 @@ const db = new Sedentary("file.db");
52
52
 
53
53
  class Items extends db.model("Item", {
54
54
  num: db.INT,
55
- str: db.VARCHAR(30)
55
+ str: db.VarChar(30)
56
56
  });
57
57
 
58
58
  (async function () {
package/package.json CHANGED
@@ -33,16 +33,17 @@
33
33
  "repository": "https://github.com/iccicci/sedentary",
34
34
  "scripts": {
35
35
  "build": "make build",
36
- "coverage": "jest --coverage --runInBand",
36
+ "coverage": "jest --coverage --no-cache --runInBand",
37
37
  "deploy": "npm_config_registry=\"registry.npmjs.org\" npm publish",
38
38
  "precoverage": "make pretest",
39
39
  "preinstall": "if [ -f Makefile ] ; then make ; fi",
40
40
  "pretest": "make pretest",
41
- "test": "jest --runInBand"
41
+ "test": "jest --no-cache --runInBand"
42
42
  },
43
43
  "tsd": {
44
44
  "compilerOptions": {
45
45
  "alwaysStrict": true,
46
+ "composite": false,
46
47
  "esModuleInterop": true,
47
48
  "moduleResolution": "Node",
48
49
  "noImplicitAny": true,
@@ -57,5 +58,5 @@
57
58
  }
58
59
  },
59
60
  "types": "./dist/types/index.d.ts",
60
- "version": "0.0.42"
61
+ "version": "0.0.43"
61
62
  }
package/dist/cjs/db.js DELETED
@@ -1,115 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Transaction = exports.DB = exports.Table = exports.Attribute = exports.Type = exports.EntryBase = void 0;
4
- class EntryBase {
5
- constructor(from) {
6
- if (from === "load")
7
- this.preLoad();
8
- else {
9
- if (from)
10
- Object.assign(this, from);
11
- this.construct();
12
- }
13
- }
14
- construct() { }
15
- postLoad() { }
16
- postRemove() { }
17
- postSave() { }
18
- preLoad() { }
19
- preRemove() { }
20
- preSave() { }
21
- async remove() {
22
- return false;
23
- }
24
- async save() {
25
- return false;
26
- }
27
- }
28
- exports.EntryBase = EntryBase;
29
- class Type {
30
- constructor(from) {
31
- Object.assign(this, from);
32
- }
33
- }
34
- exports.Type = Type;
35
- class Attribute extends Type {
36
- constructor(from) {
37
- super(from);
38
- }
39
- }
40
- exports.Attribute = Attribute;
41
- function autoImplement() {
42
- return class {
43
- constructor(defaults) {
44
- Object.assign(this, defaults);
45
- }
46
- };
47
- }
48
- class Table extends autoImplement() {
49
- findField(name) {
50
- return this.attributes.filter(_ => _.fieldName === name)[0];
51
- }
52
- }
53
- exports.Table = Table;
54
- class DB {
55
- constructor(log) {
56
- this.tables = [];
57
- this.sync = true;
58
- this.log = log;
59
- }
60
- findTable(name) {
61
- return this.tables.filter(_ => _.tableName === name)[0];
62
- }
63
- indexesEq(a, b) {
64
- if (a.fields.length !== b.fields.length)
65
- return false;
66
- for (const i in a.fields)
67
- if (a.fields[i] !== b.fields[i])
68
- return false;
69
- if (a.type !== b.type)
70
- return false;
71
- if (a.unique !== b.unique)
72
- return false;
73
- return true;
74
- }
75
- async syncDataBase() {
76
- for (const table of this.tables) {
77
- this.sync = table.sync;
78
- await this.syncTable(table);
79
- const indexes = await this.dropConstraints(table);
80
- await this.dropIndexes(table, indexes);
81
- await this.dropFields(table);
82
- await this.syncFields(table);
83
- await this.syncSequence(table);
84
- await this.syncConstraints(table);
85
- await this.syncIndexes(table);
86
- }
87
- }
88
- syncLog(message) {
89
- this.log(this.sync ? message : "NOT SYNCING: " + message);
90
- }
91
- }
92
- exports.DB = DB;
93
- class Transaction {
94
- constructor(log) {
95
- this.entries = [];
96
- this.log = log;
97
- }
98
- addEntry(entry) {
99
- Object.defineProperty(entry, "tx", { configurable: true, value: this });
100
- this.entries.push(entry);
101
- }
102
- clean() {
103
- const { entries } = this;
104
- for (const entry of entries)
105
- Object.defineProperty(entry, "tx", { configurable: true, value: null });
106
- this.entries = [];
107
- }
108
- async commit() {
109
- this.clean();
110
- }
111
- async rollback() {
112
- this.clean();
113
- }
114
- }
115
- exports.Transaction = Transaction;
package/dist/cjs/index.js DELETED
@@ -1,516 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Sedentary = exports.Type = exports.Transaction = exports.Table = exports.EntryBase = exports.DB = exports.Attribute = void 0;
4
- const db_1 = require("./db");
5
- var db_2 = require("./db");
6
- Object.defineProperty(exports, "Attribute", { enumerable: true, get: function () { return db_2.Attribute; } });
7
- Object.defineProperty(exports, "DB", { enumerable: true, get: function () { return db_2.DB; } });
8
- Object.defineProperty(exports, "EntryBase", { enumerable: true, get: function () { return db_2.EntryBase; } });
9
- Object.defineProperty(exports, "Table", { enumerable: true, get: function () { return db_2.Table; } });
10
- Object.defineProperty(exports, "Transaction", { enumerable: true, get: function () { return db_2.Transaction; } });
11
- Object.defineProperty(exports, "Type", { enumerable: true, get: function () { return db_2.Type; } });
12
- const operators = ["=", ">", "<", ">=", "<=", "<>", "IN", "IS NULL", "LIKE", "NOT"];
13
- const allowedOption = ["indexes", "int8id", "parent", "primaryKey", "sync", "tableName"];
14
- const reservedNames = [
15
- ...["attr2field", "attributeName", "attributes", "base", "class", "construct", "constructor", "defaultValue", "entry", "fieldName", "foreignKeys", "load"],
16
- ...["loaded", "methods", "name", "postLoad", "postSave", "preLoad", "preSave", "primaryKey", "prototype", "save", "size", "tableName", "tx", "type"]
17
- ];
18
- class Sedentary {
19
- constructor(options) {
20
- this.doSync = true;
21
- this.models = {};
22
- if (!options)
23
- options = {};
24
- if (!(options instanceof Object))
25
- throw new Error("new Sedentary: 'options' argument: Wrong type, expected 'Object'");
26
- for (const k in options)
27
- if (!["autoSync", "log", "sync"].includes(k))
28
- throw new Error(`new Sedentary: 'options' argument: Unknown '${k}' option`);
29
- const { autoSync, log, sync } = { autoSync: true, sync: true, ...options };
30
- if (typeof autoSync !== "boolean")
31
- throw new Error("new Sedentary: 'autoSync' option: Wrong type, expected 'boolean'");
32
- if (log !== null && log !== undefined && !(log instanceof Function))
33
- throw new Error("new Sedentary: 'log' option: Wrong type, expected 'null' or 'Function'");
34
- if (typeof sync !== "boolean")
35
- throw new Error("new Sedentary: 'sync' option: Wrong type, expected 'boolean'");
36
- this.autoSync = autoSync;
37
- this.db = null;
38
- // eslint-disable-next-line no-console
39
- this.log = log ? log : log === null ? () => { } : console.log;
40
- this.doSync = sync;
41
- }
42
- BOOLEAN() {
43
- return new db_1.Type({ base: Boolean, type: "BOOLEAN" });
44
- }
45
- DATETIME() {
46
- return new db_1.Type({ base: Date, type: "DATETIME" });
47
- }
48
- FKEY(attribute, options) {
49
- const { attributeName, base, fieldName, size, tableName, type } = attribute;
50
- return new db_1.Type({ base, foreignKey: { attributeName, fieldName, options, tableName }, size, type });
51
- }
52
- INT(size) {
53
- const message = "Sedentary.INT: 'size' argument: Wrong value, expected 2 or 4";
54
- size = size ? this.checkSize(size, message) : 4;
55
- if (size !== 2 && size !== 4)
56
- throw new Error(message);
57
- return new db_1.Type({ base: Number, size, type: "INT" });
58
- }
59
- INT8() {
60
- return new db_1.Type({ base: BigInt, size: 8, type: "INT8" });
61
- }
62
- NUMBER() {
63
- return new db_1.Type({ base: Number, type: "NUMBER" });
64
- }
65
- VARCHAR(size) {
66
- const message = "Sedentary.VARCHAR: 'size' argument: Wrong value, expected positive integer";
67
- size = size ? this.checkSize(size, message) : undefined;
68
- return new db_1.Type({ base: String, size, type: "VARCHAR" });
69
- }
70
- checkDB() {
71
- if (!this.db)
72
- throw new Error("Package sedentary can't be used directly. Please check: https://www.npmjs.com/package/sedentary#disclaimer");
73
- }
74
- checkOrderBy(order, attributes, modelName) {
75
- let array = [];
76
- if (!order)
77
- return true;
78
- if (typeof order === "string")
79
- array = [order];
80
- else if (order instanceof Array)
81
- array = order;
82
- else
83
- return false;
84
- const provided = {};
85
- for (const attribute of array) {
86
- if (typeof attribute !== "string")
87
- return false;
88
- const attributeName = attribute.startsWith("-") ? attribute.substring(1) : attribute;
89
- if (!(attributeName in attributes))
90
- throw new Error(`${modelName}.load: 'order' argument: '${attributeName}' is not an attribute name`);
91
- if (provided[attributeName])
92
- throw new Error(`${modelName}.load: 'order' argument: Reused '${attributeName}' attribute`);
93
- provided[attributeName] = true;
94
- }
95
- return true;
96
- }
97
- checkSize(size, message) {
98
- const str = size.toString();
99
- const parsed = parseInt(str, 10);
100
- if (str !== parsed.toString())
101
- throw new Error(message);
102
- return parsed;
103
- }
104
- createWhere(modelName, attributes, where) {
105
- if (typeof where === "string")
106
- return [where, true, true];
107
- if (typeof where !== "object")
108
- throw new Error(`${modelName}.load: 'where' argument: Wrong type, expected 'Array', 'Object' or 'string'`);
109
- if (!where)
110
- return ["", false, false];
111
- if (where instanceof Array) {
112
- const length = where.length;
113
- if (!length)
114
- throw new Error(`${modelName}.load: 'where' argument: Empty Array`);
115
- if (!["AND", "NOT", "OR"].includes(where[0]))
116
- throw new Error(`${modelName}.load: 'where' argument: Wrong logical operator, expected 'AND', 'OR' or 'NOT'`);
117
- if (length === 1)
118
- return ["", false, false];
119
- if (where[0] === "NOT") {
120
- if (length > 2)
121
- throw new Error(`${modelName}.load: 'where' argument: 'NOT' operator is unary`);
122
- const [res] = this.createWhere(modelName, attributes, where[1]);
123
- return [res === "" ? "" : `NOT (${res})`, false, false];
124
- }
125
- const conditions = where
126
- .filter((_, i) => i)
127
- .map(_ => this.createWhere(modelName, attributes, _))
128
- .filter(([_]) => _);
129
- if (conditions.length === 1)
130
- return conditions[0];
131
- const isOr = where[0] === "OR";
132
- return [isOr ? conditions.map(([_, , a]) => (a ? `(${_})` : _)).join(" OR ") : conditions.map(([_, o]) => (o ? `(${_})` : _)).join(" AND "), isOr, false];
133
- }
134
- const conditions = [];
135
- for (const key in where) {
136
- const field = attributes[key];
137
- if (!field)
138
- throw new Error(`${modelName}.load: 'where' argument: Unknown '${key}' attribute`);
139
- const value = where[key];
140
- if (value instanceof Array) {
141
- const operator = value[0];
142
- const length = value.length;
143
- if (!length)
144
- throw new Error(`${modelName}.load: 'where' argument: Missing arithmetic operator, expected one of: ${operators.map(_ => `'${_}'`).join(", ")}`);
145
- if (!operators.includes(operator))
146
- throw new Error(`${modelName}.load: 'where' argument: Wrong arithmetic operator, expected one of: ${operators.map(_ => `'${_}'`).join(", ")}`);
147
- if (operator === "IS NULL") {
148
- if (length !== 1)
149
- throw new Error(`${modelName}.load: 'where' argument: 'IS NULL' operator is unary`);
150
- conditions.push(`${field} IS NULL`);
151
- }
152
- else if (operator === "NOT") {
153
- if (length !== 1)
154
- throw new Error(`${modelName}.load: 'where' argument: 'NOT' operator is unary`);
155
- conditions.push(`NOT ${field}`);
156
- }
157
- else {
158
- if (length !== 2)
159
- throw new Error(`${modelName}.load: 'where' argument: '${operator}' operator is binary`);
160
- if (operator === "IN") {
161
- if (!(value[1] instanceof Array))
162
- throw new Error(`${modelName}.load: 'where' argument: 'IN' right operand: Wrong type, expected Array`);
163
- conditions.push(`${field} IN (${value[1].map(_ => this.escape(_)).join(", ")})`);
164
- }
165
- else
166
- conditions.push(`${field} ${operator} ${this.escape(value[1])}`);
167
- }
168
- }
169
- else
170
- conditions.push(`${field} = ${this.escape(value)}`);
171
- }
172
- return [conditions.length ? conditions.join(" AND ") : "", false, false];
173
- }
174
- async connect(sync) {
175
- try {
176
- this.checkDB();
177
- this.log("Connecting...");
178
- await this.db.connect();
179
- this.log("Connected");
180
- if (this.autoSync || sync)
181
- await this.sync();
182
- }
183
- catch (e) {
184
- this.log("Connecting: " + (e instanceof Error ? e.message : JSON.stringify(e)));
185
- throw e;
186
- }
187
- }
188
- async sync() {
189
- this.log("Syncing...");
190
- await this.db.syncDataBase();
191
- this.log("Synced");
192
- }
193
- async end() {
194
- this.log("Closing connection...");
195
- await this.db.end();
196
- this.log("Connection closed");
197
- }
198
- async begin() {
199
- return this.db.begin();
200
- }
201
- escape(value) {
202
- return this.db.escape(value);
203
- }
204
- /* eslint-enable @typescript-eslint/no-explicit-any */
205
- model(modelName, attributes, options, methods) {
206
- this.checkDB();
207
- if (typeof modelName !== "string")
208
- throw new Error("Sedentary.model: 'name' argument: Wrong type, expected 'string'");
209
- if (this.models[modelName])
210
- throw new Error(`Sedentary.model: '${modelName}' model: Model already defined`);
211
- if (!attributes)
212
- attributes = {};
213
- if (!(attributes instanceof Object))
214
- throw new Error(`Sedentary.model: '${modelName}' model: 'attributes' argument: Wrong type, expected 'Object'`);
215
- if (!options)
216
- options = {};
217
- if (!(options instanceof Object))
218
- throw new Error(`Sedentary.model: '${modelName}' model: 'options' argument: Wrong type, expected 'Object'`);
219
- for (const k in options)
220
- if (!allowedOption.includes(k))
221
- throw new Error(`Sedentary.model: '${modelName}' model: 'options' argument: Unknown '${k}' option`);
222
- if (options.int8id && options.parent)
223
- throw new Error(`Sedentary.model: '${modelName}' model: 'int8id' and 'parent' options conflict each other`);
224
- if (options.int8id && options.primaryKey)
225
- throw new Error(`Sedentary.model: '${modelName}' model: 'int8id' and 'primaryKey' options conflict each other`);
226
- if (options.parent && options.primaryKey)
227
- throw new Error(`Sedentary.model: '${modelName}' model: 'parent' and 'primaryKey' options conflict each other`);
228
- let autoIncrement = true;
229
- const { indexes, int8id, parent, primaryKey, sync, tableName } = { sync: this.doSync, tableName: modelName, ...options };
230
- let aarray = int8id
231
- ? [new db_1.Attribute({ ...this.INT8(), attributeName: "id", fieldName: "id", modelName, notNull: true, tableName, unique: true })]
232
- : [new db_1.Attribute({ ...this.INT(4), attributeName: "id", fieldName: "id", modelName, notNull: true, tableName, unique: true })];
233
- let constraints = [{ attribute: aarray[0], constraintName: `${tableName}_id_unique`, type: "u" }];
234
- const iarray = [];
235
- let pk = aarray[0];
236
- let attr2field = { id: "id" };
237
- if (!methods)
238
- methods = {};
239
- if (!(methods instanceof Object))
240
- throw new Error(`Sedentary.model: '${modelName}' model: 'methods' option: Wrong type, expected 'Object'`);
241
- if (parent)
242
- if (!parent.attributes)
243
- throw new Error(`Sedentary.model: '${modelName}' model: 'parent' option: Wrong type, expected 'Model'`);
244
- if (primaryKey && typeof primaryKey !== "string")
245
- throw new Error(`Sedentary.model: '${modelName}' model: 'primaryKey' option: Wrong type, expected 'string'`);
246
- if (primaryKey && !Object.keys(attributes).includes(primaryKey))
247
- throw new Error(`Sedentary.model: '${modelName}' model: 'primaryKey' option: Attribute '${primaryKey}' does not exists`);
248
- if (parent || primaryKey) {
249
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
250
- attr2field = parent ? { ...parent.attr2field } : {};
251
- autoIncrement = false;
252
- aarray = [];
253
- constraints = [];
254
- }
255
- for (const attributeName of Object.keys(attributes).sort()) {
256
- if (reservedNames.includes(attributeName))
257
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: Reserved name`);
258
- const call = (defaultValue, fieldName, notNull, unique, func, message1, message2) => {
259
- if (func === this.FKEY)
260
- throw new Error(`${message1} 'this.FKEY' can't be used directly`);
261
- if (![this.BOOLEAN, this.DATETIME, this.NUMBER, this.INT, this.INT8, this.VARCHAR].includes(func))
262
- throw new Error(`${message1} ${message2}`);
263
- return new db_1.Attribute({ attributeName, defaultValue, fieldName, modelName, notNull, tableName, unique, ...func() });
264
- };
265
- const attributeDefinition = attributes[attributeName];
266
- let { base, defaultValue, fieldName, foreignKey, notNull, size, type, unique } = (() => {
267
- const ret = (() => {
268
- if (attributeDefinition instanceof db_1.Type)
269
- return new db_1.Attribute({ attributeName, fieldName: attributeName, modelName, notNull: false, tableName, ...attributeDefinition });
270
- if (attributeDefinition instanceof Function)
271
- return call(undefined, attributeName, false, false, attributeDefinition, `Sedentary.model: '${modelName}' model: '${attributeName}' attribute:`, "Wrong type, expected 'Attribute'");
272
- if (!(attributeDefinition instanceof Object))
273
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: Wrong attribute type, expected 'Attribute'`);
274
- const attributeDefaults = { defaultValue: undefined, fieldName: attributeName, notNull: false, unique: false, ...attributeDefinition };
275
- const { defaultValue, fieldName, notNull, unique, type } = attributeDefaults;
276
- if (defaultValue === null)
277
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'defaultValue' option: Does 'null' default value really makes sense?`);
278
- if (typeof fieldName !== "string")
279
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'fieldName' option: Wrong type, expected 'string'`);
280
- if (typeof notNull !== "boolean")
281
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'notNull' option: Wrong type, expected 'boolean'`);
282
- if (typeof unique !== "boolean")
283
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'unique' option: Wrong type, expected 'boolean'`);
284
- if (type === undefined)
285
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: Missing 'type' option`);
286
- if (type instanceof db_1.Type)
287
- return new db_1.Attribute({ attributeName, defaultValue, fieldName, modelName, notNull, tableName, unique, ...type });
288
- if (type instanceof Function)
289
- return call(defaultValue, fieldName, notNull, unique, type, `Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'type' option:`, "Wrong type, expected 'Type'");
290
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'type' option: Wrong type, expected 'Type'`);
291
- })();
292
- const { base, defaultValue } = ret;
293
- if (defaultValue !== undefined) {
294
- if (base === BigInt && typeof defaultValue !== "bigint")
295
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'defaultValue' option: Wrong type, expected 'BigInt'`);
296
- if (base === Date && !(defaultValue instanceof Date))
297
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'defaultValue' option: Wrong type, expected 'Date'`);
298
- if (base === Number && typeof defaultValue !== "number")
299
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'defaultValue' option: Wrong type, expected 'number'`);
300
- if (base === String && typeof defaultValue !== "string")
301
- throw new Error(`Sedentary.model: '${modelName}' model: '${attributeName}' attribute: 'defaultValue' option: Wrong type, expected 'string'`);
302
- }
303
- return ret;
304
- })();
305
- if (foreignKey) {
306
- const options = foreignKey.options || {};
307
- if (foreignKey.options !== undefined && !(foreignKey.options instanceof Object))
308
- throw new Error(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: Wrong options type, expected 'Object'`);
309
- for (const k in options)
310
- if (!["onDelete", "onUpdate"].includes(k))
311
- throw new Error(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: Unknown option '${k}'`);
312
- for (const onChange of ["onDelete", "onUpdate"]) {
313
- const actions = ["cascade", "no action", "restrict", "set default", "set null"];
314
- let action = options[onChange];
315
- if (!action)
316
- action = options[onChange] = "no action";
317
- if (action && !actions.includes(action))
318
- throw new Error(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: '${onChange}' option: Wrong value, expected ${actions.map(_ => `'${_}'`).join(" | ")}`);
319
- }
320
- foreignKey.options = options;
321
- }
322
- if (primaryKey === attributeName) {
323
- notNull = true;
324
- unique = true;
325
- }
326
- if (defaultValue)
327
- notNull = true;
328
- const attribute = new db_1.Attribute({ attributeName, base, defaultValue, fieldName, foreignKey, modelName, notNull, size, tableName, type, unique });
329
- if (primaryKey === attributeName)
330
- pk = attribute;
331
- aarray.push(attribute);
332
- attr2field[attributeName] = fieldName;
333
- if (foreignKey)
334
- constraints.push({ attribute, constraintName: `fkey_${fieldName}_${foreignKey.tableName}_${foreignKey.fieldName}`, type: "f" });
335
- if (unique)
336
- constraints.push({ attribute, constraintName: `${tableName}_${fieldName}_unique`, type: "u" });
337
- }
338
- if (indexes) {
339
- const flds = attributes;
340
- if (!(indexes instanceof Object))
341
- throw new Error(`Sedentary.model: '${modelName}' model: 'indexes' option: Wrong type, expected 'Object'`);
342
- for (const indexName in indexes) {
343
- if (aarray.filter(({ fieldName, unique }) => unique && `${tableName}_${fieldName}_unique` === indexName).length !== 0)
344
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: index name already inferred by the unique constraint on an attribute`);
345
- const idx = indexes[indexName];
346
- const checkAttribute = (attribute, l) => {
347
- if (typeof attribute !== "string")
348
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: #${l + 1} attribute: Wrong type, expected 'string'`);
349
- if (!(attribute in flds))
350
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: #${l + 1} attribute: Unknown attribute '${attribute}'`);
351
- };
352
- let attributes;
353
- let type = "btree";
354
- let unique = false;
355
- if (idx instanceof Array) {
356
- idx.forEach(checkAttribute);
357
- attributes = idx;
358
- }
359
- else if (typeof idx === "string") {
360
- checkAttribute(idx, 0);
361
- attributes = [idx];
362
- }
363
- else if (idx instanceof Object) {
364
- for (const k in idx)
365
- if (!["attributes", "type", "unique"].includes(k))
366
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: Unknown index option '${k}'`);
367
- ({ attributes, type, unique } = { type: "btree", unique: false, ...idx });
368
- if (!attributes)
369
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: Missing 'attributes' option`);
370
- if (attributes instanceof Array)
371
- attributes.forEach(checkAttribute);
372
- else if (typeof attributes === "string") {
373
- checkAttribute(attributes, 0);
374
- attributes = [attributes];
375
- }
376
- else
377
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: 'attributes' option: Wrong type, expected 'FieldNames'`);
378
- if (typeof type !== "string")
379
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: 'type' option: Wrong type, expected 'string'`);
380
- if (!["btree", "hash"].includes(type))
381
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: 'type' option: Wrong value, expected 'btree' or 'hash'`);
382
- if (typeof unique !== "boolean")
383
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: 'unique' option: Wrong type, expected 'boolean'`);
384
- }
385
- else
386
- throw new Error(`Sedentary.model: '${modelName}' model: '${indexName}' index: Wrong type, expected 'Object'`);
387
- iarray.push({ fields: attributes, indexName, type, unique });
388
- }
389
- }
390
- this.models[modelName] = true;
391
- const foreignKeys = aarray
392
- .filter(_ => _.foreignKey)
393
- .reduce((ret, curr) => {
394
- ret[curr.attributeName] = true;
395
- return ret;
396
- }, {});
397
- for (const foreignKey in foreignKeys) {
398
- if (foreignKey + "Load" in attributes)
399
- throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with an attribute`);
400
- if (foreignKey + "Load" in methods)
401
- throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with a method`);
402
- }
403
- for (const method in methods)
404
- if (method in attributes)
405
- throw new Error(`Sedentary.model: '${modelName}' model: '${method}' method: conflicts with an attribute`);
406
- const checkParent = (parent) => {
407
- if (!parent)
408
- return;
409
- for (const attribute in attributes) {
410
- if (attribute in parent.attributes)
411
- throw new Error(`Sedentary.model: '${modelName}' model: '${attribute}' attribute: conflicts with an attribute of '${parent.modelName}' model`);
412
- if (attribute in parent.methods)
413
- throw new Error(`Sedentary.model: '${modelName}' model: '${attribute}' attribute: conflicts with a method of '${parent.modelName}' model`);
414
- for (const foreignKey in parent.foreignKeys)
415
- if (attribute === foreignKey + "Load")
416
- throw new Error(`Sedentary.model: '${modelName}' model: '${attribute}' attribute: conflicts with an inferred methods of '${parent.modelName}' model`);
417
- }
418
- for (const foreignKey in foreignKeys) {
419
- if (foreignKey + "Load" in parent.attributes)
420
- throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with an attribute of '${parent.modelName}' model`);
421
- if (foreignKey + "Load" in parent.methods)
422
- throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with a method of '${parent.modelName}' model`);
423
- }
424
- for (const method in methods) {
425
- if (method in parent.attributes)
426
- throw new Error(`Sedentary.model: '${modelName}' model: '${method}' method: conflicts with an attribute of '${parent.modelName}' model`);
427
- for (const foreignKey in parent.foreignKeys)
428
- if (foreignKey + "Load" === method)
429
- throw new Error(`Sedentary.model: '${modelName}' model: '${method}' method: conflicts with an inferred methods of '${parent.modelName}' model`);
430
- }
431
- checkParent(parent.parent);
432
- };
433
- checkParent(parent);
434
- const ret = class extends (parent || db_1.EntryBase) {
435
- constructor(from, tx) {
436
- super(from);
437
- if (tx)
438
- tx.addEntry(this);
439
- }
440
- };
441
- const table = new db_1.Table({ autoIncrement, constraints, attributes: aarray, indexes: iarray, model: ret, parent, pk, sync, tableName });
442
- this.db.tables.push(table);
443
- const load_ = this.db.load(tableName, attr2field, pk, ret, table);
444
- const load = async (where, ...args) => {
445
- let order = undefined;
446
- let limit = undefined;
447
- let tx = undefined;
448
- let lock = undefined;
449
- const checkArgs = (first) => {
450
- if (!args.length)
451
- return;
452
- if (args[0] instanceof db_1.Transaction) {
453
- if (first)
454
- order = undefined;
455
- limit = undefined;
456
- [tx, lock] = args;
457
- }
458
- else if (typeof args[0] === "number") {
459
- if (first)
460
- order = undefined;
461
- [limit, tx, lock] = args;
462
- }
463
- else {
464
- if (first) {
465
- order = args.shift();
466
- checkArgs(false);
467
- }
468
- else
469
- throw new Error(`${modelName}.load: 'limit' argument: Wrong type, expected 'number'`);
470
- }
471
- };
472
- checkArgs(true);
473
- if (!this.checkOrderBy(order, attr2field, modelName))
474
- throw new Error(`${modelName}.load: 'order' argument: Wrong type, expected 'string | string[]'`);
475
- if (tx && !(tx instanceof db_1.Transaction))
476
- throw new Error(`${modelName}.load: 'tx' argument: Wrong type, expected 'Transaction'`);
477
- const [str] = this.createWhere(modelName, attr2field, where);
478
- const ret = await load_(str, order, limit, tx, lock);
479
- return ret;
480
- };
481
- Object.defineProperty(load, "name", { value: modelName + ".load" });
482
- Object.defineProperty(ret, "name", { value: modelName });
483
- Object.defineProperty(ret, "load", { value: load });
484
- Object.defineProperty(ret, "attr2field", { value: attr2field });
485
- Object.defineProperty(ret, "attributes", { value: attributes });
486
- Object.defineProperty(ret, "foreignKeys", { value: foreignKeys });
487
- Object.defineProperty(ret, "methods", { value: methods });
488
- Object.assign(ret.prototype, methods);
489
- const remove = this.db.remove(tableName, pk);
490
- ret.prototype.remove = async function () {
491
- if (!this.loaded)
492
- throw new Error(`${modelName}.remove: Can't remove a never saved Entry`);
493
- this.preRemove();
494
- const ret = await remove.call(this);
495
- if (ret)
496
- this.postRemove();
497
- return ret;
498
- };
499
- Object.defineProperty(ret.prototype.remove, "name", { value: modelName + ".remove" });
500
- const save = this.db.save(tableName, attr2field, pk);
501
- ret.prototype.save = async function () {
502
- this.preSave();
503
- const ret = await save.call(this);
504
- if (ret)
505
- this.postSave();
506
- return ret;
507
- };
508
- Object.defineProperty(ret.prototype.save, "name", { value: modelName + ".save" });
509
- for (const attribute of aarray)
510
- Object.defineProperty(ret, attribute.attributeName, { value: attribute });
511
- for (const key of ["attributeName", "base", "fieldName", "modelName", "size", "tableName", "type", "unique"])
512
- Object.defineProperty(ret, key, { value: pk[key] });
513
- return ret;
514
- }
515
- }
516
- exports.Sedentary = Sedentary;