sedentary 0.0.19 → 0.0.20

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/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { DB, EntryBase, ForeignKeyOptions, Meta, Natural, Type } from "./lib/db";
1
+ import { Attribute, DB, EntryBase, ForeignKeyOptions, Natural, Type } from "./lib/db";
2
2
  export { EntryBase, ForeignKeyActions, ForeignKeyOptions, Natural, Type } from "./lib/db";
3
3
  export declare type TypeDefinition<N extends Natural, E> = (() => Type<N, E>) | Type<N, E>;
4
4
  export interface AttributeOptions<N extends Natural, E> {
@@ -16,13 +16,9 @@ declare type ForeignKeysAttributes<T, k> = T extends AttributeDefinition<Natural
16
16
  declare type ForeignKeys<A extends AttributesDefinition> = {
17
17
  [a in keyof A]?: ForeignKeysAttributes<A[a], a>;
18
18
  }[keyof A];
19
- declare type Methods<E> = {
20
- [key: string]: (this: E) => unknown;
21
- };
22
19
  declare type Native__<T> = T extends Type<infer N, unknown> ? N : never;
23
20
  declare type Native_<T> = T extends () => Type<infer N, infer E> ? Native__<Type<N, E>> : Native__<T>;
24
21
  declare type Native<T> = T extends AttributeOptions<infer N, infer E> ? Native__<Type<N, E>> : Native_<T>;
25
- declare type Parent<T> = T extends Meta<Natural, infer E> ? E : never;
26
22
  export declare type IndexAttributes = string[] | string;
27
23
  export interface IndexOptions {
28
24
  attributes: IndexAttributes;
@@ -33,51 +29,59 @@ export declare type IndexDefinition = IndexAttributes | IndexOptions;
33
29
  export declare type IndexesDefinition = {
34
30
  [key: string]: IndexDefinition;
35
31
  };
36
- declare type BaseModelOptions<B extends boolean, T> = {
32
+ interface BaseModelOptions {
37
33
  indexes?: IndexesDefinition;
38
- init?: (this: T) => void;
39
- int8id?: B;
40
34
  sync?: boolean;
41
35
  tableName?: string;
42
- };
43
- export declare type ModelOptions<B extends boolean, K extends string, M extends Methods<T>, P extends Meta<Natural, EntryBase>, T extends EntryBase> = BaseModelOptions<B, T> & {
44
- methods?: M;
45
- parent?: P;
46
- primaryKey?: K;
47
- };
48
- declare type ModelBaseOptions = {
49
- indexes?: IndexesDefinition;
50
- sync?: boolean;
51
- tableName?: string;
52
- };
53
- export declare type ModelOptions2 = ModelBaseOptions & {
36
+ }
37
+ export interface ModelOptions extends BaseModelOptions {
54
38
  int8id?: boolean;
55
39
  parent?: Type<Natural, EntryBase>;
56
40
  primaryKey?: string;
41
+ }
42
+ declare type ConditionAttribute<N extends Natural> = N | [">" | "<" | ">=" | "<=" | "<>", N] | ["LIKE", string] | ["IN", ...N[]];
43
+ declare type ConditionBase<A extends AttributesDefinition> = string | {
44
+ [a in keyof A]?: ConditionAttribute<Native<A[a]>>;
57
45
  };
46
+ declare type Condition<A extends AttributesDefinition> = ConditionBase<A> | ["NOT", Condition<A>] | ["AND", ...Condition<A>[]] | ["OR", ...Condition<A>[]];
58
47
  declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;
59
48
  declare type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true;
60
- declare type EntryIdNatural<B extends boolean> = IsUnion<B> extends true ? number : B extends true ? string : number;
61
- export declare type EntryId<B extends boolean> = {
62
- id?: EntryIdNatural<B>;
63
- };
49
+ declare type BaseKeyType<B extends boolean> = IsUnion<B> extends true ? number : B extends true ? string : number;
50
+ declare type KeyType<B extends boolean, P extends ModelStd> = P extends new () => EntryBase ? (P extends Attribute<infer T, EntryBase> ? T : never) : BaseKeyType<B>;
64
51
  declare type ForeignKey<A> = A extends AttributeDefinition<Natural, infer E> ? () => Promise<E> : never;
65
- declare type ModelFKAttributes<A extends AttributesDefinition> = {
66
- [a in ForeignKeys<A> & string as `${a}Load`]?: ForeignKey<A[a]>;
67
- };
68
- declare type ModelBaseAttributes<A extends AttributesDefinition> = {
52
+ declare type EntryBaseAttributes<A extends AttributesDefinition> = {
69
53
  [a in keyof A]?: Native<A[a]>;
70
54
  };
71
- declare type ModelAttributes<A extends AttributesDefinition> = keyof ModelFKAttributes<A> extends never ? ModelBaseAttributes<A> : ModelBaseAttributes<A> & ModelFKAttributes<A>;
72
- declare type Ancestor<A, N extends Natural, T extends EntryBase> = (new () => T) & {
73
- [a in keyof A]?: Meta<Native<A[a]>, T>;
55
+ declare type EntryMethodsBase<P extends ModelStd> = P extends new () => EntryBase ? P["methods"] : EntryBase;
56
+ declare type EntryMethodsFK<A extends AttributesDefinition> = {
57
+ [a in ForeignKeys<A> & string as `${a}Load`]: ForeignKey<A[a]>;
58
+ };
59
+ declare type EntryMethods<A extends AttributesDefinition, P extends ModelStd> = keyof EntryMethodsFK<A> extends never ? EntryMethodsBase<P> : EntryMethodsBase<P> & EntryMethodsFK<A>;
60
+ declare type ModelAttributesIf<A extends AttributesDefinition, T> = keyof A extends never ? T : T & A;
61
+ declare type ModelAttributes<A extends AttributesDefinition, B extends boolean, K extends string, P extends ModelStd> = K extends keyof A ? A : ModelAttributesIf<A, P extends new () => EntryBase ? P["attributes"] : {
62
+ id: Type<BaseKeyType<B>, unknown>;
63
+ }>;
64
+ declare type ModelBase<N extends Natural, A extends AttributesDefinition, EA extends Record<string, Natural | undefined>, EM extends EntryBase, E extends EntryBase> = (new (from?: EA) => E) & Attribute<N, E> & {
65
+ attributes: A;
66
+ foreignKeys: Record<string, boolean>;
67
+ methods: EM;
68
+ parent?: ModelStd;
69
+ tableName: string;
70
+ load: (where?: Condition<A>) => Promise<E[]>;
74
71
  } & {
75
- load: (boh: boolean) => Promise<T[]>;
76
- } & Meta<N, T> & {
77
- tmp: number;
72
+ [a in keyof A]: Attribute<Native<A[a]>, E>;
73
+ };
74
+ declare type Model<N extends Natural, A extends AttributesDefinition, EM extends EntryBase> = ModelBase<N, A, EntryBaseAttributes<A>, EM, EntryBaseAttributes<A> & EM>;
75
+ declare type ModelStd = Attribute<Natural, EntryBase> & {
76
+ attributes: AttributesDefinition;
77
+ foreignKeys: Record<string, boolean>;
78
+ methods: EntryBase;
79
+ parent?: ModelStd;
78
80
  };
79
- declare type ModelBase<E extends EntryBase> = new () => E;
80
81
  export declare type Entry<M> = M extends new () => infer E ? E : never;
82
+ export declare type Where<M> = M extends {
83
+ load: (where: infer T) => void;
84
+ } ? Exclude<T, undefined> : never;
81
85
  export interface SedentaryOptions {
82
86
  log?: ((message: string) => void) | null;
83
87
  serverless?: boolean;
@@ -90,36 +94,22 @@ export declare class Sedentary {
90
94
  private models;
91
95
  constructor(filename: string, options?: SedentaryOptions);
92
96
  DATETIME(): Type<Date, unknown>;
93
- FKEY<N extends Natural, E extends EntryBase>(attribute: Type<N, E>, options?: ForeignKeyOptions): Type<N, E>;
97
+ FKEY<N extends Natural, E extends EntryBase>(attribute: Attribute<N, E>, options?: ForeignKeyOptions): Type<N, E>;
94
98
  INT(size?: number): Type<number, unknown>;
95
99
  INT8(): Type<string, unknown>;
96
100
  VARCHAR(size?: number): Type<string, unknown>;
97
101
  checkSize(size: number, message: string): number;
98
102
  connect(): Promise<void>;
99
103
  end(): Promise<void>;
100
- model2<E extends EntryBase>(modelName: string): ModelBase<E>;
101
- model2<E extends EntryBase, M extends Record<string, <S extends M>(this: E & S) => unknown>>(modelName: string, methods: M & Record<string, (this: E & M) => void>): ModelBase<E & M>;
102
- model<A extends AttributesDefinition, B extends boolean, E extends EntryBase & EntryId<B> & ModelAttributes<A>>(modelName: string, attributes: A, options?: BaseModelOptions<B, E>): Ancestor<A, string, E>;
103
- model<A extends AttributesDefinition, B extends boolean, K extends keyof A, P extends Meta<Natural, EntryBase>, N extends P extends {
104
- tmp: number;
105
- } ? (P extends Meta<infer N, EntryBase> ? N : never) : Native<A[K]>, E extends (P extends {
106
- tmp: number;
107
- } ? Parent<P> : EntryBase) & ModelAttributes<A>>(modelName: string, attributes: A, options?: BaseModelOptions<B, E> & {
104
+ model<A extends AttributesDefinition, B extends boolean, K extends string, P extends ModelStd, EM extends EntryMethods<A, P>>(modelName: string, attributes: A, options?: BaseModelOptions & {
105
+ int8id?: B;
108
106
  parent?: P;
109
- primaryKey?: K;
110
- }): Ancestor<A, N, E>;
111
- model<A extends AttributesDefinition, B extends boolean, E extends EntryBase & EntryId<B> & ModelAttributes<A>, M extends Record<string, <S extends M>(this: E & S) => unknown>>(modelName: string, attributes: A, options: BaseModelOptions<B, E>, methods: M & Record<string, (this: E & M) => unknown>): Ancestor<A, string, E & M>;
112
- model<A extends AttributesDefinition, B extends boolean, K extends keyof A, P extends Meta<Natural, EntryBase>, N extends P extends {
113
- tmp: number;
114
- } ? (P extends Meta<infer N, EntryBase> ? N : never) : Native<A[K]>, E extends (P extends {
115
- tmp: number;
116
- } ? Parent<P> : EntryBase) & ModelAttributes<A>, M extends Record<string, <S extends M>(this: E & S) => unknown>>(modelName: string, attributes: A, options: BaseModelOptions<B, E> & {
107
+ primaryKey?: K | keyof A;
108
+ }): Model<K extends keyof A ? Native<A[K]> : KeyType<B, P>, ModelAttributes<A, B, K, P>, EM>;
109
+ model<A extends AttributesDefinition, B extends boolean, K extends string, P extends ModelStd, EA extends EntryBaseAttributes<ModelAttributes<A, B, K, P>>, EM extends EntryMethods<A, P>, M extends Record<string, <S extends M>(this: EA & EM & S, ...args: any[]) => void>>(modelName: string, attributes: A, options: BaseModelOptions & {
110
+ int8id?: B;
117
111
  parent?: P;
118
- primaryKey?: K;
119
- }, methods: M & Record<string, (this: E & M) => unknown>): Ancestor<A, N, E & M>;
112
+ primaryKey?: K | keyof A;
113
+ }, methods: M & Record<keyof M, (this: EA & EM & M, ...args: any[]) => void>): Model<K extends keyof A ? Native<A[K]> : KeyType<B, P>, ModelAttributes<A, B, K, P>, EM & M>;
120
114
  }
121
115
  export declare const Package: typeof Sedentary;
122
- export declare class Sedentary2 {
123
- model<E extends EntryBase>(modelName: string): ModelBase<E>;
124
- model<E extends EntryBase, M extends Record<string, <S extends M>(this: E & S) => unknown>>(modelName: string, methods: M & Record<string, (this: E & M) => void>): ModelBase<E & M>;
125
- }
package/index.js CHANGED
@@ -1,16 +1,15 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Sedentary2 = exports.Package = exports.Sedentary = exports.Type = exports.EntryBase = void 0;
3
+ exports.Package = exports.Sedentary = exports.Type = exports.EntryBase = void 0;
4
4
  const db_1 = require("./lib/db");
5
- const log_1 = require("./lib/log");
6
5
  const minidb_1 = require("./lib/minidb");
7
6
  var db_2 = require("./lib/db");
8
7
  Object.defineProperty(exports, "EntryBase", { enumerable: true, get: function () { return db_2.EntryBase; } });
9
8
  Object.defineProperty(exports, "Type", { enumerable: true, get: function () { return db_2.Type; } });
10
- const allowedOption = ["indexes", "init", "int8id", "methods", "parent", "primaryKey", "sync", "tableName", "type"];
9
+ const allowedOption = ["indexes", "int8id", "parent", "primaryKey", "sync", "tableName"];
11
10
  const reservedNames = [
12
- ...["attributeName", "base", "class", "constructor", "defaultValue", "entry", "fieldName", "init", "isModel"],
13
- ...["load", "meta", "methods", "name", "primaryKey", "prototype", "save", "size", "tableName", "type"]
11
+ ...["attributeName", "attributes", "base", "class", "construct", "constructor", "defaultValue", "entry", "fieldName", "foreignKeys", "load"],
12
+ ...["methods", "name", "postLoad", "postSave", "preLoad", "preSave", "primaryKey", "prototype", "save", "size", "tableName", "type"]
14
13
  ];
15
14
  class Sedentary {
16
15
  constructor(filename, options) {
@@ -30,7 +29,8 @@ class Sedentary {
30
29
  throw new Error("new Sedentary: 'log' option: Wrong type, expected 'null' or 'Function'");
31
30
  if (typeof sync !== "boolean")
32
31
  throw new Error("new Sedentary: 'sync' option: Wrong type, expected 'boolean'");
33
- this.log = (0, log_1.createLogger)(log);
32
+ // eslint-disable-next-line no-console
33
+ this.log = log ? log : log === null ? () => { } : console.log;
34
34
  this.db = new minidb_1.MiniDB(filename, this.log);
35
35
  this.sync = sync;
36
36
  }
@@ -72,7 +72,7 @@ class Sedentary {
72
72
  this.log("Synced");
73
73
  }
74
74
  catch (e) {
75
- this.log("Connecting:", e.message);
75
+ this.log("Connecting: " + (e instanceof Error ? e.message : JSON.stringify(e)));
76
76
  throw e;
77
77
  }
78
78
  }
@@ -81,15 +81,7 @@ class Sedentary {
81
81
  await this.db.end();
82
82
  this.log("Connection closed");
83
83
  }
84
- model2(modelName, methods) {
85
- const ret = function () {
86
- this.save();
87
- };
88
- Object.defineProperty(ret, "name", { value: name });
89
- if (methods)
90
- Object.assign(ret.prototype, methods);
91
- return ret;
92
- }
84
+ /* eslint-enable @typescript-eslint/no-explicit-any */
93
85
  model(modelName, attributes, options, methods) {
94
86
  if (typeof modelName !== "string")
95
87
  throw new Error("Sedentary.model: 'name' argument: Wrong type, expected 'string'");
@@ -123,16 +115,10 @@ class Sedentary {
123
115
  if (methods && !(methods instanceof Object))
124
116
  throw new Error(`Sedentary.model: '${modelName}' model: 'methods' option: Wrong type, expected 'Object'`);
125
117
  const originalMethods = methods;
126
- if (parent) {
127
- try {
128
- if (!parent.isModel())
129
- throw new Error();
130
- }
131
- catch (e) {
118
+ if (parent)
119
+ if (!parent.attributes)
132
120
  throw new Error(`Sedentary.model: '${modelName}' model: 'parent' option: Wrong type, expected 'Model'`);
133
- }
134
- methods = (methods ? Object.assign(Object.assign({}, (parent.methods || {})), methods) : parent.methods);
135
- }
121
+ //methods = (methods ? { ...(parent.methods || {}), ...methods } : parent.methods) as never;
136
122
  if (primaryKey && typeof primaryKey !== "string")
137
123
  throw new Error(`Sedentary.model: '${modelName}' model: 'primaryKey' option: Wrong type, expected 'string'`);
138
124
  if (primaryKey && !Object.keys(attributes).includes(primaryKey))
@@ -191,21 +177,21 @@ class Sedentary {
191
177
  return ret;
192
178
  })();
193
179
  if (foreignKey) {
194
- if (!foreignKey.options)
195
- foreignKey.options = {};
196
- if (!(foreignKey.options instanceof Object))
180
+ const options = foreignKey.options || {};
181
+ if (foreignKey.options !== undefined && !(foreignKey.options instanceof Object))
197
182
  throw new Error(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: Wrong options type, expected 'Object'`);
198
- for (const k in foreignKey.options)
183
+ for (const k in options)
199
184
  if (!["onDelete", "onUpdate"].includes(k))
200
185
  throw new Error(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: Unknown option '${k}'`);
201
186
  for (const onChange of ["onDelete", "onUpdate"]) {
202
187
  const actions = ["cascade", "no action", "restrict", "set default", "set null"];
203
- let action = foreignKey.options[onChange];
188
+ let action = options[onChange];
204
189
  if (!action)
205
- action = foreignKey.options[onChange] = "no action";
190
+ action = options[onChange] = "no action";
206
191
  if (action && !actions.includes(action))
207
192
  throw new Error(`Sedentary.FKEY: '${modelName}' model: '${attributeName}' attribute: '${onChange}' option: Wrong value, expected ${actions.map(_ => `'${_}'`).join(" | ")}`);
208
193
  }
194
+ foreignKey.options = options;
209
195
  }
210
196
  if (primaryKey === attributeName) {
211
197
  notNull = true;
@@ -274,70 +260,38 @@ class Sedentary {
274
260
  }
275
261
  this.db.tables.push(new db_1.Table({ autoIncrement, constraints, attributes: aarray, indexes: iarray, parent, sync, tableName }));
276
262
  this.models[modelName] = true;
277
- const init = parent
278
- ? options.init
279
- ? function () {
280
- parent.init.call(this);
281
- options.init.call(this);
282
- }
283
- : parent.init
284
- : options.init;
285
- class Class {
286
- constructor() {
287
- if (init)
288
- init.call(this);
289
- }
290
- save() {
291
- return new Promise((resolve, reject) => {
292
- const save = () => reject(new Error("eh no"));
293
- Object.defineProperty(save, "name", { value: modelName + ".save" });
294
- setTimeout(save, 10);
295
- });
296
- }
297
- }
298
- const load = (boh) => new Promise((resolve, reject) => setTimeout(() => {
299
- if (boh)
300
- return resolve([new Class()]);
301
- reject(new Error("boh"));
302
- }, 10));
303
- Object.defineProperty(load, "name", { value: modelName + ".load" });
304
- const metaAttributes = aarray.reduce((ret, curr) => {
305
- ret[curr.attributeName] = curr;
306
- return ret;
307
- }, {});
308
- const metaForeignKeys = aarray
263
+ const foreignKeys = aarray
309
264
  .filter(_ => _.foreignKey)
310
265
  .reduce((ret, curr) => {
311
- ret[curr.attributeName] = curr;
266
+ ret[curr.attributeName] = true;
312
267
  return ret;
313
268
  }, {});
314
- const meta = new db_1.Meta({ base: Number, attributes: metaAttributes, foreignKeys: metaForeignKeys, modelName, parent: parent, type: "meta", tableName, primaryKey, init, methods });
315
- for (const foreignKey in metaForeignKeys) {
316
- if (foreignKey + "Load" in metaAttributes)
269
+ for (const foreignKey in foreignKeys) {
270
+ if (foreignKey + "Load" in attributes)
317
271
  throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with an attribute`);
318
272
  if (originalMethods && foreignKey + "Load" in originalMethods)
319
273
  throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with a method`);
320
274
  }
321
275
  if (originalMethods)
322
276
  for (const method in originalMethods)
323
- if (method in metaAttributes)
277
+ if (method in attributes)
324
278
  throw new Error(`Sedentary.model: '${modelName}' model: '${method}' method: conflicts with an attribute`);
325
279
  const checkParent = (parent) => {
326
280
  if (!parent)
327
281
  return;
328
- for (const attribute in metaAttributes) {
282
+ for (const attribute in attributes) {
329
283
  if (attribute in parent.attributes)
330
284
  throw new Error(`Sedentary.model: '${modelName}' model: '${attribute}' attribute: conflicts with an attribute of '${parent.modelName}' model`);
331
- if (parent.methods && attribute in parent.methods)
285
+ if (attribute in parent.methods)
332
286
  throw new Error(`Sedentary.model: '${modelName}' model: '${attribute}' attribute: conflicts with a method of '${parent.modelName}' model`);
333
287
  for (const foreignKey in parent.foreignKeys)
334
288
  if (attribute === foreignKey + "Load")
335
289
  throw new Error(`Sedentary.model: '${modelName}' model: '${attribute}' attribute: conflicts with an inferred methods of '${parent.modelName}' model`);
336
290
  }
337
- for (const foreignKey in metaForeignKeys) {
291
+ for (const foreignKey in foreignKeys) {
338
292
  if (foreignKey + "Load" in parent.attributes)
339
293
  throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with an attribute of '${parent.modelName}' model`);
340
- if (parent.methods && foreignKey + "Load" in parent.methods)
294
+ if (foreignKey + "Load" in parent.methods)
341
295
  throw new Error(`Sedentary.model: '${modelName}' model: '${foreignKey}' attribute: '${foreignKey}Load' inferred methods conflicts with a method of '${parent.modelName}' model`);
342
296
  }
343
297
  if (originalMethods) {
@@ -347,135 +301,36 @@ class Sedentary {
347
301
  for (const foreignKey in parent.foreignKeys)
348
302
  if (foreignKey + "Load" === method)
349
303
  throw new Error(`Sedentary.model: '${modelName}' model: '${method}' method: conflicts with an inferred methods of '${parent.modelName}' model`);
350
- if (parent.methods && method in parent.methods)
304
+ if (method in parent.methods)
351
305
  throw new Error(`Sedentary.model: '${modelName}' model: '${method}' method: conflicts with a method of '${parent.modelName}' model`);
352
306
  }
353
307
  }
354
308
  checkParent(parent.parent);
355
309
  };
356
310
  checkParent(parent);
357
- Object.defineProperty(Class, "isModel", { value: () => true });
358
- Object.defineProperty(Class, "load", { value: load });
359
- Object.defineProperty(Class, "meta", { value: meta });
360
- Object.defineProperty(Class, "name", { value: modelName });
361
- Object.defineProperty(Class.prototype.save, "name", { value: modelName + ".save" });
362
- Object.assign(Class, meta);
363
- Object.assign(Class.prototype, methods);
364
- for (const attribute of aarray)
365
- Object.defineProperty(Class, attribute.attributeName, { value: attribute });
366
- for (const key of ["attributeName", "base", "fieldName", "modelName", "size", "type", "unique"])
367
- Object.defineProperty(Class, key, { value: pk[key] });
368
- return Class;
369
- }
370
- }
371
- exports.Sedentary = Sedentary;
372
- exports.Package = Sedentary;
373
- const db = new Sedentary("gino");
374
- const Users = db.model("User", { foo: db.INT(), bar: { type: db.VARCHAR(), unique: true } }, {});
375
- class Item extends db.model("Item", {
376
- num: db.FKEY(Users),
377
- str: db.VARCHAR()
378
- }, {
379
- init: function () {
380
- this.num = "0";
381
- this.str = "0";
382
- },
383
- int8id: true
384
- /*
385
- methods: {
386
- prova: (): string => "ok"
387
- }
388
- */
389
- }) {
390
- }
391
- class Super extends db.model("Super", {
392
- a: db.INT,
393
- n: db.FKEY(Item),
394
- s: db.FKEY(Users.bar)
395
- }, {
396
- parent: Item
397
- /*
398
- init: async function() {
399
- this.n = "23";
400
- this.id = 0;
401
- this.num = 0;
402
- const a = this.nLoad ? await this.nLoad() : { prova: (): null => null };
403
- a.prova();
404
- this.prova();
405
- }
406
- */
407
- }) {
408
- }
409
- class Next extends db.model("Next", { a: db.INT, b: db.INT }, {
410
- init: function () {
411
- this.a = 23;
412
- },
413
- primaryKey: "a"
414
- }) {
415
- }
416
- class Current extends db.model("Current", { b: { type: db.FKEY(Next), unique: true } }, {
417
- init: function () {
418
- this.b = 24;
419
- }
420
- }) {
421
- }
422
- class Last extends db.model("Last", { c: db.FKEY(Current.b) }, {
423
- init: function () {
424
- this.c = 24;
425
- },
426
- parent: Next
427
- }) {
428
- }
429
- (async function () {
430
- const item = new Super();
431
- try {
432
- await item.save();
433
- }
434
- catch (e) {
435
- console.log(Item.load, item.save, await Item.load(true), item, e.message);
436
- //console.log(new Next(), Next.load, await Next.load(true), new Last(), item.prova());
437
- }
438
- return true;
439
- })();
440
- function model(modelName, attributes, options, methods) {
441
- const model = function () { };
442
- Object.defineProperty(model, "name", { value: modelName });
443
- if (methods)
444
- Object.assign(model.prototype, methods);
445
- return model;
446
- }
447
- const T1 = model("T1", {});
448
- const t1 = new T1();
449
- t1.id = 0;
450
- console.log(t1);
451
- const T2 = model("T2", { a: db.INT, b: db.VARCHAR }, { int8id: true }, {
452
- test: function (repeat = true) {
453
- if (repeat)
454
- this.b = this.test(false);
455
- this.c = this.a = 0;
456
- return "test";
457
- }
458
- });
459
- const t2 = new T2();
460
- //t2.id = "0";
461
- const tt2 = (t) => console.log(t, t.test(), t.a, t.b);
462
- tt2(t2);
463
- class Sedentary2 {
464
- model(modelName, methods) {
465
311
  const ret = function () { };
312
+ const load = (boh) => new Promise((resolve, reject) => setTimeout(() => {
313
+ if (boh)
314
+ return resolve([new ret()]);
315
+ reject(new Error("boh"));
316
+ }, 10));
317
+ Object.defineProperty(load, "name", { value: modelName + ".load" });
466
318
  Object.defineProperty(ret, "name", { value: modelName });
319
+ Object.defineProperty(ret, "load", { value: load });
320
+ Object.defineProperty(ret, "attributes", { value: attributes });
321
+ Object.defineProperty(ret, "foreignKeys", { value: foreignKeys });
322
+ Object.defineProperty(ret, "methods", { value: methods || {} });
467
323
  if (methods)
468
324
  Object.assign(ret.prototype, methods);
469
- ret.prototype.save = () => new Promise(resolve => resolve(false));
325
+ ret.prototype.save = function () {
326
+ return Promise.resolve(false);
327
+ };
328
+ for (const attribute of aarray)
329
+ Object.defineProperty(ret, attribute.attributeName, { value: attribute });
330
+ for (const key of ["attributeName", "base", "fieldName", "modelName", "size", "tableName", "type", "unique"])
331
+ Object.defineProperty(ret, key, { value: pk[key] });
470
332
  return ret;
471
333
  }
472
334
  }
473
- exports.Sedentary2 = Sedentary2;
474
- const db2 = new Sedentary2();
475
- const T22 = db2.model("T2", {
476
- c: function () {
477
- this.id = "0";
478
- this.c();
479
- return 0;
480
- }
481
- });
335
+ exports.Sedentary = Sedentary;
336
+ exports.Package = Sedentary;
package/lib/db.d.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export declare type Natural = Date | Record<string, unknown> | boolean | number | string;
2
2
  export declare class EntryBase {
3
+ construct(): void;
4
+ postLoad(): void;
5
+ preLoad(): void;
6
+ preSave(): void;
3
7
  save(): Promise<boolean>;
4
8
  }
5
9
  export declare type ForeignKeyActions = "cascade" | "no action" | "restrict" | "set default" | "set null";
@@ -7,7 +11,7 @@ export interface ForeignKeyOptions {
7
11
  onDelete?: ForeignKeyActions;
8
12
  onUpdate?: ForeignKeyActions;
9
13
  }
10
- export declare class Type<N extends Natural, E> {
14
+ export interface Type<N extends Natural, E> {
11
15
  base: unknown;
12
16
  entry?: E;
13
17
  native?: N;
@@ -19,27 +23,11 @@ export declare class Type<N extends Natural, E> {
19
23
  options?: ForeignKeyOptions;
20
24
  tableName: string;
21
25
  };
22
- constructor(from: Type<N, E>);
23
26
  }
24
- export declare class Meta<N extends Natural, E> extends Type<N, E> {
25
- attributes: {
26
- [key: string]: unknown;
27
- };
28
- foreignKeys: {
29
- [key: string]: unknown;
30
- };
31
- init: () => void;
32
- isModel?: () => boolean;
33
- methods: {
34
- [key: string]: () => unknown;
35
- };
36
- modelName: string;
37
- parent?: Meta<Natural, E>;
38
- primaryKey: string;
39
- tableName: string;
40
- constructor(from: Meta<N, E>);
27
+ export declare class Type<N extends Natural, E> {
28
+ constructor(from: Type<N, E>);
41
29
  }
42
- export declare class Attribute<N extends Natural, E> extends Type<N, E> {
30
+ export interface Attribute<N extends Natural, E> extends Type<N, E> {
43
31
  attributeName: string;
44
32
  defaultValue?: unknown;
45
33
  fieldName: string;
@@ -47,6 +35,8 @@ export declare class Attribute<N extends Natural, E> extends Type<N, E> {
47
35
  notNull: boolean;
48
36
  tableName: string;
49
37
  unique?: boolean;
38
+ }
39
+ export declare class Attribute<N extends Natural, E> extends Type<N, E> {
50
40
  constructor(from: Attribute<N, E>);
51
41
  }
52
42
  export interface Constraint {
@@ -65,11 +55,11 @@ interface ITable {
65
55
  autoIncrement: boolean;
66
56
  constraints: Constraint[];
67
57
  indexes: Index[];
68
- parent: Meta<Natural, unknown>;
58
+ parent: any;
69
59
  sync: boolean;
70
60
  tableName: string;
71
61
  }
72
- declare const Table_base: new (defaults?: ITable) => ITable;
62
+ declare const Table_base: new (defaults?: ITable | undefined) => ITable;
73
63
  export declare class Table extends Table_base {
74
64
  autoIncrementOwn?: boolean;
75
65
  oid?: number;
@@ -77,7 +67,7 @@ export declare class Table extends Table_base {
77
67
  }
78
68
  export declare abstract class DB {
79
69
  tables: Table[];
80
- protected log: (...data: unknown[]) => void;
70
+ protected log: (message: string) => void;
81
71
  protected sync: boolean;
82
72
  abstract connect(): Promise<void>;
83
73
  abstract end(): Promise<void>;
@@ -85,7 +75,7 @@ export declare abstract class DB {
85
75
  findTable(name: string): Table;
86
76
  protected indexesEq(a: Index, b: Index): boolean;
87
77
  syncDataBase(): Promise<void>;
88
- protected syncLog(...data: unknown[]): void;
78
+ protected syncLog(message: string): void;
89
79
  abstract dropConstraints(table: Table): Promise<number[]>;
90
80
  abstract dropFields(table: Table): Promise<void>;
91
81
  abstract dropIndexes(table: Table, constraintIndexes: number[]): Promise<void>;
package/lib/db.js CHANGED
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DB = exports.Table = exports.Attribute = exports.Meta = exports.Type = exports.EntryBase = void 0;
4
- /**/
3
+ exports.DB = exports.Table = exports.Attribute = exports.Type = exports.EntryBase = void 0;
5
4
  class EntryBase {
5
+ construct() { }
6
+ postLoad() { }
7
+ preLoad() { }
8
+ preSave() { }
6
9
  async save() {
7
10
  return false;
8
11
  }
@@ -14,12 +17,6 @@ class Type {
14
17
  }
15
18
  }
16
19
  exports.Type = Type;
17
- class Meta extends Type {
18
- constructor(from) {
19
- super(from);
20
- }
21
- }
22
- exports.Meta = Meta;
23
20
  class Attribute extends Type {
24
21
  constructor(from) {
25
22
  super(from);
@@ -42,6 +39,7 @@ exports.Table = Table;
42
39
  class DB {
43
40
  constructor(log) {
44
41
  this.tables = [];
42
+ this.sync = true;
45
43
  this.log = log;
46
44
  }
47
45
  findTable(name) {
@@ -72,9 +70,8 @@ class DB {
72
70
  await this.syncIndexes(table);
73
71
  }
74
72
  }
75
- syncLog(...data) {
76
- const args = this.sync ? data : ["NOT SYNCING:", ...data];
77
- this.log(...args);
73
+ syncLog(message) {
74
+ this.log(this.sync ? message : "NOT SYNCING: " + message);
78
75
  }
79
76
  }
80
77
  exports.DB = DB;
package/lib/minidb.js CHANGED
@@ -16,7 +16,8 @@ class MiniDB extends db_1.DB {
16
16
  this.body = JSON.parse((await readFile(this.file)).toString());
17
17
  }
18
18
  catch (e) {
19
- if (e.code !== "ENOENT")
19
+ const err = e;
20
+ if (err.code !== "ENOENT")
20
21
  throw e;
21
22
  }
22
23
  }
@@ -0,0 +1,2 @@
1
+ export declare class Transaction {
2
+ }
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Transaction = void 0;
4
+ class Transaction {
5
+ }
6
+ exports.Transaction = Transaction;
package/package.json CHANGED
@@ -5,10 +5,10 @@
5
5
  "description": "The ORM which never needs to migrate",
6
6
  "devDependencies": {
7
7
  "@types/mocha": "9.0.0",
8
- "@types/node": "17.0.0",
8
+ "@types/node": "17.0.5",
9
9
  "@types/yamljs": "0.2.31",
10
- "@typescript-eslint/eslint-plugin": "5.7.0",
11
- "@typescript-eslint/parser": "5.7.0",
10
+ "@typescript-eslint/eslint-plugin": "5.8.1",
11
+ "@typescript-eslint/parser": "5.8.1",
12
12
  "eslint": "8.5.0",
13
13
  "mocha": "9.1.3",
14
14
  "nyc": "15.1.0",
@@ -58,9 +58,21 @@
58
58
  },
59
59
  "tsd": {
60
60
  "compilerOptions": {
61
- "strict": false
61
+ "alwaysStrict": true,
62
+ "declaration": true,
63
+ "esModuleInterop": true,
64
+ "module": "commonjs",
65
+ "noImplicitAny": true,
66
+ "noImplicitReturns": true,
67
+ "noImplicitThis": true,
68
+ "strict": true,
69
+ "strictBindCallApply": true,
70
+ "strictFunctionTypes": true,
71
+ "strictNullChecks": true,
72
+ "strictPropertyInitialization": true,
73
+ "target": "es2017"
62
74
  }
63
75
  },
64
76
  "types": "index.d.ts",
65
- "version": "0.0.19"
77
+ "version": "0.0.20"
66
78
  }
package/utils.d.ts ADDED
@@ -0,0 +1 @@
1
+ export {};
package/utils.js ADDED
@@ -0,0 +1,130 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const yamljs_1 = __importDefault(require("yamljs"));
7
+ const fs_1 = require("fs");
8
+ const { readFile, writeFile } = fs_1.promises;
9
+ const { VERSION, npm_package_name } = process.env;
10
+ const common = ["*.tgz", "coverage", "node_modules", "test.json", ""];
11
+ const git = [".gitignore", ".npmignore", ".nyc_output", "docs/build", "docs/__pycache__", "index.d.ts", "index.js", "lib/*.d.ts", "lib/*.js"];
12
+ const npm = [".*", "Makefile", "docs", "index.ts", "lib/db.ts", "lib/minidb.ts", "lib/transaction.ts", "sedentary-*", "test", "tsconfig.json", "utils.ts"];
13
+ const descriptions = { sedentary: "", "sedentary-mysql": " - MySQL", "sedentary-pg": " - PostgreSQL", "sedentary-sqlite": " - SQLite" };
14
+ const urls = { sedentary: "", "sedentary-mysql": "-mysql", "sedentary-pg": "-pg", "sedentary-sqlite": "-sqlite" };
15
+ const deps = { sedentary: {}, "sedentary-mysql": {}, "sedentary-pg": { pg: "8.7.1", "pg-format": "1.0.4" }, "sedentary-sqlite": {} };
16
+ const devd = { sedentary: {}, "sedentary-mysql": {}, "sedentary-pg": { "@types/pg": "8.6.3", "@types/pg-format": "1.0.2" }, "sedentary-sqlite": {} };
17
+ const packagejson = {
18
+ author: "Daniele Ricci <daniele.icc@gmail.com> (https://github.com/iccicci)",
19
+ dependencies: {},
20
+ devDependencies: {
21
+ "@types/mocha": "9.0.0",
22
+ "@types/node": "17.0.5",
23
+ "@types/yamljs": "0.2.31",
24
+ "@typescript-eslint/eslint-plugin": "5.8.1",
25
+ "@typescript-eslint/parser": "5.8.1",
26
+ eslint: "8.5.0",
27
+ mocha: "9.1.3",
28
+ prettier: "2.5.1",
29
+ nyc: "15.1.0",
30
+ "ts-node": "10.4.0",
31
+ tsd: "0.19.0",
32
+ typescript: "4.5.4",
33
+ yamljs: "0.3.0"
34
+ },
35
+ engines: { node: ">=12.0" },
36
+ funding: { url: "https://blockchain.info/address/1Md9WFAHrXTb3yPBwQWmUfv2RmzrtbHioB" },
37
+ keywords: ["DB", "ORM", "database", "migration", "mysql", "postgresql", "sqlite"],
38
+ license: "MIT",
39
+ prettier: {
40
+ arrowParens: "avoid",
41
+ endOfLine: "lf",
42
+ jsxBracketSameLine: true,
43
+ printWidth: 200,
44
+ trailingComma: "none",
45
+ useTabs: false
46
+ },
47
+ readmeFilename: "README.md",
48
+ scripts: {
49
+ coverage: "nyc -r lcov -r text -r text-summary -r html mocha -r ts-node/register test/*ts",
50
+ gitignore: "node -r ts-node/register utils.ts gitignore",
51
+ npmignore: "node -r ts-node/register utils.ts npmignore",
52
+ packagejson: "node -r ts-node/register utils.ts packagejson",
53
+ test: "mocha -r ts-node/register test/*ts",
54
+ travis: "node -r ts-node/register utils.ts travis",
55
+ tsc: "tsc --declaration",
56
+ version: "node -r ts-node/register utils.ts version"
57
+ },
58
+ tsd: { compilerOptions: {} },
59
+ types: "index.d.ts"
60
+ };
61
+ const before_script_common = [
62
+ "curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter",
63
+ "chmod +x ./cc-test-reporter",
64
+ "./cc-test-reporter before-build"
65
+ ];
66
+ const conditions = { sedentary: "", "sedentary-pg": "&& $PG_VERSION == 14 " };
67
+ const travis = {
68
+ common: {
69
+ after_script: [`if [[ \`node --version\` =~ ^v16 ${conditions[npm_package_name]}]] ; then ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT ; fi`],
70
+ before_script: before_script_common,
71
+ language: "node_js",
72
+ node_js: ["16", "14", "12"],
73
+ script: "npm run coverage",
74
+ sudo: "required"
75
+ },
76
+ sedentary: { env: { global: ["CC_TEST_REPORTER_ID=1aa1f737e7bf7d2859a2c7d9a0d9634a0d9aa89e3a19476d576faa7d02a1d46f"] } },
77
+ "sedentary-pg": {
78
+ before_install: ["sudo service postgresql stop", "sudo service postgresql restart $PG_VERSION"],
79
+ before_script: [
80
+ ...before_script_common,
81
+ 'psql -c "CREATE DATABASE sedentary;" -U postgres',
82
+ "psql -c \"ALTER DATABASE sedentary SET timezone TO 'GMT';\" -U postgres",
83
+ 'export SPG=\'{"database":"sedentary","password":"postgres","user":"postgres"}\''
84
+ ],
85
+ env: {
86
+ global: ["CC_TEST_REPORTER_ID=c7519657dfea145349c1b7a98f7134f033c25f598b40ad5b077744eb4beb7c66"],
87
+ matrix: ["PG_VERSION=14", "PG_VERSION=13", "PG_VERSION=12", "PG_VERSION=11", "PG_VERSION=10"]
88
+ }
89
+ }
90
+ };
91
+ function sort(obj) {
92
+ const ret = {};
93
+ if (obj instanceof Array || !(obj instanceof Object))
94
+ return obj;
95
+ Object.entries(obj)
96
+ .sort(([a], [b]) => (a < b ? -1 : 1))
97
+ .forEach(([k, v]) => (ret[k] = sort(v)));
98
+ return ret;
99
+ }
100
+ (async function () {
101
+ if (process.argv[2] === "gitignore")
102
+ writeFile(".gitignore", [...git, ...common].join("\n"), "utf-8");
103
+ if (process.argv[2] === "npmignore")
104
+ writeFile(".npmignore", [...npm, ...common].join("\n"), "utf-8");
105
+ if (process.argv[2] === "travis")
106
+ writeFile(".travis.yml", yamljs_1.default.stringify(sort(Object.assign(Object.assign({}, travis.common), travis[npm_package_name])), 4, 2), "utf-8");
107
+ if (process.argv[2] === "packagejson") {
108
+ const bugs = `https://github.com/iccicci/sedentary${urls[npm_package_name]}/issues`;
109
+ const description = "The ORM which never needs to migrate" + descriptions[npm_package_name];
110
+ const homepage = `https://github.com/iccicci/sedentary${urls[npm_package_name]}#readme`;
111
+ const repository = `https://github.com/iccicci/sedentary${urls[npm_package_name]}`;
112
+ const pkg = JSON.parse(await readFile("package.json", "utf-8"));
113
+ const { compilerOptions } = JSON.parse(await readFile("tsconfig.json", "utf-8"));
114
+ const { name, version } = pkg;
115
+ const tsd = { compilerOptions };
116
+ let { dependencies, devDependencies } = pkg;
117
+ try {
118
+ const { version } = JSON.parse(await readFile("../package.json", "utf-8"));
119
+ dependencies = Object.assign(Object.assign({}, deps[npm_package_name]), { sedentary: version });
120
+ devDependencies = Object.assign(Object.assign({}, devDependencies), devd[npm_package_name]);
121
+ }
122
+ catch (e) { }
123
+ await writeFile("package.json", JSON.stringify(sort(Object.assign(Object.assign({}, packagejson), { bugs, dependencies, devDependencies, description, homepage, name, repository, tsd, version })), null, 2), "utf-8");
124
+ }
125
+ if (process.argv[2] === "version") {
126
+ const pkg = JSON.parse(await readFile("package.json", "utf-8"));
127
+ pkg.version = VERSION;
128
+ await writeFile("package.json", JSON.stringify(pkg, null, 2), "utf-8");
129
+ }
130
+ })();
package/lib/log.d.ts DELETED
@@ -1,4 +0,0 @@
1
- export declare function createLogger(log: ((message: string) => void) | null | undefined): {
2
- (...data: any[]): void;
3
- (message?: any, ...optionalParams: any[]): void;
4
- };
package/lib/log.js DELETED
@@ -1,20 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createLogger = void 0;
4
- const console_1 = require("console");
5
- const stream_1 = require("stream");
6
- class Logger extends stream_1.Writable {
7
- constructor(log) {
8
- super();
9
- this.log = log;
10
- }
11
- _write(chunk, encoding, callback) {
12
- this.log(chunk.toString());
13
- callback();
14
- }
15
- }
16
- function createLogger(log) {
17
- // eslint-disable-next-line no-console
18
- return log ? new console_1.Console(new Logger(log)).log : log === null ? () => { } : console.log;
19
- }
20
- exports.createLogger = createLogger;
package/lib/log.ts DELETED
@@ -1,22 +0,0 @@
1
- import { Console } from "console";
2
- import { Writable } from "stream";
3
-
4
- class Logger extends Writable {
5
- private log: (message: string) => void;
6
-
7
- constructor(log: (message: string) => void) {
8
- super();
9
-
10
- this.log = log;
11
- }
12
-
13
- _write(chunk: Buffer, encoding: string, callback: () => void) {
14
- this.log(chunk.toString());
15
- callback();
16
- }
17
- }
18
-
19
- export function createLogger(log: ((message: string) => void) | null | undefined) {
20
- // eslint-disable-next-line no-console
21
- return log ? new Console(new Logger(log)).log : log === null ? () => {} : console.log;
22
- }