tspace-mysql 1.4.6 → 1.4.7

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
@@ -21,15 +21,17 @@ npm install tspace-mysql --save
21
21
  - [Backup](#backup)
22
22
  - [Generating Model Classes](#generating-model-classes)
23
23
  - [Model Conventions](#model-conventions)
24
- - [Relationships](#relationships)
25
- - [One To One](#one-to-one)
26
- - [One To Many](#one-to-many)
27
- - [Belongs To](#belongs-to)
28
- - [Many To Many](#many-to-many)
29
- - [Deeply Nested Relations](#deeply-nested-relations)
30
- - [Relation Exists](#relation-exists)
31
- - [Built in Relation Functions](#built-in-relation-functions)
32
- - [Schema Sync](#schema-sync)
24
+ - [Relationships](#relationships)
25
+ - [One To One](#one-to-one)
26
+ - [One To Many](#one-to-many)
27
+ - [Belongs To](#belongs-to)
28
+ - [Many To Many](#many-to-many)
29
+ - [Deeply Nested Relations](#deeply-nested-relations)
30
+ - [Relation Exists](#relation-exists)
31
+ - [Built in Relation Functions](#built-in-relation-functions)
32
+ - [Schema Model](#schema-model)
33
+ - [Validation](#validation)
34
+ - [Sync](#sync)
33
35
  - [Query Builder](#query-builder)
34
36
  - [Cli](#cli)
35
37
  - [Make Model](#make-model)
@@ -101,15 +103,24 @@ import { DB } from 'tspace-mysql'
101
103
  await new DB('users').findMany() // SELECT * FROM users => Array
102
104
  await new DB('users').findOne() // SELECT * FROM users LIMIT 1 => Object
103
105
  })()
106
+
107
+ ```
108
+ Running A Raw Query
109
+ ```js
110
+ const rawQuery = await new DB().query('SELECT * FROM users')
111
+
104
112
  ```
105
113
  Running A Select Query
106
114
  ```js
107
- const selectQuery = await new DB('users').select('id','username').findOne()
108
- // selectQuery => { id : 1, username : 'tspace'}
109
- const selectQueries = await new DB('users').select('id','username').findMany()
110
- // selectQueries => [{ id : 1, username : 'tspace' } , { id : 2, username : 'tspace2'}]
115
+ const select = await new DB('users').select('id','username').findOne()
116
+
117
+ const selectRaw = await new DB('users').selectRaw('COUNT(id)').findMany()
111
118
 
112
- const selectQueryRaw = await new DB('users').selectRaw('COUNT(id)').findMany()
119
+ const selectObject = await new DB('posts')
120
+ .join('posts.user_id', 'users.id')
121
+ .select('posts.*')
122
+ .selectObject({ id : 'users.id', name : 'users.name' , email : 'users.email'},'user')
123
+ .findOne()
113
124
 
114
125
  /**
115
126
  * @example except
@@ -137,10 +148,10 @@ await new DB('posts').rightJoin('posts.user_id' , 'users.id').findMany()
137
148
 
138
149
  Running A Where Query
139
150
  ```js
140
- const user = await new DB('users').where('id',1).findOne()
151
+ const whereEqual = await new DB('users').where('id',1).findOne()
141
152
  // SELECT * FROM `users` WHERE `users`.`id` = '1' LIMIT 1;
142
153
 
143
- const users = await new DB('users').where('id','!=',1).findMany()
154
+ const whereNotEqual = await new DB('users').where('id','!=',1).findMany()
144
155
  // SELECT * FROM `users` WHERE `users`.`id` != '1';
145
156
 
146
157
  const whereIn = await new DB('users').whereIn('id',[1,2]).findMany()
@@ -165,8 +176,14 @@ const whereQuery = await new DB('users').whereQuery(query => query.where('id',1)
165
176
  const whereExists = await new DB('users').whereExists(new DB('users').select('id').where('id',1).toString()).findOne()
166
177
  // SELECT * FROM `users` WHERE EXISTS (SELECT `id` FROM `users` WHERE id = 1) LIMIT 1;
167
178
 
168
- const whereJson= await new DB('users').whereJSON('json', { targetKey : 'id', value : '1234' }).findOne()
179
+ const whereJSON = await new DB('users').whereJSON('json', { key : 'id', value : '1234' }).findOne()
169
180
  // SELECT * FROM `users` WHERE `users`.`json`->>'$.id' = '1234' LIMIT 1;
181
+
182
+ const whereWhenIsTrue = await new DB('users').where('id',1).when(true, (query) => query.where('username','when is actived')).findOne()
183
+ // SELECT * FROM `users` WHERE `users`.`id` = '1' AND `users`.`username` = 'when is actived' LIMIT 1;
184
+
185
+ const whereWhenIsFalse = await new DB('users').where('id',1).when(false, (query) => query.where('username','when is actived')).findOne()
186
+ // SELECT * FROM `users` WHERE `users`.`id` = '1' LIMIT 1;
170
187
  ```
171
188
 
172
189
  Running A Hook Query
@@ -239,9 +256,10 @@ Running A Update Query
239
256
  const user = await new DB('users')
240
257
  .where('id',1)
241
258
  .update({
242
- name : 'tspace1**',
243
- email : 'tspace1@gmail.com'
244
- }).save()
259
+ name : 'tspace1**',
260
+ email : 'tspace1@gmail.com'
261
+ })
262
+ .save()
245
263
  // user => { id : 1 , username : 'tspace1**', email : 'tspace1@gmail.com'}
246
264
 
247
265
  +--------------------------------------------------------------------------+
@@ -420,7 +438,7 @@ class User extends Model {
420
438
  *
421
439
  * Assign setting global in your model
422
440
  * @useMethod
423
- *
441
+ * this.usePattern('camelCase') // => default 'snake_case'
424
442
  * this.useDebug()
425
443
  * this.usePrimaryKey('id')
426
444
  * this.useTimestamp({
@@ -430,8 +448,7 @@ class User extends Model {
430
448
  * this.useSoftDelete('deletedAt') // => default target to colmun deleted_at
431
449
  * this.useTable('users')
432
450
  * this.useTableSingular() // => 'user'
433
- * this.useTablePlural() // => 'users'
434
- * this.usePattern('camelCase') // => default 'snake_case'
451
+ * this.useTablePlural() // => 'users'
435
452
  * this.useUUID('uuid') // => runing a uuid (universally unique identifier) when insert new data
436
453
  * this.useRegistry() // => build-in functions registry
437
454
  * this.useLoadRelationsInRegistry() // => auto generated result from relationship to results
@@ -440,14 +457,34 @@ class User extends Model {
440
457
  * this.useSchema ({
441
458
  * id : new Blueprint().int().notNull().primary().autoIncrement(),
442
459
  * uuid : new Blueprint().varchar(50).null(),
443
- * user_id : new Blueprint().int().notNull(),
444
- * title : new Blueprint().varchar(255).null(),
460
+ * name : new Blueprint().varchar(191).notNull(),
461
+ * email : new Blueprint().varchar(191).notNull(),
445
462
  * created_at : new Blueprint().timestamp().null(),
446
463
  * updated_at : new Blueprint().timestamp().null(),
447
464
  * deleted_at : new Blueprint().timestamp().null()
448
465
  * }) // auto-generated table when table is not exists and auto-create column when column not exists
449
466
  *
450
- * this.useValidateSchema() // => validate type of value when return results reference to the schema in 'this.useSchema'
467
+ * // validate input when create or update reference to the schema in 'this.useSchema'
468
+ * this.useValidateSchema({
469
+ * id : Number,
470
+ * uuid : Number,
471
+ * name : {
472
+ * type : String,
473
+ * length : 191
474
+ * require : true
475
+ * },
476
+ * email : {
477
+ * type : String,
478
+ * require : true,
479
+ * length : 191,
480
+ * match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
481
+ * unique : true,
482
+ * fn : (email : string) => !/^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
483
+ * },
484
+ * created_at : Date,
485
+ * updated_at : Date,
486
+ * deleted_at : Date
487
+ * })
451
488
  */
452
489
 
453
490
 
@@ -686,7 +723,7 @@ await new User()
686
723
 
687
724
  ```
688
725
  ## Relation Exists
689
- Relationships can return only result is not empty in relations.
726
+ Relationships can return only result is not empty in relations (soft delete).
690
727
  let's example a exists in relations :
691
728
  ```js
692
729
  +-------------+--------------+----------------------------+--------------------+
@@ -823,10 +860,59 @@ for (const post of posts) {
823
860
  }
824
861
 
825
862
  ```
863
+ ## Schema Model
864
+ Define the schema of Model
865
+ let's example a validator model:
866
+
867
+ ## Validation
868
+ Validate the schema of Model
869
+ let's example a validator model:
870
+ ```js
871
+
872
+ class User extends Model {
873
+ constructor(){
874
+ super()
875
+ this.useCamelCase()
876
+ this.useSchema ({
877
+ id : new Blueprint().int().notNull().primary().autoIncrement(),
878
+ uuid : new Blueprint().varchar(50).null(),
879
+ name : new Blueprint().varchar(191).notNull(),
880
+ email : new Blueprint().varchar(191).notNull(),
881
+ createdAt : new Blueprint().timestamp().null(),
882
+ updatedAt : new Blueprint().timestamp().null(),
883
+ deletedAt : new Blueprint().timestamp().null()
884
+ })
885
+ // validate input when create or update reference to the schema in 'this.useSchema'
886
+ this.useValidateSchema({
887
+ id : Number,
888
+ uuid : Number,
889
+ name : {
890
+ type : String,
891
+ length : 191
892
+ require : true,
893
+ json : true
894
+ },
895
+ email : {
896
+ type : String,
897
+ require : true,
898
+ length : 191,
899
+ match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
900
+ unique : true,
901
+ fn : (email : string) => !/^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
902
+ },
903
+ createdAt : Date,
904
+ updatedAt : Date,
905
+ deletedAt : Date
906
+ })
907
+ }
908
+ }
826
909
 
827
- ## Schema Sync
828
- Sync schema to Models in your directory,
829
- Sync will check for create or update table or columns with useSchema in your models.
910
+ ```
911
+
912
+ ## Sync
913
+ Sync schema with Models setting in your directory,
914
+ Sync will check for create or update table columns and foreign keys,
915
+ Related by method 'useSchema' in your models.
830
916
  Let's examine a basic model sync class:
831
917
 
832
918
  ```js
@@ -840,43 +926,44 @@ Let's examine a basic model sync class:
840
926
  * - Models
841
927
  * - User.ts
842
928
  * - Post.ts
843
- *
844
- * // file User.ts
845
- * class User extends Model {
846
- * constructor(){
847
- * super()
848
- * this.hasMany({ name : 'posts' , model : Post })
849
- * this.useSchema ({
850
- * id : new Blueprint().int().notNull().primary().autoIncrement(),
851
- * uuid : new Blueprint().varchar(50).null(),
852
- * email : new Blueprint().int().notNull().unique(),
853
- * name : new Blueprint().varchar(255).null(),
854
- * created_at : new Blueprint().timestamp().null(),
855
- * updated_at : new Blueprint().timestamp().null(),
856
- * deleted_at : new Blueprint().timestamp().null()
857
- * })
858
- * }
859
- * }
860
- *
861
- * // file Post.ts
862
- * class Post extends Model {
863
- * constructor(){
864
- * super()
865
- * this.hasMany({ name : 'comments' , model : Comment })
866
- * this.belongsTo({ name : 'user' , model : User })
867
- * this.useSchema ({
868
- * id : new Blueprint().int().notNull().primary().autoIncrement(),
869
- * uuid : new Blueprint().varchar(50).null(),
870
- * user_id : new Blueprint().int().notNull(),
871
- * title : new Blueprint().varchar(255).null(),
872
- * created_at : new Blueprint().timestamp().null(),
873
- * updated_at : new Blueprint().timestamp().null(),
874
- * deleted_at : new Blueprint().timestamp().null()
875
- * })
876
- * }
877
- * }
878
- *
879
929
  */
930
+
931
+ // file User
932
+ class User extends Model {
933
+ constructor(){
934
+ super()
935
+ this.hasMany({ name : 'posts' , model : Post })
936
+ this.useSchema ({
937
+ id : new Blueprint().int().notNull().primary().autoIncrement(),
938
+ uuid : new Blueprint().varchar(50).null(),
939
+ email : new Blueprint().int().notNull().unique(),
940
+ name : new Blueprint().varchar(255).null(),
941
+ created_at : new Blueprint().timestamp().null(),
942
+ updated_at : new Blueprint().timestamp().null(),
943
+ deleted_at : new Blueprint().timestamp().null()
944
+ })
945
+ }
946
+ }
947
+
948
+ // file Post
949
+ import User from './User'
950
+ class Post extends Model {
951
+ constructor(){
952
+ super()
953
+ this.hasMany({ name : 'comments' , model : Comment })
954
+ this.belongsTo({ name : 'user' , model : User })
955
+ this.useSchema ({
956
+ id : new Blueprint().int().notNull().primary().autoIncrement(),
957
+ uuid : new Blueprint().varchar(50).null(),
958
+ user_id : new Blueprint().int().notNull()
959
+ .foreign({ references : 'id' , on : User ,onDelete : 'CASCADE' , onUpdate : 'CASCADE' }),
960
+ title : new Blueprint().varchar(255).null(),
961
+ created_at : new Blueprint().timestamp().null(),
962
+ updated_at : new Blueprint().timestamp().null(),
963
+ deleted_at : new Blueprint().timestamp().null()
964
+ })
965
+ }
966
+ }
880
967
  await Schema.sync(`src/Models` , { force : true })
881
968
 
882
969
  ```
@@ -903,6 +990,8 @@ orWhere(column , operator , value)
903
990
  orWhereRaw(sql)
904
991
  orWhereIn(column , [])
905
992
  orWhereSubQuery(colmn , rawSQL)
993
+ when(contition , callback)
994
+ if(contition , callback)
906
995
  select(column1 ,column2 ,...N)
907
996
  distinct()
908
997
  selectRaw(column1 ,column2 ,...N)
@@ -926,8 +1015,10 @@ groupByRaw (column)
926
1015
  create(objects)
927
1016
  createMultiple(array objects)
928
1017
  update (objects)
1018
+ updateMany (objects)
929
1019
  createNotExists(objects)
930
1020
  updateOrCreate (objects)
1021
+ onlyTrashed()
931
1022
  connection(options)
932
1023
  backup({ database , connection })
933
1024
  backupToFile({ filePath, database , connection })
@@ -971,8 +1062,8 @@ findMany()
971
1062
  findOne()
972
1063
  find(id)
973
1064
  delelte()
974
- exists ()
975
- onlyTrashed()
1065
+ delelteMany()
1066
+ exists()
976
1067
  toString()
977
1068
  toJSON()
978
1069
  toArray(column)
@@ -982,7 +1073,7 @@ avg(column)
982
1073
  max(column)
983
1074
  min(column)
984
1075
  pagination({ limit , page })
985
- save() /*for action statements insert update or delete */
1076
+ save() /* for actions statements insert or update */
986
1077
  ```
987
1078
 
988
1079
  ## Cli
@@ -1152,4 +1243,5 @@ primary()
1152
1243
  default(string)
1153
1244
  defaultTimestamp()
1154
1245
  autoIncrement()
1246
+ foreign({ references : <column> , on : <table or model>}),
1155
1247
  ```
@@ -14,7 +14,7 @@ class ${model} extends Model {
14
14
  * createdAt : 'created_at',
15
15
  * updatedAt : 'updated_at'
16
16
  * }) // runing a timestamp when insert or update
17
- * this.useSoftDelete('deletedAt') // => default target to colmun deleted_at
17
+ * this.useSoftDelete('deletedAt') // => default target to column deleted_at
18
18
  * this.usePattern('snake_case') // => default 'snake_case'
19
19
  * this.useUUID('uuid') // => runing a uuid (universally unique identifier) when insert new data
20
20
  * this.useRegistry() // => build-in functions registry
@@ -29,6 +29,6 @@ export declare class PoolConnection {
29
29
  * @property {Function} Connection.connection
30
30
  */
31
31
  declare const pool: Connection;
32
- export { pool as Pool };
33
32
  export { loadOptionsEnvironment };
33
+ export { pool as Pool };
34
34
  export default pool;
@@ -26,7 +26,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.loadOptionsEnvironment = exports.Pool = exports.PoolConnection = void 0;
29
+ exports.Pool = exports.loadOptionsEnvironment = exports.PoolConnection = void 0;
30
30
  const fs_1 = __importDefault(require("fs"));
31
31
  const path_1 = __importDefault(require("path"));
32
32
  const options_1 = __importStar(require("./options"));
@@ -5,9 +5,9 @@ const CONSTANTS = Object.freeze({
5
5
  ID: 'ID',
6
6
  SHOW: 'SHOW',
7
7
  BINARY: 'BINARY',
8
- SHOW_TABLES: 'SHOW TABLES',
9
8
  FIELDS: 'FIELDS',
10
9
  COLUMNS: 'COLUMNS',
10
+ TABLES: 'TABLES',
11
11
  WHERE: 'WHERE',
12
12
  BETWEEN: 'BETWEEN',
13
13
  NOT_BETWEEN: 'NOT BETWEEN',
@@ -18,7 +18,6 @@ const CONSTANTS = Object.freeze({
18
18
  OR: 'OR',
19
19
  LIKE: 'LIKE',
20
20
  SELECT: 'SELECT',
21
- SELECTED: '*',
22
21
  DISTINCT: 'DISTINCT',
23
22
  FROM: 'FROM',
24
23
  OFFSET: 'OFFSET',
@@ -71,6 +70,7 @@ const CONSTANTS = Object.freeze({
71
70
  ALTER_TABLE: 'ALTER TABLE',
72
71
  ADD: 'ADD',
73
72
  AFTER: 'AFTER',
73
+ JSON_OBJECT: 'JSON_OBJECT',
74
74
  RELATIONSHIP: {
75
75
  hasOne: 'hasOne',
76
76
  hasMany: 'hasMany',
@@ -94,13 +94,13 @@ const CONSTANTS = Object.freeze({
94
94
  DELETE: '',
95
95
  UPDATE: '',
96
96
  INSERT: '',
97
- SELECT: '',
97
+ SELECT: [],
98
98
  ONLY: [],
99
99
  EXCEPTS: [],
100
100
  CHUNK: 0,
101
101
  COUNT: '',
102
- FROM: '',
103
- JOIN: '',
102
+ FROM: 'FROM',
103
+ JOIN: [],
104
104
  WHERE: '',
105
105
  GROUP_BY: '',
106
106
  ORDER_BY: '',
@@ -119,7 +119,7 @@ const CONSTANTS = Object.freeze({
119
119
  MODEL: {
120
120
  PRIMARY_KEY: 'id',
121
121
  VOID: false,
122
- SELECT: '',
122
+ SELECT: [],
123
123
  DELETE: '',
124
124
  UPDATE: '',
125
125
  INSERT: '',
@@ -127,8 +127,8 @@ const CONSTANTS = Object.freeze({
127
127
  EXCEPTS: [],
128
128
  CHUNK: 0,
129
129
  COUNT: '',
130
- FROM: '',
131
- JOIN: '',
130
+ FROM: 'FROM',
131
+ JOIN: [],
132
132
  WHERE: '',
133
133
  GROUP_BY: '',
134
134
  ORDER_BY: '',
@@ -143,7 +143,6 @@ const CONSTANTS = Object.freeze({
143
143
  SOFT_DELETE: false,
144
144
  SOFT_DELETE_FORMAT: 'deleted_at',
145
145
  SOFT_DELETE_RELATIONS: false,
146
- RELATION: [],
147
146
  PAGE: 1,
148
147
  PER_PAGE: 1,
149
148
  REGISTRY: {},
@@ -153,6 +152,7 @@ const CONSTANTS = Object.freeze({
153
152
  PLUCK: '',
154
153
  SAVE: '',
155
154
  HOOKS: [],
155
+ RELATION: [],
156
156
  RELATIONS: [],
157
157
  RELATIONS_TRASHED: false,
158
158
  RELATIONS_EXISTS: false,
@@ -166,7 +166,9 @@ const CONSTANTS = Object.freeze({
166
166
  VALIDATE_SCHEMA_DEFINED: null,
167
167
  FUNCTION_RELATION: false,
168
168
  SCHEMA_TABLE: null,
169
- RETRY_QUERIES: 0
169
+ RETRY: 0,
170
+ OBSERVER: null,
171
+ DATA: null
170
172
  }
171
173
  });
172
174
  exports.CONSTANTS = CONSTANTS;
@@ -35,8 +35,8 @@ declare abstract class AbstractBuilder {
35
35
  abstract whereUser(id: number): this;
36
36
  abstract whereEmail(value: string): this;
37
37
  abstract whereQuery(callback: Function): this;
38
- abstract whereJSON(column: string, { targetKey, value, operator }: {
39
- targetKey: string;
38
+ abstract whereJSON(column: string, { key, value, operator }: {
39
+ key: string;
40
40
  value: string;
41
41
  operator: string;
42
42
  }): this;
@@ -70,6 +70,7 @@ declare abstract class AbstractBuilder {
70
70
  abstract insert(data: Record<string, any>): this;
71
71
  abstract create(data: Record<string, any>): this;
72
72
  abstract update(data: Record<string, any>, updateNotExists?: string[]): this;
73
+ abstract updateMany(data: Record<string, any>, updateNotExists?: string[]): this;
73
74
  abstract insertNotExists(data: Record<string, any>): this;
74
75
  abstract createNotExists(data: Record<string, any>): this;
75
76
  abstract insertOrUpdate(data: Record<string, any>): this;
@@ -111,6 +112,7 @@ declare abstract class AbstractBuilder {
111
112
  abstract min(column: string): Promise<number>;
112
113
  abstract rawQuery(sql: string): Promise<any[]>;
113
114
  abstract delete(): Promise<boolean>;
115
+ abstract deleteMany(): Promise<boolean>;
114
116
  abstract exists(): Promise<boolean>;
115
117
  abstract save(): Promise<Record<string, any> | any[] | null | undefined>;
116
118
  abstract increment(column: string, value: number): Promise<number>;
@@ -11,10 +11,14 @@ class AbstractBuilder {
11
11
  '$constants',
12
12
  '$pool',
13
13
  '$state',
14
+ '$relation'
14
15
  ];
15
16
  this.$utils = {};
16
17
  this.$constants = (name) => { };
17
- this.$state = new StateHandler_1.StateHandler({});
18
+ this.$state = new StateHandler_1.StateHandler({
19
+ state: {},
20
+ constants: {}
21
+ });
18
22
  this.$pool = {
19
23
  query: (sql) => { },
20
24
  set: (pool) => { },
@@ -3,8 +3,6 @@ import { Connection, ConnectionOptions } from '../Interface';
3
3
  declare abstract class AbstractDB extends Builder {
4
4
  abstract table(name: string): void;
5
5
  abstract beginTransaction(): Promise<any>;
6
- abstract makeObject(value: any): Record<string, any> | null;
7
- abstract makeArray(value: any): Array<any>;
8
6
  abstract generateUUID(): string;
9
7
  abstract raw(sql: string): string;
10
8
  abstract constants(constants?: string): string | Record<string, any>;
@@ -1,6 +1,8 @@
1
1
  import { Relation, RelationQuery } from '../Interface';
2
- import Builder from '../Builder';
2
+ import { Builder } from '../Builder';
3
+ import { RelationHandler } from '../RelationHandler';
3
4
  declare abstract class AbstractModel extends Builder {
5
+ protected $relation: RelationHandler | undefined;
4
6
  protected abstract useUUID(): this;
5
7
  protected abstract usePrimaryKey(primaryKey: string): this;
6
8
  protected abstract useRegistry(): this;
@@ -23,12 +25,12 @@ declare abstract class AbstractModel extends Builder {
23
25
  protected abstract hasOneBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
24
26
  protected abstract hasManyBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
25
27
  protected abstract belongsToBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
26
- protected abstract belongsToManyBuilder({ name, model, localKey, foreignKey, freezeTable, as }: RelationQuery, callback: Function): this;
28
+ protected abstract belongsToManyBuilder({ name, model, localKey, foreignKey, freezeTable, as, pivot }: RelationQuery, callback: Function): this;
27
29
  abstract ignoreSoftDelete(): this;
28
30
  abstract disableSoftDelete(): this;
29
31
  abstract registry(func: Record<string, Function>): this;
30
- abstract onlyTrashed(): Promise<any[]>;
31
- abstract trashed(): Promise<any[]>;
32
+ abstract onlyTrashed(): this;
33
+ abstract trashed(): this;
32
34
  abstract restore(): Promise<any[]>;
33
35
  abstract with(...nameRelations: string[]): this;
34
36
  abstract withQuery(nameRelations: string, callback: Function): this;
@@ -1,11 +1,8 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.AbstractModel = void 0;
7
- const Builder_1 = __importDefault(require("../Builder"));
8
- class AbstractModel extends Builder_1.default {
4
+ const Builder_1 = require("../Builder");
5
+ class AbstractModel extends Builder_1.Builder {
9
6
  }
10
7
  exports.AbstractModel = AbstractModel;
11
8
  exports.default = AbstractModel;
@@ -1,3 +1,4 @@
1
+ import { Model } from "./Model";
1
2
  /**
2
3
  * Make schema for table with Blueprint
3
4
  * @example
@@ -15,13 +16,14 @@
15
16
  */
16
17
  declare class Blueprint {
17
18
  protected type: string;
18
- protected attributes: Array<string>;
19
+ protected attributes: string[];
20
+ protected foreignKey: Record<string, any> | null;
19
21
  protected valueType: NumberConstructor | StringConstructor | DateConstructor;
20
22
  /**
21
23
  * Assign type 'int' in table
22
24
  * @return {this} this
23
25
  */
24
- int(number?: number): this;
26
+ int(_?: number): this;
25
27
  /**
26
28
  * Assign type 'TINYINT' in table
27
29
  * @param {number} number
@@ -192,6 +194,12 @@ declare class Blueprint {
192
194
  * @return {this} this
193
195
  */
194
196
  autoincrement(): this;
197
+ foreign({ references, on, onDelete, onUpdate }: {
198
+ references?: string;
199
+ on: (new () => Model) | string;
200
+ onDelete?: 'CASCADE' | 'NO ACTION' | 'RESTRICT' | 'SET NULL';
201
+ onUpdate?: 'CASCADE' | 'NO ACTION' | 'RESTRICT' | 'SET NULL';
202
+ }): this;
195
203
  private _addAssignType;
196
204
  private _addAssignAttribute;
197
205
  }
@@ -20,13 +20,14 @@ class Blueprint {
20
20
  constructor() {
21
21
  this.type = 'INT';
22
22
  this.attributes = [];
23
+ this.foreignKey = null;
23
24
  this.valueType = String;
24
25
  }
25
26
  /**
26
27
  * Assign type 'int' in table
27
28
  * @return {this} this
28
29
  */
29
- int(number) {
30
+ int(_) {
30
31
  this._addAssignType('INT');
31
32
  this.valueType = Number;
32
33
  return this;
@@ -314,6 +315,15 @@ class Blueprint {
314
315
  this._addAssignAttribute(`AUTO_INCREMENT`);
315
316
  return this;
316
317
  }
318
+ foreign({ references, on, onDelete, onUpdate }) {
319
+ this.foreignKey = {
320
+ references: references == null ? 'id' : references,
321
+ on: typeof on === 'string' ? on : new on(),
322
+ onDelete: onDelete == null ? 'CASCADE' : onDelete,
323
+ onUpdate: onUpdate == null ? 'CASCADE' : onUpdate
324
+ };
325
+ return this;
326
+ }
317
327
  _addAssignType(type) {
318
328
  this.type = type;
319
329
  return this;