tspace-mysql 1.1.0 → 1.1.2

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
@@ -1,679 +1,613 @@
1
- ## tspace-mysql
2
-
3
- [![NPM version](https://img.shields.io/npm/v/tspace-mysql.svg)](https://www.npmjs.com)
4
- [![NPM downloads](https://img.shields.io/npm/dm/tspace-mysql.svg)](https://www.npmjs.com)
5
-
6
- TspaceMySQL is an ORM that can run in NodeJs and can be used with TypeScript.
7
- The goal is to always support the latest TypeScript and JavaScript features and provide additional features that help you to develop.
8
-
9
- ## Install
10
-
11
- Install with [npm](https://www.npmjs.com/):
12
-
13
- ```sh
14
- npm install tspace-mysql --save
15
- ```
16
- ## Basic Usage
17
- - [Install](#install)
18
- - [Configuration](#configuration)
19
- - [Running Queries](#running-queryies)
20
- - [Database Transactions](#database-transactions)
21
- - [Connection](#connection)
22
- - [Backup](#backup)
23
- - [Generating Model Classes](#generating-model-classes)
24
- - [Model Conventions](#model-conventions)
25
- - [Relationships](#relationships)
26
- - [One To One](#one-to-one)
27
- - [One To Many](#one-to-many)
28
- - [Belongs To](#belongs-to)
29
- - [Many To Many](#many-to-many)
30
- - [Deep Relationships](#deep-relationships)
31
- - [Query Builder](#query-builder)
32
- - [Cli](#cli)
33
- - [Make Model](#make-model)
34
- - [Make Migration](#make-migration)
35
- - [Migrate](#migrate)
36
- - [Blueprint](#blueprint)
37
- - [Types](#types)
38
- - [Attrbuites](#attrbuites)
39
-
40
- ## Configuration
41
- Created your environment variables is to use a .env file, you may establish a connection is this:
42
-
43
- ```js
44
- DB_HOST = localhost
45
- DB_PORT = 3306
46
- DB_USERNAME = root
47
- DB_PASSWORD = password
48
- DB_DATABASE = database
49
- ```
50
- ## Running Queries
51
- Once you have configured your database connection, you may run queries is this :
52
-
53
- ```js
54
-
55
- +-------------+--------------+----------------------------+
56
- | table users |
57
- +-------------+--------------+----------------------------+
58
- | id | username | email |
59
- |-------------|--------------|----------------------------|
60
- | 1 | tspace | tspace@gmail.com |
61
- | 2 | tspace2 | tspace2@gmail.com |
62
- +-------------+--------------+----------------------------+
63
-
64
- import { DB } from 'tspace-mysql'
65
- (async () => {
66
- await new DB('users').findMany() // SELECT * FROM users => Array
67
- await new DB('users').findOne() // SELECT * FROM users LIMIT 1 => Object
68
- })()
69
- ```
70
-
71
- Running A Select Query
72
-
73
- ```js
74
- const selectQuery = await new DB('users').select('id','username').findOne()
75
- // selectQuery => { id : 1, username : 'tspace'}
76
- const selectQueries = await new DB('users').select('id','username').findMany()
77
- // selectQueries => [{ id : 1, username : 'tspace' } , { id : 2, username : 'tspace2'}]
78
- ```
79
-
80
- Running A Where Query
81
-
82
- ```js
83
- const user = await new DB('users').where('id',1).findOne()
84
- // user => { id : 1 , username : 'tspace', email : 'tspace@gmail.com'}
85
- const users = await new DB('users').where('id','!=',1).findMany()
86
- // users => [{ id : 2 , username : 'tspace2' , email : 'tspace2@gmail.com' }]
87
- ```
88
- Running A Insert Query
89
-
90
- ```js
91
- const user = await new DB('users').create({
92
- name : 'tspace3',
93
- email : 'tspace3@gmail.com'
94
- }).save()
95
- // user => { id : 3 , username : 'tspace3', email : 'tspace3@gmail.com'}
96
-
97
- +--------------------------------------------------------------------------+
98
-
99
- const reposity = new DB('users')
100
- reposity.name = 'tspace4'
101
- reposity.email = 'tspace4@gmail.com'
102
- await reposity.save()
103
- const { result } = reposity
104
- // result => { id : 4 , username : 'tspace4', email : 'tspace4@gmail.com'}
105
- ```
106
- Running A Update Query
107
-
108
- ```js
109
- const user = await new DB('users').where('id',1)
110
- .update({
111
- name : 'tspace1**',
112
- email : 'tspace1@gmail.com'
113
- }).save()
114
- // user => { id : 1 , username : 'tspace1**', email : 'tspace1@gmail.com'}
115
-
116
- +--------------------------------------------------------------------------+
117
-
118
- const reposity = new DB('users').where('id',1)
119
- reposity.name = 'tspace1++'
120
- reposity.email = 'tspace1++@gmail.com'
121
- await reposity.save()
122
- const { result } = reposity
123
- // result => { id : 1 , username : 'tspace1++', email : 'tspace1++@gmail.com'}
124
- ```
125
- Running A Delete Query
126
-
127
- ```js
128
- const deleted = await new DB('users').where('id',1).delete()
129
- // deleted => true
130
- ```
131
- ## Database Transactions
132
-
133
- Within a database transaction, you may use the:
134
-
135
- ```js
136
- const transaction = await new DB().beginTransaction()
137
- try {
138
- const user = await new DB('users').create({
139
- name : 'tspace5',
140
- email : 'tspace5@gmail.com'
141
- })
142
- .save(transaction)
143
- // user => { id : 5 , username : 'tspace5', email : 'tspace5@gmail.com'}
144
-
145
- const userSecond = await new DB('users').create({
146
- name : 'tspace6',
147
- email : 'tspace6@gmail.com'
148
- })
149
- .save(transaction)
150
- // userSecond => { id : 6 , username : 'tspace6', email : 'tspace6@gmail.com'}
151
-
152
- throw new Error('try to using transaction')
153
-
154
- } catch (err) {
155
- const rollback = await transaction.rollback()
156
- // rollback => true
157
- // * rollback data user, userSecond in your database
158
- }
159
- ```
160
-
161
- ## Connection
162
- When establishing a connection, you may establish options is this:
163
-
164
- ```js
165
- const users = await new DB('users')
166
- .connection({
167
- host : 'localhost..',
168
- port : 3306,
169
- database : 'database'
170
- username : 'username',
171
- password : 'password',
172
- })
173
- .findMany()
174
- // users => [{ .... }]
175
- ```
176
-
177
- ## Backup
178
- Backup database, you may backup is this:
179
-
180
- ```js
181
- /**
182
- * @param {string} database created new database
183
- * @param {object?} connection [connection=defalut current connection]
184
- */
185
- const backup = await new DB().backup({
186
- database: 'try-to-backup',
187
- connection : {
188
- host : 'localhost..',
189
- port : 3306,
190
- database : 'database'
191
- username : 'username',
192
- password : 'password',
193
- }
194
- })
195
- /**
196
- * @param {string} database new database
197
- * @param {object?} connection [connection=defalut current connection]
198
- */
199
- const backupToFile = await new DB().backupToFile({
200
- database: 'try-to-backup',
201
- filePath: 'backup.sql',
202
- connection : {
203
- host : 'localhost..',
204
- port : 3306,
205
- database : 'database'
206
- username : 'username',
207
- password : 'password',
208
- }
209
- })
210
- // backupToFile => backup.sql
211
- ```
212
-
213
- ## Generating Model Classes
214
- To get started, let's install npm install tspace-mysql -g
215
- you may use the make:model command to generate a new model:
216
-
217
- ```sh
218
- npm install tspace-mysql -g
219
- tspace-mysql make:model <model name> --dir=<directory>
220
-
221
- # tspace-mysql make:model User --dir=App/Models
222
- # => App/Models/User.ts
223
- ```
224
- ## Model Conventions
225
- Models generated by the make:model command will be placed in the specific directory.
226
- Let's examine a basic model class:
227
-
228
- ```js
229
- import { Model } from 'tspace-mysql'
230
- class User extends Model {
231
- constructor(){
232
- super()
233
- /**
234
- * The "snake case", plural name of the class will be used as the table name // => users
235
- *
236
- * Assign setting global in your model
237
- * @useMethod
238
- *
239
- * this.useDebug() // => runing a uuid (universally unique identifier) when insert new data
240
- * this.usePrimaryKey('id') // => runing a uuid (universally unique identifier) when insert new data
241
- * this.useTimestamp({ createdAt : 'created_at' , updatedAt : 'updated_at' }) // runing a timestamp when insert or update
242
- * this.useSoftDelete()
243
- * this.useDisableSoftDeleteInRelations()
244
- * this.useTable('users')
245
- * this.useTableSingular()
246
- * this.useTablePlural()
247
- * this.usePattern('snake_case')
248
- * this.useUUID('uuid')
249
- * this.useRegistry()
250
- */
251
- }
252
- }
253
- export { User }
254
- export default User
255
- ```
256
- ## Relationships
257
- Relationships are defined as methods on your Model classes.
258
- Let's examine a basic relations :
259
-
260
- ## One To One
261
- A one-to-one relationship is used to define relationships where a single model is the parent to one child models
262
- ```js
263
- import { Model } from 'tspace-mysql'
264
- import Phone from '../Phone'
265
- class User extends Model {
266
- constructor(){
267
- super()
268
- this.useTimestamp()
269
- /**
270
- *
271
- * @hasOne Get the phone associated with the user.
272
- * @relationship users.id -> phones.user_id
273
- */
274
- this.hasOne({ name : 'phone' , model : Phone })
275
- }
276
- /**
277
- * @hasOneQuery Get the phone associated with the user. using function callback
278
- * @function
279
- */
280
- phone (callback ?: Function) {
281
- return this.hasOneQuery({ model : Phone }, (query) => {
282
- return callback ? callback(query) : query
283
- })
284
- }
285
- }
286
- export default User
287
-
288
- +--------------------------------------------------------------------------+
289
-
290
- import User from '../User'
291
- const user = await new User().with('brand').findOne()
292
- // user?.phone => {...}
293
- const userUsingFunction = await new User().phone().findOne()
294
- // userUsingFunction?.phone => {...}
295
- ```
296
-
297
- ## One To Many
298
- A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models.
299
-
300
- ```js
301
- import { Model } from 'tspace-mysql'
302
- import Comment from '../Comment'
303
- class Post extends Model {
304
- constructor(){
305
- super()
306
- this.useTimestamp()
307
- /**
308
- *
309
- * @hasMany Get the comments for the post.
310
- * @relationship posts.id -> comments.post_id
311
- */
312
- this.hasMany({ name : 'comments' , model : Comment })
313
- }
314
- /**
315
- * @hasManyQuery Get the comments for the post. using function callback
316
- * @function
317
- */
318
- comments (callback ?: Function) {
319
- return this.hasManyQuery({ model : Comment }, (query) => {
320
- return callback ? callback(query) : query
321
- })
322
- }
323
- }
324
- export default Post
325
-
326
- +--------------------------------------------------------------------------+
327
-
328
- import Post from '../Post'
329
- const posts = await new Post().with('comments').findOne()
330
- // posts?.comments => [{...}]
331
- const postsUsingFunction = await new Post().comments().findOne()
332
- // postsUsingFunction?.comments => [{...}]
333
- ```
334
-
335
- ## Belongs To
336
- ```js
337
- import { Model } from 'tspace-mysql'
338
- import User from '../User'
339
- class Phone extends Model {
340
- constructor(){
341
- super()
342
- this.useTimestamp()
343
- /**
344
- *
345
- * @belongsTo Get the user that owns the phone.
346
- * @relationship phones.user_id -> users.id
347
- */
348
- this.belognsTo({ name : 'user' , model : User })
349
- }
350
- /**
351
- * @belongsToQuery Get the user that owns the phone.. using function callback
352
- * @function
353
- */
354
- user (callback ?: Function) {
355
- return this.belongsToQuery({ model : User }, (query) => {
356
- return callback ? callback(query) : query
357
- })
358
- }
359
- }
360
- export default Phone
361
-
362
- +--------------------------------------------------------------------------+
363
-
364
- import Phone from '../Phone'
365
- const phone = await new Phone().with('user').findOne()
366
- // phone?.user => {...}
367
- const phoneUsingFunction = await new Phone().user().findOne()
368
- // phoneUsingFunction?.user => {...}
369
- ```
370
-
371
- ## Many To Many
372
- Many-to-many relationships are slightly more complicated than hasOne and hasMany relationships.
373
-
374
- ```js
375
- import { Model } from 'tspace-mysql'
376
- import Role from '../Role'
377
- class User extends Model {
378
- constructor(){
379
- super()
380
- this.useTimestamp()
381
- /**
382
- *
383
- * @belongsToMany Get The roles that belong to the user.
384
- * @relationship users.id , roles.id => role_user.user_id , role_user.role_id
385
- */
386
- this.belognsToMany({ name : 'roles' , model : Role })
387
- }
388
- /**
389
- * @belongsToQuery Get the user that owns the phone.. using function callback
390
- * @function
391
- */
392
- roles (callback ?: Function) {
393
- return this.belongsToManyQuery({ model : Role }, (query) => {
394
- return callback ? callback(query) : query
395
- })
396
- }
397
- }
398
- export default User
399
-
400
- +--------------------------------------------------------------------------+
401
-
402
- import User from '../User'
403
- const user = await new User().with('roles').findOne()
404
- // user?.roles => [{...}]
405
- const userUsingFunction = await new User().roles().findOne()
406
- // user?.roles => [{...}]
407
- ```
408
-
409
- ## Deep Relationships
410
- Deep Relationships using methods on your child Model classes.
411
- Let's examine a basic relations :
412
-
413
- ```js
414
- import { Model } from 'tspace-mysql'
415
- import Post from '../Post'
416
- class User extends Model {
417
- constructor(){
418
- super()
419
- this.hasMany({ name : 'posts' , model : Post })
420
- }
421
- }
422
- export default User
423
-
424
- +--------------------------------------------------------------------------+
425
-
426
- import { Model } from 'tspace-mysql'
427
- import User from '../User'
428
- class Comment extends Model {
429
- constructor(){
430
- super()
431
- this.belongsTo({ name : 'user' , model : User })
432
- }
433
- }
434
- export default Comment
435
-
436
- +--------------------------------------------------------------------------+
437
-
438
- import { Model } from 'tspace-mysql'
439
- import Comment from '../Comment'
440
- class Post extends Model {
441
- constructor(){
442
- super()
443
- this.hasMany({ name : 'comments' , model : Comment })
444
- }
445
- }
446
- export default Post
447
-
448
- +--------------------------------------------------------------------------+
449
-
450
- import Post from '../Post'
451
- const post = await new Post()
452
- .with('comments','user') // => has many comments in posts , => write by user ...
453
- .withQuery('comments',(query) => {
454
- /**
455
- *
456
- * @callback query registry in Comment classes
457
- */
458
- return query
459
- .with('user') // relation this comment by user?
460
- .withQuery('user' , (query) => {
461
- return query
462
- .with('posts') // relation this user has many posts ...
463
- })
464
- })
465
- .findOne()
466
- /* post => {
467
- * ....post details,
468
- * comments : [
469
- * {
470
- * ...comment details,
471
- * user : {
472
- * ...user detils
473
- * posts : [{ ...post details }]
474
- * }
475
- * }
476
- * ],
477
- * user : { ...user detils }
478
- * }
479
- */
480
- ```
481
-
482
- ## Query Builder
483
- Method chaining for queries
484
- ```js
485
- where(column , operator , value)
486
- whereSensitive(column , operator , value)
487
- whereId(id)
488
- whereUser(userId)
489
- whereEmail(value)
490
- orWhere(column , operator , value)
491
- whereIn(column , [])
492
- whereNotIn(column , [])
493
- whereNull(column)
494
- whereNotNull(column)
495
- whereBetween (column , [value1 , value2])
496
- whereSubQuery(colmn , rawSQL)
497
- select(column1 ,column2 ,...N)
498
- except(column1 ,column2 ,...N)
499
- only(column1 ,column2 ,...N)
500
- hidden(column1 ,column2 ,...N)
501
- join(primary key , table.foreign key)
502
- rightJoin (primary key , table.foreign key)
503
- leftJoin (primary key , table.foreign key)
504
- limit (limit)
505
- orderBy (column ,'ASC' || 'DSCE')
506
- having (condition)
507
- latest (column)
508
- oldest (column)
509
- groupBy (column)
510
- create(objects)
511
- createMultiple(array objects)
512
- update (objects)
513
- createNotExists(objects)
514
- updateOrCreate (objects)
515
- connection(options)
516
- backup({ database , connection })
517
- backupToFile({ filePath, database , connection })
518
-
519
- /**
520
- * registry relation in your models
521
- * @relationship
522
- * @param {string} relation.name
523
- * @param {class} relation.model
524
- * @param {string?} relation.as
525
- * @param {string?} relation.localKey
526
- * @param {string?} relation.foreignKey
527
- * @param {string?} relation.freezeTable
528
- */
529
- hasOne({ name , model , localKey , foreignKey , freezeTable , as })
530
- hasMany({ name , model , localKey , foreignKey , freezeTable , as })
531
- belongsTo({ name , model , localKey , foreignKey , freezeTable , as })
532
- belongsToMany({ name , model , localKey , foreignKey , freezeTable , as })
533
- /**
534
- * @relation using registry lists in your models
535
- */
536
- with(name1 , name2,...nameN)
537
- /**
538
- * @relation using registry in your models. if exists child data remove this parent data
539
- */
540
- withExists(name1 , name2,...nameN)
541
- /**
542
- * @relation call name relation in registry, callback query this relation
543
- */
544
- withQuery('relation registry',(callback query))
545
-
546
- /**
547
- * queries statements
548
- * @exec statements
549
- */
550
- findMany()
551
- findOne()
552
- findOneOrError(message , options?)
553
- find(id)
554
- delelte()
555
- exists ()
556
- onlyTrashed()
557
- toSQL()
558
- toString()
559
- toJSON()
560
- toArray(column)
561
- count(column)
562
- sum(column)
563
- avg(column)
564
- max(column)
565
- min(column)
566
- pagination({ limit , page })
567
- save() /*for action statements insert update or delete */
568
- ```
569
-
570
- ## Cli
571
- To get started, let's install npm install tspace-mysql -g
572
- you may use a basic cli :
573
-
574
- ## Make Model
575
- Command will be placed Model in the specific directory
576
- ```sh
577
- tspace-mysql make:model <MODEL NAME> --m --dir=.... --type=....
578
- /**
579
- * @options
580
- * --m // created scheme table for migrate
581
- * --dir=directory // created model in directory
582
- * --type=js // extension js default ts
583
- */
584
-
585
- tspace-mysql make:model User --m --dir=app/Models
586
- // =>
587
- - node_modules
588
- - app
589
- - Models
590
- User.ts
591
- */
592
- ```
593
-
594
- ## Make Migration
595
- Command will be placed Migration in the specific directory
596
- ```sh
597
- tspace-mysql make:migration <TABLE NAME>
598
- /**
599
- * @options
600
- * --type=js /* extension js default ts */
601
- * --dir=directory /* created table in directory */
602
- */
603
- tspace-mysql make:migration users --dir=app/Models/Migrations
604
- // =>
605
- - node_modules
606
- - app
607
- - Models
608
- - Migrations
609
- create_users_table.ts
610
- User.ts
611
- */
612
- ```
613
- ## Migrate
614
- ```sh
615
- tspace-mysql migrate <FOLDER> --type=...
616
- /**
617
- * @options
618
- *--type=js /* extension js default ts */
619
- *--dir=directory /* find migrate in directory */
620
- */
621
-
622
- tspace-mysql migrate --dir=App/Models/Migrations
623
- // => migrate all schema table in folder into database
624
- ```
625
-
626
- ## Blueprint
627
- Schema table created by command make:migration. you may use the:
628
- ```js
629
- import { Schema , Blueprint , DB } from 'tspace-mysql'
630
- (async () => {
631
- await new Schema().table('users',{
632
- id : new Blueprint().int().notNull().primary().autoIncrement(),
633
- name : new Blueprint().varchar(120).default('my name'),
634
- email : new Blueprint().varchar(255).unique(),
635
- email_verify : new Blueprint().tinyInt(),
636
- password : new Blueprint().varchar(255),
637
- created_at : new Blueprint().null().timestamp(),
638
- updated_at : new Blueprint().null().timestamp()
639
- })
640
- /**
641
- *
642
- * @Faker fake data 5 raw
643
- * await new DB().table('users').faker(5)
644
- */
645
- })()
646
- ```
647
-
648
- ## Types
649
-
650
- ```js
651
- int ()
652
- tinyInt (number)
653
- bigInt (number)
654
- double ()
655
- float ()
656
- varchar (number)
657
- char (number)
658
- longText()
659
- mediumText()
660
- tinyText()
661
- text()
662
- enum(...n)
663
- date()
664
- dateTime()
665
- timestamp()
666
- ```
667
-
668
- ## Attrbuites
669
-
670
- ```js
671
- unsigned ()
672
- unique ()
673
- null ()
674
- notNull ()
675
- primary()
676
- default(string)
677
- defaultTimestamp()
678
- autoIncrement()
1
+ ## tspace-mysql
2
+
3
+ [![NPM version](https://img.shields.io/npm/v/tspace-mysql.svg)](https://www.npmjs.com)
4
+ [![NPM downloads](https://img.shields.io/npm/dm/tspace-mysql.svg)](https://www.npmjs.com)
5
+
6
+ tspace-mysql is an ORM that can run in NodeJs and can be used with TypeScript.
7
+ Its always support the latest TypeScript and JavaScript features and provide additional features that help you to develop.
8
+
9
+ ## Install
10
+
11
+ Install with [npm](https://www.npmjs.com/):
12
+
13
+ ```sh
14
+ npm install tspace-mysql --save
15
+ ```
16
+ ## Basic Usage
17
+ - [Configuration](#configuration)
18
+ - [Running Queries](#running-queryies)
19
+ - [Database Transactions](#database-transactions)
20
+ - [Connection](#connection)
21
+ - [Backup](#backup)
22
+ - [Generating Model Classes](#generating-model-classes)
23
+ - [Model Conventions](#model-conventions)
24
+ - [Relationships](#relationships)
25
+ - [One To One](#one-to-one)
26
+ - [One To Many](#one-to-many)
27
+ - [One To One & One To Many (Inverse) / Belongs To](#inverse-belongs-to)
28
+ - [Many To Many](#many-to-many)
29
+ - [Query Builder](#query-builder)
30
+ - [Cli](#cli)
31
+ - [Make Model](#make-model)
32
+ - [Make Migration](#make-migration)
33
+ - [Migrate](#migrate)
34
+ - [Blueprint](#blueprint)
35
+
36
+ ## Configuration
37
+ Created your environment variables is to use a .env file, you may establish a connection is this:
38
+ ```js
39
+ DB_HOST = localhost
40
+ DB_PORT = 3306
41
+ DB_USERNAME = root
42
+ DB_PASSWORD = password
43
+ DB_DATABASE = database
44
+ ```
45
+ ## Running Queries
46
+ Once you have configured your database connection, you may run queries is this :
47
+ ```js
48
+ +-------------+--------------+----------------------------+
49
+ | table users |
50
+ +-------------+--------------+----------------------------+
51
+ | id | username | email |
52
+ |-------------|--------------|----------------------------|
53
+ | 1 | tspace | tspace@gmail.com |
54
+ | 2 | tspace2 | tspace2@gmail.com |
55
+ +-------------+--------------+----------------------------+
56
+
57
+ import { DB } from 'tspace-mysql'
58
+ (async () => {
59
+ await new DB('users').findMany() // SELECT * FROM users => Array
60
+ await new DB('users').findOne() // SELECT * FROM users LIMIT 1 => Object
61
+ })()
62
+ ```
63
+ Running A Select Query
64
+ ```js
65
+ const selectQuery = await new DB('users').select('id','username').findOne()
66
+ // selectQuery => { id : 1, username : 'tspace'}
67
+ const selectQueries = await new DB('users').select('id','username').findMany()
68
+ // selectQueries => [{ id : 1, username : 'tspace' } , { id : 2, username : 'tspace2'}]
69
+ ```
70
+ Running A Where Query
71
+ ```js
72
+ const user = await new DB('users').where('id',1).findOne()
73
+ // user => { id : 1 , username : 'tspace', email : 'tspace@gmail.com'}
74
+ const users = await new DB('users').where('id','!=',1).findMany()
75
+ // users => [{ id : 2 , username : 'tspace2' , email : 'tspace2@gmail.com' }]
76
+ ```
77
+ Running A Insert Query
78
+ ```js
79
+ const user = await new DB('users')
80
+ .create({
81
+ name : 'tspace3',
82
+ email : 'tspace3@gmail.com'
83
+ }).save()
84
+ // user => { id : 3 , username : 'tspace3', email : 'tspace3@gmail.com'}
85
+
86
+ +--------------------------------------------------------------------------+
87
+
88
+ const reposity = new DB('users')
89
+ reposity.name = 'tspace4'
90
+ reposity.email = 'tspace4@gmail.com'
91
+ await reposity.save()
92
+ const { result } = reposity
93
+ // result => { id : 4 , username : 'tspace4', email : 'tspace4@gmail.com'}
94
+ ```
95
+ Running A Update Query
96
+ ```js
97
+ const user = await new DB('users')
98
+ .where('id',1)
99
+ .update({
100
+ name : 'tspace1**',
101
+ email : 'tspace1@gmail.com'
102
+ }).save()
103
+ // user => { id : 1 , username : 'tspace1**', email : 'tspace1@gmail.com'}
104
+
105
+ +--------------------------------------------------------------------------+
106
+
107
+ const reposity = new DB('users').where('id',1)
108
+ reposity.name = 'tspace1++'
109
+ reposity.email = 'tspace1++@gmail.com'
110
+ await reposity.save()
111
+ const { result } = reposity
112
+ // result => { id : 1 , username : 'tspace1++', email : 'tspace1++@gmail.com'}
113
+ ```
114
+ Running A Delete Query
115
+ ```js
116
+ const deleted = await new DB('users').where('id',1).delete()
117
+ // deleted => true
118
+ ```
119
+ ## Database Transactions
120
+
121
+ Within a database transaction, you may use the:
122
+
123
+ ```js
124
+ const connection = await new DB().beginTransaction()
125
+
126
+ try {
127
+ /**
128
+ *
129
+ * @startTransaction start transaction in scopes function
130
+ */
131
+ await connection.startTransaction()
132
+
133
+ const user = await new User()
134
+ .create({
135
+ name : `tspace`,
136
+ email : 'tspace@example.com'
137
+ })
138
+ /**
139
+ *
140
+ * bind method for make sure this connection has same transaction in connection
141
+ * @params {Function} connection
142
+ */
143
+ .bind(connection)
144
+ .save()
145
+
146
+ const posts = await new Post().createMultiple([
147
+ {
148
+ user_id : user.id,
149
+ title : `tspace-post1`
150
+ },
151
+ {
152
+ user_id : user.id,
153
+ title : `tspace-post2`
154
+ },
155
+ {
156
+ user_id : user.id,
157
+ title : `tspace-post3`
158
+ }
159
+ ])
160
+ /**
161
+ *
162
+ * bind method for make sure this connection has same transaction in connection
163
+ * @params {Function} connection
164
+ */
165
+ .bind(connection)
166
+ .save()
167
+
168
+ // throw new Error('try error')
169
+
170
+ /**
171
+ *
172
+ * @commit commit transaction to database
173
+ */
174
+ await connection.commit()
175
+
176
+ } catch (err) {
177
+
178
+ /**
179
+ *
180
+ * @rollback rollback transaction
181
+ */
182
+ await connection.rollback()
183
+ }
184
+
185
+ ```
186
+
187
+ ## Connection
188
+ When establishing a connection, you may establish options is this:
189
+ ```js
190
+ const users = await new DB('users')
191
+ .connection({
192
+ host: 'localhost',
193
+ port : 3306,
194
+ database: 'database'
195
+ username: 'username',
196
+ password: 'password',
197
+ })
198
+ .findMany()
199
+ // users => [{ .... }]
200
+ ```
201
+
202
+ ## Backup
203
+ Backup database, you may backup is this:
204
+ ```js
205
+ /**
206
+ *
207
+ * @param conection defalut current connection
208
+ */
209
+ const backup = await new DB().backup({
210
+ database: 'try-to-backup',
211
+ connection ?: {
212
+ host: 'localhost',
213
+ port : 3306,
214
+ database: 'database'
215
+ username: 'username',
216
+ password: 'password',
217
+ }
218
+ })
219
+ /**
220
+ *
221
+ * @param {string} database Database selected
222
+ * @param {string} filePath file path
223
+ * @param {object | null} conection defalut current connection
224
+ */
225
+ const backupToFile = await new DB().backupToFile({
226
+ database: 'try-to-backup',
227
+ filePath: 'backup.sql',
228
+ connection ?: {
229
+ host: 'localhost',
230
+ port : 3306,
231
+ database: 'database'
232
+ username: 'username',
233
+ password: 'password',
234
+ }
235
+ })
236
+ // backupToFile => backup.sql
237
+ ```
238
+
239
+ ## Generating Model Classes
240
+ To get started, let's install npm install tspace-mysql -g
241
+ you may use the make:model command to generate a new model:
242
+
243
+ ```sh
244
+ npm install tspace-mysql -g
245
+ tspace-mysql make:model <model name> --dir=<directory>
246
+
247
+ # tspace-mysql make:model User --dir=App/Models
248
+ # => App/Models/User.ts
249
+ ```
250
+ ## Model Conventions
251
+ Models generated by the make:model command will be placed in the specific directory.
252
+ Let's examine a basic model class:
253
+
254
+ ```js
255
+ import { Model } from 'tspace-mysql'
256
+ class User extends Model {
257
+ constructor(){
258
+ super()
259
+ this.useTimestamp()
260
+ /*
261
+ * the "snake case", plural name of the class will be used as the table name
262
+ *
263
+ * @param {string} name The table associated with the model.
264
+ */
265
+ this.useTable('users')
266
+ }
267
+ }
268
+ export { User }
269
+ export default User
270
+ ```
271
+ ## Relationships
272
+ Relationships are defined as methods on your Model classes
273
+ Let's examine a basic relations :
274
+
275
+ ## One To One
276
+ A one-to-one relationship is used to define relationships where a single model is the parent to one child models
277
+ ```js
278
+ import { Model } from 'tspace-mysql'
279
+ import Phone from '../Phone'
280
+ class User extends Model {
281
+ constructor(){
282
+ super()
283
+ this.useTimestamp()
284
+ /**
285
+ *
286
+ * @hasOne Get the phone associated with the user.
287
+ * @relationship users.id -> phones.user_id
288
+ */
289
+ this.hasOne({ name : 'phone' , model : Phone })
290
+ }
291
+ /**
292
+ * @hasOneQuery Get the phone associated with the user. using function callback
293
+ * @function
294
+ */
295
+ phone (callback ?: Function) {
296
+ return this.hasOneQuery({ model : Phone }, (query) => {
297
+ return callback ? callback(query) : query
298
+ })
299
+ }
300
+ }
301
+ export default User
302
+
303
+ +--------------------------------------------------------------------------+
304
+
305
+ import User from '../User'
306
+ const user = await new User().relations('brand').findOne()
307
+ // user?.phone => {...}
308
+ const userUsingFunction = await new User().phone().findOne()
309
+ // userUsingFunction?.phone => {...}
310
+ ```
311
+
312
+ ## One To Many
313
+ A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models.
314
+ ```js
315
+ import { Model } from 'tspace-mysql'
316
+ import Comment from '../Comment'
317
+ class Post extends Model {
318
+ constructor(){
319
+ super()
320
+ this.useTimestamp()
321
+ /**
322
+ *
323
+ * @hasMany Get the comments for the post.
324
+ * @relationship posts.id -> comments.post_id
325
+ */
326
+ this.hasMany({ name : 'comments' , model : Comment })
327
+ }
328
+ /**
329
+ * @hasManyQuery Get the comments for the post. using function callback
330
+ * @function
331
+ */
332
+ comments (callback ?: Function) {
333
+ return this.hasManyQuery({ model : Comment }, (query) => {
334
+ return callback ? callback(query) : query
335
+ })
336
+ }
337
+ }
338
+ export default Post
339
+
340
+ +--------------------------------------------------------------------------+
341
+
342
+ import Post from '../Post'
343
+ const posts = await new Post().relations('comments').findOne()
344
+ // posts?.comments => [{...}]
345
+ const postsUsingFunction = await new Post().comments().findOne()
346
+ // postsUsingFunction?.comments => [{...}]
347
+ ```
348
+
349
+ ## One To One & One To Many (Inverse) / Belongs To
350
+ ```js
351
+ import { Model } from 'tspace-mysql'
352
+ import User from '../User'
353
+ class Phone extends Model {
354
+ constructor(){
355
+ super()
356
+ this.useTimestamp()
357
+ /**
358
+ *
359
+ * @belongsTo Get the user that owns the phone.
360
+ * @relationship phones.user_id -> users.id
361
+ */
362
+ this.belognsTo({ name : 'user' , model : User })
363
+ }
364
+ /**
365
+ * @belongsToQuery Get the user that owns the phone.. using function callback
366
+ * @function
367
+ */
368
+ user (callback ?: Function) {
369
+ return this.belongsToQuery({ model : User }, (query) => {
370
+ return callback ? callback(query) : query
371
+ })
372
+ }
373
+ }
374
+ export default Phone
375
+
376
+ +--------------------------------------------------------------------------+
377
+
378
+ import Phone from '../Phone'
379
+ const phone = await new Phone().relations('user').findOne()
380
+ // phone?.user => {...}
381
+ const phoneUsingFunction = await new Phone().user().findOne()
382
+ // phoneUsingFunction?.user => {...}
383
+ ```
384
+
385
+ ## Many To Many
386
+ Many-to-many relations are slightly more complicated than hasOne and hasMany relationships.
387
+ ```js
388
+ import { Model } from 'tspace-mysql'
389
+ import Role from '../Role'
390
+ class User extends Model {
391
+ constructor(){
392
+ super()
393
+ this.useTimestamp()
394
+ /**
395
+ *
396
+ * @belongsToMany Get The roles that belong to the user.
397
+ * @relationship users.id , roles.id => role_user.user_id , role_user.role_id
398
+ */
399
+ this.belognsToMany({ name : 'roles' , model : Role })
400
+ }
401
+ /**
402
+ * @belongsToQuery Get the user that owns the phone.. using function callback
403
+ * @function
404
+ */
405
+ roles (callback ?: Function) {
406
+ return this.belongsToManyQuery({ model : Role }, (query) => {
407
+ return callback ? callback(query) : query
408
+ })
409
+ }
410
+ }
411
+ export default User
412
+
413
+ +--------------------------------------------------------------------------+
414
+
415
+ import User from '../User'
416
+ const user = await new User().relations('roles').findOne()
417
+ // user?.roles => [{...}]
418
+ const userUsingFunction = await new User().roles().findOne()
419
+ // user?.roles => [{...}]
420
+ ```
421
+ ## Query Builder
422
+ method chaining for queries
423
+ ```js
424
+ where(column , operator , value)
425
+ whereSensitive(column , operator , value)
426
+ whereId(id)
427
+ whereUser(userId)
428
+ whereEmail(value)
429
+ orWhere(column , operator , value)
430
+ whereIn(column , [])
431
+ whereNotIn(column , [])
432
+ whereNull(column)
433
+ whereNotNull(column)
434
+ whereBetween (column , [value1 , value2])
435
+ whereSubQuery(colmn , rawSQL)
436
+ select(column1 ,column2 ,...N)
437
+ except(column1 ,column2 ,...N)
438
+ only(column1 ,column2 ,...N)
439
+ hidden(column1 ,column2 ,...N)
440
+ join(primary key , table.foreign key)
441
+ rightJoin (primary key , table.foreign key)
442
+ leftJoin (primary key , table.foreign key)
443
+ limit (limit)
444
+ orderBy (column ,'ASC' || 'DSCE')
445
+ having (condition)
446
+ latest (column)
447
+ oldest (column)
448
+ groupBy (column)
449
+ create(objects)
450
+ createMultiple(array objects)
451
+ update (objects)
452
+ createNotExists(objects)
453
+ updateOrCreate (objects)
454
+ connection(options)
455
+ backup({ database , connection })
456
+ backupToFile({ filePath, database , connection })
457
+
458
+ /**
459
+ * registry relation in your models
460
+ * @relationship
461
+ */
462
+ hasOne({ name , model , localKey , foreignKey , freezeTable , as })
463
+ hasMany({ name , model , localKey , foreignKey , freezeTable , as })
464
+ belongsTo({ name , model , localKey , foreignKey , freezeTable , as })
465
+ belongsToMany({ name , model , localKey , foreignKey , freezeTable , as })
466
+ /**
467
+ * @relation using registry in your models
468
+ */
469
+ relations(name1 , name2,...nameN)
470
+ /**
471
+ * @relation using registry in your models. if exists child data remove this parent data
472
+ */
473
+ relationsExists(name1 , name2,...nameN)
474
+ /**
475
+ * @relation call a relation in registry, callback query of parent data
476
+ */
477
+ relationQuery(name,(callback))
478
+
479
+ /**
480
+ * queries statements
481
+ * @execute data statements
482
+ */
483
+ findMany()
484
+ findOne()
485
+ find(id)
486
+ delelte()
487
+ exists ()
488
+ onlyTrashed()
489
+ toSQL()
490
+ toString()
491
+ toJSON()
492
+ toArray(column)
493
+ count(column)
494
+ sum(column)
495
+ avg(column)
496
+ max(column)
497
+ min(column)
498
+ pagination({ limit , page })
499
+ save() /*for action statements insert update or delete */
500
+ ```
501
+
502
+ ## Cli
503
+ To get started, let's install npm install tspace-mysql -g
504
+ you may use a basic cli :
505
+
506
+ ## Make Model
507
+ Command will be placed Model in the specific directory
508
+ ```sh
509
+ tspace-mysql make:model <MODEL NAME> --m --dir=.... --type=....
510
+ /**
511
+ * @options
512
+ * --m // created scheme table for migrate
513
+ * --dir=directory // created model in directory
514
+ * --type=js // extension js default ts
515
+ */
516
+
517
+ tspace-mysql make:model User --m --dir=app/Models
518
+ // =>
519
+ - node_modules
520
+ - app
521
+ - Models
522
+ User.ts
523
+ */
524
+ ```
525
+
526
+ ## Make Migration
527
+ Command will be placed Migration in the specific directory
528
+ ```sh
529
+ tspace-mysql make:migration <TABLE NAME>
530
+ /**
531
+ * @options
532
+ * --type=js /* extension js default ts */
533
+ * --dir=directory /* created table in directory */
534
+ */
535
+ tspace-mysql make:migration users --dir=app/Models/Migrations
536
+ // =>
537
+ - node_modules
538
+ - app
539
+ - Models
540
+ - Migrations
541
+ create_users_table.ts
542
+ User.ts
543
+ */
544
+ ```
545
+ ## Migrate
546
+ ```sh
547
+ tspace-mysql migrate <FOLDER> --type=...
548
+ /**
549
+ * @options
550
+ *--type=js /* extension js default ts */
551
+ *--dir=directory /* find migrate in directory */
552
+ */
553
+
554
+ tspace-mysql migrate --dir=App/Models/Migrations
555
+ // => migrate all schema table in folder into database
556
+ ```
557
+
558
+ ## Blueprint
559
+ Schema table created by command make:migration, you may use the:
560
+ ```js
561
+ import { Schema , Blueprint , DB } from 'tspace-mysql'
562
+ (async () => {
563
+ await new Schema().table('users',{
564
+ id : new Blueprint().int().notNull().primary().autoIncrement(),
565
+ name : new Blueprint().varchar(120).default('my name'),
566
+ email : new Blueprint().varchar(255).unique(),
567
+ email_verify : new Blueprint().tinyInt(),
568
+ password : new Blueprint().varchar(255),
569
+ created_at : new Blueprint().null().timestamp(),
570
+ updated_at : new Blueprint().null().timestamp()
571
+ })
572
+ /**
573
+ *
574
+ * @Faker fake data 5 raw
575
+ * await new DB().table('users').faker(5)
576
+ */
577
+ })()
578
+
579
+ /**
580
+ *
581
+ * @Types
582
+ *
583
+ */
584
+ int ()
585
+ tinyInt (number)
586
+ bigInt (number)
587
+ double ()
588
+ float ()
589
+ varchar (number)
590
+ char (number)
591
+ longText()
592
+ mediumText()
593
+ tinyText()
594
+ text()
595
+ enum(...n)
596
+ date()
597
+ dateTime()
598
+ timestamp ()
599
+
600
+ /**
601
+ *
602
+ * @Attrbuites
603
+ *
604
+ */
605
+ unsigned ()
606
+ unique ()
607
+ null ()
608
+ notNull ()
609
+ primary()
610
+ default (string)
611
+ defaultTimestamp ()
612
+ autoIncrement ()
679
613
  ```