tspace-mysql 1.9.0 → 1.9.1

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.
Files changed (108) hide show
  1. package/README.md +4357 -133
  2. package/dist/lib/config/index.d.ts +2 -2
  3. package/dist/lib/config/index.js +24 -16
  4. package/dist/lib/config/index.js.map +1 -1
  5. package/dist/lib/constants/index.d.ts +10 -1
  6. package/dist/lib/constants/index.js +11 -2
  7. package/dist/lib/constants/index.js.map +1 -1
  8. package/dist/lib/core/Abstracts/AbstractBuilder.d.ts +11 -7
  9. package/dist/lib/core/Abstracts/AbstractBuilder.js +11 -13
  10. package/dist/lib/core/Abstracts/AbstractBuilder.js.map +1 -1
  11. package/dist/lib/core/Abstracts/AbstractDB.d.ts +4 -1
  12. package/dist/lib/core/Abstracts/AbstractDB.js.map +1 -1
  13. package/dist/lib/core/Abstracts/AbstractView.js.map +1 -1
  14. package/dist/lib/core/Blueprint.d.ts +30 -10
  15. package/dist/lib/core/Blueprint.js +39 -14
  16. package/dist/lib/core/Blueprint.js.map +1 -1
  17. package/dist/lib/core/Builder.d.ts +263 -9
  18. package/dist/lib/core/Builder.js +610 -347
  19. package/dist/lib/core/Builder.js.map +1 -1
  20. package/dist/lib/core/Cache/DBCache.js +19 -20
  21. package/dist/lib/core/Cache/DBCache.js.map +1 -1
  22. package/dist/lib/core/Cache/MemoryCache.js +3 -3
  23. package/dist/lib/core/Cache/MemoryCache.js.map +1 -1
  24. package/dist/lib/core/Cache/RedisCache.js +27 -17
  25. package/dist/lib/core/Cache/RedisCache.js.map +1 -1
  26. package/dist/lib/core/Cache/index.js +5 -4
  27. package/dist/lib/core/Cache/index.js.map +1 -1
  28. package/dist/lib/core/Contracts/AlterTable.d.ts +152 -0
  29. package/dist/lib/core/Contracts/AlterTable.js +243 -0
  30. package/dist/lib/core/Contracts/AlterTable.js.map +1 -0
  31. package/dist/lib/core/Contracts/Audit.js +2 -5
  32. package/dist/lib/core/Contracts/Audit.js.map +1 -1
  33. package/dist/lib/core/DB.d.ts +101 -9
  34. package/dist/lib/core/DB.js +168 -29
  35. package/dist/lib/core/DB.js.map +1 -1
  36. package/dist/lib/core/Decorator.d.ts +144 -16
  37. package/dist/lib/core/Decorator.js +156 -14
  38. package/dist/lib/core/Decorator.js.map +1 -1
  39. package/dist/lib/core/Driver/index.d.ts +43 -9
  40. package/dist/lib/core/Driver/index.js +9 -7
  41. package/dist/lib/core/Driver/index.js.map +1 -1
  42. package/dist/lib/core/Driver/mariadb/MariadbDriver.js +74 -27
  43. package/dist/lib/core/Driver/mariadb/MariadbDriver.js.map +1 -1
  44. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.d.ts +45 -9
  45. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js +165 -21
  46. package/dist/lib/core/Driver/mariadb/MariadbQueryBuilder.js.map +1 -1
  47. package/dist/lib/core/Driver/mongodb/MongodbDriver.d.ts +24 -0
  48. package/dist/lib/core/Driver/mongodb/MongodbDriver.js +255 -0
  49. package/dist/lib/core/Driver/mongodb/MongodbDriver.js.map +1 -0
  50. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.d.ts +141 -0
  51. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js +563 -0
  52. package/dist/lib/core/Driver/mongodb/MongodbQueryBuilder.js.map +1 -0
  53. package/dist/lib/core/Driver/mysql/MysqlDriver.js +105 -95
  54. package/dist/lib/core/Driver/mysql/MysqlDriver.js.map +1 -1
  55. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.d.ts +45 -9
  56. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js +165 -21
  57. package/dist/lib/core/Driver/mysql/MysqlQueryBuilder.js.map +1 -1
  58. package/dist/lib/core/Driver/postgres/PostgresDriver.js +97 -72
  59. package/dist/lib/core/Driver/postgres/PostgresDriver.js.map +1 -1
  60. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.d.ts +50 -9
  61. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js +296 -41
  62. package/dist/lib/core/Driver/postgres/PostgresQueryBuilder.js.map +1 -1
  63. package/dist/lib/core/Driver/sqlite/SqliteDriver.d.ts +20 -0
  64. package/dist/lib/core/Driver/sqlite/SqliteDriver.js +192 -0
  65. package/dist/lib/core/Driver/sqlite/SqliteDriver.js.map +1 -0
  66. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.d.ts +144 -0
  67. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js +689 -0
  68. package/dist/lib/core/Driver/sqlite/SqliteQueryBuilder.js.map +1 -0
  69. package/dist/lib/core/JoinModel.js +2 -2
  70. package/dist/lib/core/JoinModel.js.map +1 -1
  71. package/dist/lib/core/Meta.d.ts +17 -11
  72. package/dist/lib/core/Meta.js +25 -19
  73. package/dist/lib/core/Meta.js.map +1 -1
  74. package/dist/lib/core/Model.d.ts +450 -108
  75. package/dist/lib/core/Model.js +1031 -587
  76. package/dist/lib/core/Model.js.map +1 -1
  77. package/dist/lib/{tools/index.d.ts → core/Package.d.ts} +11 -3
  78. package/dist/lib/{tools/index.js → core/Package.js} +20 -7
  79. package/dist/lib/core/Package.js.map +1 -0
  80. package/dist/lib/core/Pool.js +42 -30
  81. package/dist/lib/core/Pool.js.map +1 -1
  82. package/dist/lib/core/Queue.d.ts +240 -0
  83. package/dist/lib/core/Queue.js +686 -0
  84. package/dist/lib/core/Queue.js.map +1 -0
  85. package/dist/lib/core/RelationManager.js +27 -25
  86. package/dist/lib/core/RelationManager.js.map +1 -1
  87. package/dist/lib/core/Repository.d.ts +73 -207
  88. package/dist/lib/core/Repository.js +120 -235
  89. package/dist/lib/core/Repository.js.map +1 -1
  90. package/dist/lib/core/Schema.d.ts +218 -0
  91. package/dist/lib/core/Schema.js +370 -65
  92. package/dist/lib/core/Schema.js.map +1 -1
  93. package/dist/lib/core/StateManager.d.ts +25 -12
  94. package/dist/lib/core/StateManager.js +10 -5
  95. package/dist/lib/core/StateManager.js.map +1 -1
  96. package/dist/lib/core/UtilityTypes.d.ts +85 -56
  97. package/dist/lib/core/UtilityTypes.js.map +1 -1
  98. package/dist/lib/core/index.d.ts +4 -0
  99. package/dist/lib/core/index.js +6 -2
  100. package/dist/lib/core/index.js.map +1 -1
  101. package/dist/lib/types/decorator/index.d.ts +1 -1
  102. package/dist/lib/types/index.d.ts +69 -22
  103. package/dist/lib/types/repository/index.d.ts +68 -37
  104. package/dist/lib/utils/index.d.ts +11 -1
  105. package/dist/lib/utils/index.js +58 -2
  106. package/dist/lib/utils/index.js.map +1 -1
  107. package/package.json +14 -6
  108. package/dist/lib/tools/index.js.map +0 -1
package/README.md CHANGED
@@ -10,7 +10,7 @@ tspace-mysql is an Object-Relational Mapping (ORM) tool designed to run seamless
10
10
 
11
11
  | **Feature** | **Description** |
12
12
  |--------------------------------|---------------------------------------------------------------------------------------------------------|
13
- | **Supports Driver** | MySQL ✅ / MariaDB ✅ / Postgres / ✅ MSSQL / SQLite3 / Oracle |
13
+ | **Supports Driver** | MySQL ✅ / MariaDB ✅ / Postgres / SQLite / Mongodb (yes, even MongoDB 😏) / MSSQL |
14
14
  | **Query Builder** | Create flexible queries like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`. You can also use raw SQL. |
15
15
  | **Join Clauses** | Use `INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, and `CROSS JOIN` to combine data from multiple tables. |
16
16
  | **Model** | Provides a way to interact with database records as objects in code. You can perform create, read, update, and delete (CRUD) operations. Models also support soft deletes and relationship methods. |
@@ -24,6 +24,7 @@ tspace-mysql is an Object-Relational Mapping (ORM) tool designed to run seamless
24
24
  | **Repository** | Follows a pattern for managing database operations like `SELECT`, `INSERT`, `UPDATE`, and `DELETE`. It helps keep the code organized. |
25
25
  | **Decorators** | Use decorators to add extra functionality or information to model classes and methods, making the code easier to read. |
26
26
  | **Caching** | Improves performance by storing frequently requested data. Supports in-memory caching (like memory DB) and Redis for distributed caching. |
27
+ | **Queue** | Job queue for background and async processing. Runs on top of databases for distributed workers (similar to pg-boss). |
27
28
  | **Migrations** | Use CLI commands to create models, make migrations, and apply changes to the database structure. |
28
29
  | **Blueprints** | Create a clear layout of the database structure and how models and tables relate to each other. |
29
30
  | **CLI** | A Command Line Interface for managing models, running migrations, executing queries, and performing other tasks using commands (like `make:model`, `migrate`, and `query`). |
@@ -33,148 +34,4371 @@ tspace-mysql is an Object-Relational Mapping (ORM) tool designed to run seamless
33
34
  Install with [npm](https://www.npmjs.com/):
34
35
 
35
36
  ```sh
36
- # Install tspace-mysql locally for your project
37
+ ## Install tspace-mysql locally for your project
37
38
  npm install tspace-mysql --save
38
39
 
39
- # Install tspace-mysql globally (optional)
40
+ ## Install tspace-mysql globally (optional)
40
41
  npm install -g tspace-mysql
42
+ ```
43
+
44
+ ## Documentation
45
+
46
+ See the [`docs`](https://thanathip41.github.io/tspace-mysql) directory for full documentation.
47
+
48
+ ## TypeScript
49
+
50
+ The TypeScript version is specified only for **development and build-time** purposes and does **not** restrict how consumers use the library.
51
+
52
+ This library is built using **TypeScript 5.9.3**.
53
+ The minimum supported **TypeScript version is >= 5.6.2**.
54
+
55
+ If you are contributing to this library or building it locally, install the pinned TypeScript version:
56
+
57
+ ```sh
58
+
59
+ npm install -D typescript@5.9.3
60
+
61
+ ```
62
+
63
+ ## Basic Usage
41
64
 
42
- # Install database drivers if needed:
43
- # For MariaDB
65
+ - [Configuration](#configuration)
66
+ - [MySQL Database](#mysql-database)
67
+ - [Mariadb Database](#mariadb-database)
68
+ - [Postgres Database](#postgres-database)
69
+ - [Cluster Database](#cluster-database)
70
+ - [SQL Like](#sql-Like)
71
+ - [Query Builder](#query-builder)
72
+ - [Table Name & Alias Name](#table-name--alias-name)
73
+ - [Returning Results](#returning-results)
74
+ - [Query Statement](#query-statements)
75
+ - [Select Statements](#select-statements)
76
+ - [Raw Expressions](#raw-expressions)
77
+ - [Ordering, Grouping, Limit and Offset](#ordering-grouping-limit-and-offset)
78
+ - [Ordering](#ordering)
79
+ - [Grouping](#grouping)
80
+ - [Limit and Offset](#limit-and-offset)
81
+ - [Joins](#joins)
82
+ - [Inner Join Clause](#inner-join-clause)
83
+ - [Left Join, Right Join Clause](#left-join-right-join-clause)
84
+ - [Cross Join Clause](#cross-join-clause)
85
+ - [Basic Where Clauses](#basic-where-clauses)
86
+ - [Where Clauses](#where-clauses)
87
+ - [Or Where Clauses](#or-where-clauses)
88
+ - [Where cases](#where-cases)
89
+ - [Where Object Clauses](#where-object-clauses)
90
+ - [JSON Where Clauses](#json-where-clauses)
91
+ - [Additional Where Clauses](#additional-where-clauses)
92
+ - [Logical Grouping](#logical-grouping)
93
+ - [Advanced Where Clauses](#advanced-where-clauses)
94
+ - [Where Exists Clauses](#where-exists-clauses)
95
+ - [Subquery Where Clauses](#subquery-where-clauses)
96
+ - [Conditional Where Clauses](#conditional-where-clauses)
97
+ - [GetGroupBy](#getgroupby)
98
+ - [Paginating](#paginating)
99
+ - [Insert Statements](#insert-statements)
100
+ - [Update Statements](#update-statements)
101
+ - [Delete Statements](#delete-statements)
102
+ - [Hook Statements](#hook-statements)
103
+ - [Faker Statements](#faker-statements)
104
+ - [Unset Statements](#unset-statements)
105
+ - [Common Table Expressions](#common-table-expressions)
106
+ - [Union](#union)
107
+ - [More Methods](#more-methods)
108
+ - [Database Transactions](#database-transactions)
109
+ - [Race Condition](#race-condition)
110
+ - [Connection](#connection)
111
+ - [Backup](#backup)
112
+ - [Injection](#injection)
113
+ - [Generating Model Classes](#generating-model-classes)
114
+ - [Model Conventions](#model-conventions)
115
+ - [Basic Model Setup](#basic-model-setup)
116
+ - [Table Name](#table-name)
117
+ - [Pattern](#pattern)
118
+ - [UUID](#uuid)
119
+ - [Timestamp](#timestamp)
120
+ - [Debug](#debug)
121
+ - [Observer](#observer)
122
+ - [Logger](#logger)
123
+ - [Hooks](#hooks)
124
+ - [Global Scope](#global-scope)
125
+ - [Schema](#schema)
126
+ - [Schema Model](#schema-model)
127
+ - [Virtual Column](#virtual-column)
128
+ - [Validation](#validation)
129
+ - [Sync](#sync)
130
+ - [SoftDelete](#softdelete)
131
+ - [Joins Model](#joins-model)
132
+ - [Inner Join Model Clause](#inner-join-model-clause)
133
+ - [Left Join , Right Join Model Clause](#left-join-right-join-model-clause)
134
+ - [Cross Join Model Clause](#cross-join-model-clause)
135
+ - [Relationships](#relationships)
136
+ - [One To One](#one-to-one)
137
+ - [One To Many](#one-to-many)
138
+ - [Belongs To](#belongs-to)
139
+ - [Many To Many](#many-to-many)
140
+ - [Relation](#relation)
141
+ - [Deeply Nested Relations](#deeply-nested-relations)
142
+ - [Relation Exists](#relation-exists)
143
+ - [Relation Count](#relation-count)
144
+ - [Relation Trashed](#relation-trashed)
145
+ - [Built in Relation Functions](#built-in-relation-functions)
146
+ - [Cache](#cache)
147
+ - [Decorator](#decorator)
148
+ - [Type Safety](#type-safety)
149
+ - [Type Safety Select](#type-safety-select)
150
+ - [Type Safety OrderBy](#type-safety-order-by)
151
+ - [Type Safety GroupBy](#type-safety-group-by)
152
+ - [Type Safety Where](#type-safety-where)
153
+ - [Type Safety Insert](#type-safety-insert)
154
+ - [Type Safety Update](#type-safety-update)
155
+ - [Type Safety Delete](#type-safety-delete)
156
+ - [Type Safety Relationships](#type-safety-relationships)
157
+ - [Type Safety Results](#type-safety-results)
158
+ - [Metadata](#metadata)
159
+ - [Audit](#audit)
160
+ - [Repository](#repository)
161
+ - [Repository Select Statements](#repository-select-statements)
162
+ - [Repository Insert Statements](#repository-insert-statements)
163
+ - [Repository Update Statements](#repository-update-statements)
164
+ - [Repository Delete Statements](#repository-delete-statements)
165
+ - [Repository Transactions](#repository-transactions)
166
+ - [Repository Relations](#repository-relations)
167
+ - [Queue](#queue)
168
+ - [View](#view)
169
+ - [Stored Procedure](#stored-procedure)
170
+ - [Blueprint](#blueprint)
171
+ - [Cli](#cli)
172
+ - [Make Model](#make-model)
173
+ - [Make Migration](#make-migration)
174
+ - [Migrate](#migrate)
175
+ - [Query](#query)
176
+ - [Dump](#dump)
177
+ - [Generate Models](#generate-models)
178
+ - [Migration Models](#migration-models)
179
+ - [Migration DB](#migration-db)
180
+
181
+ ## Configuration
182
+
183
+ To establish a connection, the recommended method for creating your environment variables is by using a '.env' file. using the following:
184
+
185
+ ```js
186
+ DB_HOST = localhost
187
+ DB_PORT = 3306
188
+ DB_USERNAME = root
189
+ DB_PASSWORD = password
190
+ DB_DATABASE = database
191
+ /**
192
+ * @default
193
+ * DB_CONNECTION_LIMIT = 20
194
+ * DB_QUEUE_LIMIT = 0
195
+ * DB_TIMEOUT = 60000
196
+ * DB_DATE_STRINGS = false
197
+ */
198
+ ```
199
+
200
+ ### MySQL Database
201
+
202
+ To connect the application to a MySQL database, using the following:
203
+ ```sh
204
+ npm install mysql2 --save
205
+ ```
206
+
207
+ ```js
208
+ DB_DRIVER = mysql
209
+ DB_HOST = localhost
210
+ DB_PORT = 3306
211
+ DB_USERNAME = root
212
+ DB_PASSWORD = password
213
+ DB_DATABASE = database
214
+ ```
215
+
216
+ ### Mariadb Database
217
+
218
+ To connect the application to a Mariadb database, using the following:
219
+
220
+ ```sh
44
221
  npm install mariadb --save
222
+ ```
223
+
224
+ ```js
225
+ DB_DRIVER = mariadb
226
+ DB_HOST = localhost
227
+ DB_PORT = 3306
228
+ DB_USERNAME = root
229
+ DB_PASSWORD = password
230
+ DB_DATABASE = database
231
+ ```
232
+
233
+ ### Postgres Database
45
234
 
46
- # For PostgreSQL
235
+ To connect the application to a Postgres database, using the following:
236
+
237
+ ```sh
47
238
  npm install pg --save
239
+ ```
48
240
 
49
- # MySQL2 driver is installed by default with tspace-mysql
241
+ ```js
242
+ DB_DRIVER = postgres
243
+ DB_HOST = localhost
244
+ DB_PORT = 5432
245
+ DB_USERNAME = root
246
+ DB_PASSWORD = password
247
+ DB_DATABASE = database
50
248
  ```
51
249
 
52
- ## Documentation
250
+ ### Cluster Database
251
+ If you need strict race condition control, it is required to use multiple nodes for write and read. <br>
252
+ Avoid using a node load balancer in this case, as it may bypass proper write/read distribution and compromise consistency.<br>
253
+ To connect your application to a Cluster database, use the following configuration:
53
254
 
54
- See the [`docs`](https://thanathip41.github.io/tspace-mysql) directory for full documentation.
255
+ ```js
256
+ // ----------------------------------------------------
257
+ // example MariaDB Galera Cluster
55
258
 
56
- ## Basic Usage
259
+ DB_DRIVER = mariadb
260
+ DB_HOST = host-load-balncer ❌
261
+ DB_PORT = 3306
262
+ DB_USERNAME = root1
263
+ DB_PASSWORD = password1
264
+ DB_DATABASE = database
265
+ ```
266
+
267
+ ```js
268
+ // ----------------------------------------------------
269
+ // MariaDB Galera Cluster
270
+ // host1 -> Master node
271
+ // host2, host3 -> slave nodes
272
+ DB_CLUSTER = true
273
+ DB_DRIVER = mariadb
274
+ DB_HOST = host1,host2,host3 ✅ // host1 still master by default
275
+ // if you want to specific master or slave
276
+ // master can be more than 1
277
+ // DB_HOST = master@host1,slave@host2,slave@host3
278
+ DB_PORT = 3306,3307,3308
279
+ DB_USERNAME = root1,root2,root3
280
+ DB_PASSWORD = password1,password2,password3
281
+ DB_DATABASE = database
282
+ ```
283
+
284
+ ## SQL Like
285
+ SQL (Structured Query Language) is used to manage data in relational databases.
286
+ Here are the four most common commands with **tspace-mysql** examples:
287
+ ```js
288
+ import { sql , OP } from 'tspace-mysql'
289
+
290
+ // select
291
+ await sql()
292
+ .select('id','name')
293
+ .from('users')
294
+ .where({
295
+ 'name' : 'tspace'
296
+ 'id' : OP.in([1,2,3])
297
+ })
298
+ .limit(3)
299
+ .orderBy('name')
300
+
301
+ // insert
302
+ await sql()
303
+ .insert('users')
304
+ .values({
305
+ email : 'tspace@example.com'
306
+ })
307
+
308
+ // insert return data
309
+ await sql()
310
+ .insert('users')
311
+ .values({
312
+ email : 'tspace@example.com'
313
+ })
314
+ .returning({
315
+ id : true,
316
+ email : true,
317
+ enum : true
318
+ })
319
+
320
+ // update
321
+ await sql()
322
+ .update('users')
323
+ .where({
324
+ id : 1
325
+ })
326
+ .set({
327
+ email : 'tspace@example.com'
328
+ })
329
+
330
+ // update return data
331
+ await sql()
332
+ .update('users')
333
+ .where({
334
+ id : 1
335
+ })
336
+ .set({
337
+ email : 'tspace@example.com'
338
+ })
339
+ .returning()
340
+
341
+ //delete
342
+ await sql()
343
+ .delete('users')
344
+ .where({
345
+ id : 1
346
+ })
347
+
348
+
349
+ ```
350
+
351
+ ## Query Builder
352
+
353
+ How a database query builder works with a simple example using the following:
354
+
355
+ ```js
356
+ +-------------+--------------+----------------------------+
357
+ | table users |
358
+ +-------------+--------------+----------------------------+
359
+ | id | username | email |
360
+ |-------------|--------------|----------------------------|
361
+ | 1 | tspace | tspace@gmail.com |
362
+ | 2 | tspace2 | tspace2@gmail.com |
363
+ +-------------+--------------+----------------------------+
364
+
365
+
366
+ +-------------+--------------+----------------------------+
367
+ | table posts |
368
+ +-------------+--------------+----------------------------+
369
+ | id | user_id | title |
370
+ |-------------|--------------|----------------------------|
371
+ | 1 | 1 | posts tspace |
372
+ | 2 | 2 | posts tspace2 |
373
+ +-------------+--------------+----------------------------+
374
+
375
+ ```
376
+
377
+ ### Table Name & Alias Name
378
+
379
+ ```js
380
+ import { DB } from 'tspace-mysql'
381
+
382
+ await new DB().from('users').find(1)
383
+ // SELECT * FROM `users` WHERE `users`.`id` = '1' LIMIT 1;
384
+
385
+ await new DB().table('users').find(1)
386
+ // SELECT * FROM `users` WHERE `users`.`id` = '1' LIMIT 1;
387
+
388
+ await new DB().table('users').alias('u').find(1)
389
+ // SELECT * FROM `users` AS `u` WHERE `u`.`id` = '1' LIMIT 1;
390
+
391
+ await new DB().fromRaw('u',new DB('users').select('*').limit(1).toString()).find(1)
392
+ // SELECT * FROM ( SELECT * FROM `users` LIMIT 1 ) AS `u` WHERE `u`.`id` = '1' LIMIT 1;
393
+
394
+ await new DB().alias('u',new DB('users').select('*').limit(1).toString()).find(1)
395
+ // SELECT * FROM ( SELECT * FROM `users` LIMIT 1 ) AS `u` WHERE `u`.`id` = '1' LIMIT 1;
396
+
397
+ ```
398
+
399
+ ### Returning Results
400
+
401
+ ```js
402
+ const user = await new DB("users").find(1); // Object or null
403
+
404
+ const user = await new DB("users").findOne(); // Object or null
405
+
406
+ const user = await new DB("users").first(); // Object or null
407
+
408
+ const user = await new DB("users").firstOrError(message); // Object or error
409
+
410
+ const users = await new DB("users").findMany(); // Array-object of users
411
+
412
+ const users = await new DB("users").get(); // Array-object of users
413
+
414
+ const users = await new DB("users").getGroupBy('name') // Map
415
+
416
+ const users = await new DB("users").findGroupBy('name') // Map
417
+
418
+ const users = await new DB("users").toArray(); // Array of users
419
+
420
+ const users = await new DB("users").toJSON(); // JSON of users
421
+
422
+ const user = await new DB("users").exists(); // Boolean true if user exists otherwise false
423
+
424
+ const user = await new DB("users").count(); // Number of users counted
425
+
426
+ const user = await new DB("users").avg(); // Number of users avg
427
+
428
+ const user = await new DB("users").sum(); // Number of users sum
429
+
430
+ const user = await new DB("users").max(); // Number of users max
431
+
432
+ const user = await new DB("user").min(); // Number of users min
433
+
434
+ const users = await new DB("users").toString(); // sql query string
435
+
436
+ const users = await new DB("users").toSQL(); // sql query string
437
+
438
+ const users = await new DB("users").toRawSQL(); // sql query string
439
+
440
+ const users = await new DB("users").pagination(); // Object of pagination
441
+
442
+ const users = await new DB("users").makeSelectStatement() // query string for select statement
443
+
444
+ const users = await new DB("users").makeInsertStatement() // query string for insert statement
445
+
446
+ const users = await new DB("users").makeUpdateStatement() // query string for update statement
447
+
448
+ const users = await new DB("users").makeDeleteStatement() // query string for delete statement
449
+
450
+ const users = await new DB("users").makeCreateTableStatement() // query string for create table statement
451
+
452
+ ```
453
+
454
+ ## Query Statements
455
+
456
+ ```js
457
+ const query = await DB.query(
458
+ "SELECT * FROM users WHERE id = :id AND email IS :email AND name IN :username", {
459
+ id : 1,
460
+ email : null,
461
+ username : ['name1','name2']
462
+ })
463
+ // SELECT * FROM users WHERE id = '1' AND email IS NULL AND username in ('name1','name2');
464
+ ```
465
+
466
+ ## Select Statements
467
+
468
+ ```js
469
+ const select = await new DB("users").select("id", "username").findOne();
470
+ // SELECT `users`.`id`, `users`.`username` FROM `users` LIMIT 1;
471
+
472
+ const selectRaw = await new DB("users").selectRaw("COUNT(id)").findMany();
473
+ // SELECT COUNT(id) FROM `users`;
474
+ // You can also use the DB.raw() function
475
+ // const selectRaw = await new DB("users").selec(DB.raw("COUNT(id)")).findMany();
476
+
477
+ const selectObject = await new DB("posts")
478
+ .join("posts.user_id", "users.id")
479
+ .select("posts.*")
480
+ .selectObject(
481
+ { id: "users.id", name: "users.name", email: "users.email" },
482
+ "user"
483
+ )
484
+ .findOne();
485
+
486
+ /**
487
+ SELECT
488
+ posts.*, JSON_OBJECT('id' , `users`.`id` , 'name' , `users`.`name` , 'email' , `users`.`email`) AS `user`
489
+ FROM `posts`
490
+ INNER JOIN `users` ON `posts`.`user_id` = `users`.`id` LIMIT 1;
491
+ */
492
+
493
+ const selectArray = await new DB("users")
494
+ .select('id','name','email')
495
+ .join("users.id", "posts.user_id")
496
+ .select("posts.*")
497
+ .selectArray(
498
+ { id: "posts.id", user_id: "posts.user_id", title: "posts.title" },
499
+ "posts"
500
+ )
501
+ .findOne();
502
+ /**
503
+ SELECT
504
+ `users`.`id`, `users`.`name`, `users`.`email`,
505
+ CASE WHEN COUNT(`posts`.`id`) = 0 THEN JSON_ARRAY()
506
+ ELSE JSON_ARRAYAGG(JSON_OBJECT('id' , `posts`.`id` , 'user_id' , `posts`.`user_id` , 'email' , `posts`.`title`))
507
+ END AS `posts`
508
+ FROM `users`
509
+ INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id` WHERE `users`.`deletedAt` IS NULL GROUP BY `users`.`id` LIMIT 1;
510
+ */
511
+
512
+ await new DB("users").except("id").findOne();
513
+ // SELECT `users`.`email`, `users`.`username` FROM `users` LIMIT 1;
514
+
515
+ await new DB("users").distinct().select("id").findOne();
516
+ // SELECT DISTINCT `users`.`id` FROM `users` LIMIT 1;
517
+ ```
518
+
519
+ ## Raw Expressions
520
+
521
+ ```js
522
+ const users = await new DB("users")
523
+ .select(DB.raw("COUNT(`username`) as c"), "username")
524
+ .groupBy("username")
525
+ .having("c > 1")
526
+ .findMany();
527
+ // SELECT COUNT(`username`) as c, `users`.`username` FROM `users` GROUP BY `username` HAVING c > 1;
528
+
529
+ const users = await new DB("users")
530
+ .where(
531
+ "id",
532
+ DB.raw(new DB("users").select("id").where("id", "1").limit(1).toString())
533
+ )
534
+ .findMany();
535
+ // SELECT * FROM `users` WHERE `users`.`id` = (SELECT `users`.`id` FROM `users` WHERE `users`.`id` = '1' LIMIT 1);
536
+
537
+ const findFullName = await new User()
538
+ .select('name',`${DB.raw('CONCAT(firstName," ",lastName) as fullName')}`)
539
+ .whereRaw(`CONCAT(firstName," ",lastName) LIKE '%${search}%'`)
540
+ .findOne()
541
+ // SELECT `users`.`name`, CONCAT(firstName," ",lastName) as fullName FROM `users` WHERE CONCAT(firstName," ",lastName) LIKE '%search%' LIMIT 1;
542
+
543
+ ```
544
+
545
+ ## Ordering, Grouping, Limit and Offset
546
+
547
+ ### Ordering
548
+
549
+ ```js
550
+ await new DB("users").orderBy("id", "asc").findOne();
551
+ // SELECT * FROM `users` ORDER BY `id` ASC LIMIT 1;
552
+
553
+ await new DB("users").orderBy("id", "desc").findOne();
554
+ // SELECT * FROM `users` ORDER BY `id` DESC LIMIT 1;
555
+
556
+ await new DB("users").oldest("id").findOne();
557
+ // SELECT * FROM `users` ORDER BY `id` ASC LIMIT 1;
558
+
559
+ await new DB("users").latest("id").findOne();
560
+ // SELECT * FROM `users` ORDER BY `id` DESC LIMIT 1;
561
+
562
+ await new DB("users").random().findMany();
563
+ // SELECT * FROM `users` ORDER BY RAND();
564
+ ```
565
+
566
+ ### Grouping
567
+
568
+ ```js
569
+ await new DB("users").groupBy("id").findOne();
570
+ // SELECT * FROM `users` GROUP BY `id` LIMIT 1;
571
+
572
+ await new DB("users").groupBy("id", "username").findOne();
573
+ // SELECT * FROM `users` GROUP BY `id`, `username` LIMIT 1;
574
+
575
+ await new DB("users")
576
+ .select(DB.raw("COUNT(username) as c"), "username")
577
+ .groupBy("username")
578
+ .having("c > 1")
579
+ .findMany();
580
+ // SELECT COUNT(username) as c, `users`.`username` FROM `users` GROUP BY `username` HAVING c > 1;
581
+ ```
582
+
583
+ ### Limit and Offset
584
+
585
+ ```js
586
+ await new DB("users").limit(5).findMany();
587
+ // SELECT * FROM `users` LIMIT 5;
588
+
589
+ await new DB("users").limit(-1).findMany();
590
+ // SELECT * FROM `users` LIMIT 2147483647; // int-32 2**31 - 1
591
+
592
+ await new DB("users").offset(1).findOne();
593
+ // SELECT * FROM `users` LIMIT 1 OFFSET 1;
594
+ ```
595
+
596
+ ## Joins
597
+
598
+ ### Inner Join Clause
599
+
600
+ ```js
601
+ await new DB("posts").join("posts.user_id", "users.id").findMany();
602
+ // SELECT * FROM `posts` INNER JOIN `users` ON `posts`.`user_id` = `users`.`id`;
603
+
604
+ await new DB("posts")
605
+ .join((join) => {
606
+ return join
607
+ .on('posts.user_id','users.id')
608
+ .on('users.id','post_user.user_id')
609
+ .and('users.id','posts.user_id')
610
+ })
611
+ .findMany();
612
+
613
+ // SELECT * FROM `posts`
614
+ // INNER JOIN `users` ON `posts`.`user_id` = `users`.`id`
615
+ // INNER JOIN `post_user` ON `users`.`id` = `post_user`.`user_id` AND `users`.`id` = `posts`.`user_id`;
616
+ ```
617
+
618
+ ### Left Join, Right Join Clause
619
+
620
+ ```js
621
+ await new DB("posts").leftJoin("posts.user_id", "users.id").findMany();
622
+ // SELECT * FROM `posts` LEFT JOIN `users` ON `posts`.`user_id` = `users`.`id`;
623
+
624
+ await new DB("posts").rightJoin("posts.user_id", "users.id").findMany();
625
+ // SELECT * FROM `posts` RIGHT JOIN `users` ON `posts`.`user_id` = `users`.`id`;
626
+ ```
627
+
628
+ ### Cross Join Clause
629
+
630
+ ```js
631
+ await new DB("posts").crossJoin("posts.user_id", "users.id").findMany();
632
+ // SELECT * FROM `posts` CROSS JOIN `users` ON `posts`.`user_id` = `users`.`id`;
633
+ ```
634
+
635
+ ## Basic Where Clauses
636
+
637
+ ### Where Clauses
638
+
639
+ ```js
640
+ const users = await new DB("users").where("id", 1).findMany();
641
+ // SELECT * FROM `users` WHERE `users`.`id` = '1'
642
+
643
+ const users = await new DB("users")
644
+ .where("id", 1)
645
+ .where("username", "try to find")
646
+ .findMany();
647
+ // SELECT * FROM `users` WHERE `users`.`id` = '1' and `users`.`username` = 'try to find'
648
+
649
+ const users = await new DB("users").where("id", ">", 1).findMany();
650
+ // SELECT * FROM `users` WHERE `users`.`id` > '1';
651
+
652
+ const users = await new DB("users").where("id", "<>", 1).findMany();
653
+ // SELECT * FROM `users` WHERE `users`.`id` <> '1';
654
+ ```
655
+
656
+ ### Or Where Clauses
657
+
658
+ ```js
659
+ const users = await new DB("users").where("id", 1).orWhere("id", 2).findMany();
660
+ // SELECT * FROM `users` WHERE `users`.`id` = 1 OR `users`.`id` = 2
661
+
662
+ const users = await new DB("users")
663
+ .where("id", 1)
664
+ .whereQuery((query) => {
665
+ return query
666
+ .where("id", "<>", 2)
667
+ .orWhere("username", "try to find")
668
+ .orWhere("email", "find@example.com");
669
+ })
670
+ .findMany();
671
+ // SELECT * FROM `users` WHERE `users`.`id` = 1
672
+ // AND
673
+ // ( `users`.`id` <> 2 OR `users`.`username` = 'try to find' OR `users`.`email` = 'find@example.com');
674
+
675
+ ```
676
+
677
+ ### Where cases
678
+
679
+ ```js
680
+ const payments = await new DB('payments')
681
+ .whereCases([
682
+ {
683
+ when : "payment_type = 'credit'",
684
+ then : "status = 'approved'"
685
+ },
686
+ {
687
+ when : "payment_type = 'paypal'",
688
+ then : "status = 'pending'"
689
+ }
690
+ ],"FALSE")
691
+ .findMany()
692
+
693
+ // SELECT * FROM `payments`
694
+ // WHERE (
695
+ // CASE
696
+ // WHEN payment_type = 'credit' THEN status = 'approved'
697
+ // WHEN payment_type = 'paypal' THEN status = 'pending'
698
+ // ELSE FALSE
699
+ // END
700
+ // );
701
+
702
+ const tasks = await new DB("tasks")
703
+ .whereCases([
704
+ {
705
+ when : "priority = 'high'",
706
+ then : "DATEDIFF(due_date, NOW()) <= 3"
707
+ },
708
+ ],"DATEDIFF(due_date, NOW()) <= 7")
709
+ .findMany()
710
+
711
+ // SELECT * FROM `tasks`
712
+ // WHERE (
713
+ // CASE
714
+ // WHEN priority = 'high' THEN DATEDIFF(due_date, NOW()) <= 3
715
+ // ELSE DATEDIFF(due_date, NOW()) <= 7
716
+ // END
717
+ // );
718
+
719
+ ```
720
+
721
+ ### Where Object Clauses
722
+
723
+ ```js
724
+ import { OP } from 'tspace-mysql'
725
+
726
+ const whereObject = await new DB("users")
727
+ .whereObject({
728
+ id : OP.notEq(1),
729
+ username : OP.in(['user1','user2']),
730
+ name : OP.like('%value%')
731
+ })
732
+ .findMany();
733
+
734
+ // SELECT * FROM `users` WHERE `users`.`id` <> '1' AND `users`.`username` = 'user1' AND `users`.`name` LIKE '%value%';
735
+
736
+ ```
737
+
738
+ ### JSON Where Clauses
739
+
740
+ ```js
741
+ const whereJSON = await new DB("users")
742
+ .whereJSON("json", { key: "id", value: "1234" })
743
+ .findMany();
744
+ // SELECT * FROM `users` WHERE `users`.`json`->>'$.id' = '1234';
745
+ ```
746
+
747
+ ### Additional Where Clauses
748
+
749
+ ```js
750
+ const users = await new DB("users").whereIn("id", [1, 2]).findMany();
751
+ // SELECT * FROM `users` WHERE `users`.`id` IN ('1','2');
752
+
753
+ const users = await new DB("users").whereNotIn("id", [1, 2]).findMany();
754
+ // SELECT * FROM `users` WHERE `users`.`id` NOT IN ('1','2');
755
+
756
+ const users = await new DB("users").whereBetween("id", [1, 2]).findMany();
757
+ // SELECT * FROM `users` WHERE `users`.`id` BETWEEN '1' AND '2';
758
+
759
+ const users = await new DB("users").whereNotBetween("id", [1, 2]).findMany();
760
+ // SELECT * FROM `users` WHERE `users`.`id` NOT BETWEEN '1' AND '2';
761
+
762
+ const users = await new DB("users").whereNull("username").findMany();
763
+ // SELECT * FROM `users` WHERE `users`.`username` IS NULL;
764
+
765
+ const users = await new DB("users").whereNotNull("username").findMany();
766
+ // SELECT * FROM `users` WHERE `users`.`username` IS NOT NULL;
767
+ ```
768
+
769
+ ### Logical Grouping
770
+
771
+ ```js
772
+ const users = await new DB("users")
773
+ .whereQuery((query) => query.where("id", 1).where("username", "values"))
774
+ .whereIn("id", [1, 2])
775
+ .findOne();
776
+ // SELECT * FROM `users` WHERE ( `users`.`id` = '1' AND `users`.`username` = 'values') AND `users`.`id` IN ('1','2'') LIMIT 1;
777
+
778
+ const users = await new DB("users")
779
+ .where("id", 1)
780
+ .whereQuery((query) => {
781
+ return query
782
+ .where("id", "<>", 2)
783
+ .where("username", "try to find")
784
+ .where("email", "find@example.com");
785
+ })
786
+ .findMany();
787
+ // SELECT * FROM `users` WHERE `users`.`id` = '1'
788
+ // AND
789
+ // ( `users`.`id` <> '2' AND `users`.`username` = 'try to find' AND `users`.`email` = 'find@example.com');
790
+
791
+ const users = await new DB("users")
792
+ .whereAny(["name", "username", "email"], "like", `%v%`)
793
+ .findMany();
794
+ // SELECT * FROM `users` WHERE ( `users`.`name` LIKE '%v%' OR `users`.`username` LIKE '%v%' OR `users`.`email` LIKE '%v%');
795
+
796
+ const users = await new DB("users")
797
+ .whereAll(["name", "username", "email"], "like", `%v%`)
798
+ .findMany();
799
+ // SELECT * FROM `users` WHERE ( `users`.`name` LIKE '%v%' AND `users`.`username` LIKE '%v%' AND `users`.`email` LIKE '%v%');
800
+ ```
801
+
802
+ ## Advanced Where Clauses
803
+
804
+ ### Where Exists Clauses
805
+
806
+ ```js
807
+ const users = await new DB("users")
808
+ .whereExists(new DB("users").select("id").where("id", 1).toString())
809
+ .findMany();
810
+ // SELECT * FROM `users` WHERE EXISTS (SELECT `id` FROM `users` WHERE id = 1);
811
+
812
+ const users = await new DB("users")
813
+ .wherNoteExists(new DB("users").select("id").where("id", 1).toString())
814
+ .findMany();
815
+ // SELECT * FROM `users` WHERE NOT EXISTS (SELECT `id` FROM `users` WHERE id = 1);
816
+ ```
817
+
818
+ ### Subquery Where Clauses
819
+
820
+ ```js
821
+ const users = await new DB("users")
822
+ .whereSubQuery("id", "SELECT id FROM users")
823
+ .findMany();
824
+ // SELECT * FROM `users` WHERE `users`.`id` IN (SELECT id FROM users);
825
+
826
+ const users = await new DB("users")
827
+ .whereSubQuery("id", new DB("users").select("id").toString())
828
+ .findMany();
829
+ // SELECT * FROM `users` WHERE `users`.`id` IN (SELECT id FROM users);
830
+
831
+ const users = await new DB("users")
832
+ .whereSubQuery(
833
+ "id",
834
+ new DB("users")
835
+ .select("id")
836
+ .whereSubQuery("id", new DB("posts").select("user_id").toString())
837
+ .toString()
838
+ )
839
+ .findMany();
840
+ /*
841
+ SELECT * FROM `users`
842
+ WHERE `users`.`id`
843
+ IN (
844
+ SELECT `users`.`id` FROM `users`
845
+ WHERE `users`.`id`
846
+ IN (
847
+ SELECT `posts`.`user_id` FROM `posts`
848
+ )
849
+ );
850
+ */
851
+ ```
852
+
853
+ ### Conditional Where Clauses
854
+
855
+ ```js
856
+ const users = await new DB("users")
857
+ .where("id", 1)
858
+ .when(true, (query) => query.where("username", "when is actived"))
859
+ .findMany();
860
+ // SELECT * FROM `users` WHERE `users`.`id` = '1' AND `users`.`username` = 'when is actived';
861
+
862
+ const users = await new DB("users")
863
+ .where("id", 1)
864
+ .when(false, (query) => query.where("username", "when is actived"))
865
+ .findMany();
866
+ // SELECT * FROM `users` WHERE `users`.`id` = '1';
867
+ ```
868
+
869
+ ## GetGroupBy
870
+
871
+ ```js
872
+ const data = await new DB("posts").getGroupBy('user_id')
873
+
874
+ // return new Map()
875
+ // find posts by user id
876
+ const userHasPosts = data.get(1)
877
+
878
+ console.log(userHasPosts)
879
+
880
+ ```
881
+
882
+ ## Paginating
883
+
884
+ ```js
885
+ const users = await new DB("users").paginate();
886
+ // SELECT * FROM `users` LIMIT 15 OFFSET 0;
887
+ // SELECT COUNT(*) AS total FROM `users`;
888
+
889
+ const pageTwoUsers = await new DB("users").paginate({ page: 2, limit: 5 });
890
+
891
+ /*
892
+ SELECT * FROM `users` LIMIT 5 OFFSET 5;
893
+ SELECT COUNT(*) AS total FROM `users`;
894
+
895
+ the results are returned
896
+ {
897
+ meta: {
898
+ total: n,
899
+ limit: 5,
900
+ total_page: 5,
901
+ current_page: 2,
902
+ last_page: n,
903
+ next_page: 3,
904
+ prev_page: 1
905
+ },
906
+ data: [...your data here]
907
+ }
908
+
909
+ */
910
+ ```
911
+
912
+ ## Insert Statements
913
+
914
+ ```js
915
+ const user = await new DB("users")
916
+ .create({
917
+ name: "tspace3",
918
+ email: "tspace3@gmail.com",
919
+ })
920
+ .save();
921
+ /**
922
+ INSERT INTO `users`
923
+ (`users`.`name`,`users`.`email`)
924
+ VALUES
925
+ ('tspace3','tspace3@gmail.com');
926
+
927
+ -- then return the result inserted --
928
+ SELECT * FROM `users` WHERE `users`.`id` = ${INSERT ID};
929
+ */
930
+
931
+ const users = await new DB("users")
932
+ .createMultiple([
933
+ {
934
+ name: "tspace4",
935
+ email: "tspace4@gmail.com",
936
+ },
937
+ {
938
+ name: "tspace5",
939
+ email: "tspace5@gmail.com",
940
+ },
941
+ {
942
+ name: "tspace6",
943
+ email: "tspace6@gmail.com",
944
+ },
945
+ ])
946
+ .save();
947
+
948
+ /**
949
+ INSERT INTO `users`
950
+ (`users`.`name`,`users`.`email`)
951
+ VALUES
952
+ ('tspace4','tspace4@gmail.com'),
953
+ ('tspace5','tspace5@gmail.com'),
954
+ ('tspace6','tspace6@gmail.com');
955
+ */
956
+
957
+ const users = await new DB("users")
958
+ .where("name", "tspace4")
959
+ .where("email", "tspace4@gmail.com")
960
+ .createNotExists({
961
+ name: "tspace4",
962
+ email: "tspace4@gmail.com",
963
+ })
964
+ .save();
965
+ /*
966
+ -- if exists return null, if not exists created new data --
967
+ SELECT EXISTS(
968
+ SELECT 1 FROM `users`
969
+ WHERE `users`.`name` = 'tspace4'
970
+ AND `users`.`email` = 'tspace4@gmail.com'
971
+ LIMIT 1
972
+ ) AS 'exists';
973
+
974
+ INSERT INTO `users` (`users`.`name`,`users`.`email`) VALUES ('tspace4','tspace4@gmail.com');
975
+ */
976
+
977
+ const users = await new DB("users")
978
+ .where("name", "tspace4")
979
+ .where("email", "tspace4@gmail.com")
980
+ .createOrSelect({
981
+ name: "tspace4",
982
+ email: "tspace4@gmail.com",
983
+ })
984
+ .save();
985
+ /**
986
+ -- if has exists return data, if not exists created new data --
987
+ SELECT EXISTS(
988
+ SELECT 1 FROM `users`
989
+ WHERE `users`.`name` = 'tspace4'
990
+ AND `users`.`email` = 'tspace4@gmail.com'
991
+ LIMIT 1
992
+ ) AS 'exists';
993
+
994
+ INSERT INTO `users` (`users`.`name`,`users`.`email`) VALUES ('tspace4','tspace4@gmail.com');
995
+
996
+ SELECT * FROM `users` WHERE `users`.`id` = '4';
997
+ */
998
+ ```
999
+
1000
+ ## Update Statements
1001
+
1002
+ ```js
1003
+ const user = await new DB("users")
1004
+ .where("id", 1)
1005
+ .update({
1006
+ name: "tspace1**",
1007
+ email: "tspace1@gmail.com",
1008
+ })
1009
+ .save();
1010
+ /**
1011
+
1012
+ UPDATE `users` SET
1013
+ `users`.`name` = 'tspace1',
1014
+ `users`.`email` = 'tspace1@gmail.com'
1015
+ WHERE `users`.`id` = '1' LIMIT 1;
1016
+
1017
+ */
1018
+
1019
+ const user = await new DB("users")
1020
+ .where("id", 1)
1021
+ .updateMany({
1022
+ name: "tspace1",
1023
+ email: "tspace1@gmail.com",
1024
+ })
1025
+ .save();
1026
+ /**
1027
+ UPDATE `users` SET
1028
+ `users`.`name` = 'tspace1',
1029
+ `users`.`email` = 'tspace1@gmail.com'
1030
+ WHERE `users`.`id` = '1';
1031
+ */
1032
+
1033
+ const user = await new DB("users")
1034
+ .where("id", 1)
1035
+ .update(
1036
+ {
1037
+ name: "tspace1",
1038
+ email: "tspace1@gmail.com",
1039
+ },
1040
+ ["name"]
1041
+ )
1042
+ .save();
1043
+ /**
1044
+ UPDATE `users` SET
1045
+ `name` =
1046
+ CASE WHEN (`name` = '' OR `name` IS NULL)
1047
+ THEN 'tspace1' ELSE `name`
1048
+ END,
1049
+ `email` =
1050
+ 'tspace1@gmail.com'
1051
+ WHERE `users`.`id` = '1' LIMIT 1;
1052
+ */
1053
+
1054
+ const user = await new DB("users")
1055
+ .updateMultiple([
1056
+ {
1057
+ when: {
1058
+ id: 1,
1059
+ name: "name1",
1060
+ },
1061
+ columns: {
1062
+ name: "update row1",
1063
+ email: "row1@example.com",
1064
+ },
1065
+ },
1066
+ {
1067
+ when: {
1068
+ id: 2,
1069
+ },
1070
+ columns: {
1071
+ name: "update row2",
1072
+ email: "row2@example.com",
1073
+ },
1074
+ },
1075
+ ])
1076
+ .save();
1077
+
1078
+ /**
1079
+ UPDATE `users` SET
1080
+ `users`.`name` = (
1081
+ CASE WHEN `users`.`id` = '1'
1082
+ AND `users`.`name` = 'name1'
1083
+ THEN 'update row1'
1084
+ WHEN `users`.`id` = '2'
1085
+ THEN 'update row2'
1086
+ ELSE `users`.`name`
1087
+ END
1088
+ ),
1089
+ `users`.`email` = (
1090
+ CASE WHEN `users`.`id` = '1'
1091
+ AND `users`.`name` = 'name1'
1092
+ THEN 'row1@example.com'
1093
+ WHEN `users`.`id` = '2'
1094
+ THEN 'row2@example.com'
1095
+ ELSE `users`.`email`
1096
+ END
1097
+ )
1098
+ WHERE `users`.`id` IN ('1','2') LIMIT 2;
1099
+
1100
+ */
1101
+
1102
+ const user = await new DB("users")
1103
+ .where("id", 1)
1104
+ .updateOrCreate({
1105
+ name: "tspace1**",
1106
+ email: "tspace1@gmail.com",
1107
+ })
1108
+ .save();
1109
+ // if has exists return update, if not exists created new data
1110
+ // UPDATE `users` SET `name` = 'tspace1**',`email` = 'tspace1@gmail.com' WHERE `users`.`id` = '1' LIMIT 1;
1111
+ // INSERT INTO `users` (`name`,`email`) VALUES ('tspace1**','tspace1@gmail.com');
1112
+ ```
1113
+
1114
+ ## Delete Statements
1115
+
1116
+ ```js
1117
+ const deleted = await new DB("users").where("id", 1).delete();
1118
+ // DELETE FROM `users` WHERE `users`.`id` = '1' LIMIT 1;
1119
+
1120
+ const deleted = await new DB("users").where("id", 1).deleteMany();
1121
+ // DELETE FROM `users` WHERE `users`.`id` = '1' ;
1122
+ ```
1123
+
1124
+ ## Hook Statements
1125
+
1126
+ ```js
1127
+ const hookImage = async (results) => {
1128
+ for(const result of results) {
1129
+ result.image = await ...getImage()
1130
+ }
1131
+ };
1132
+ const user = await new DB("users").where("id", 1).hook(hookResult).findMany();
1133
+ ```
1134
+
1135
+ ## Faker Statements
1136
+
1137
+ ```js
1138
+ await new DB("users").faker(2);
1139
+ /**
1140
+ INSERT INTO `users`
1141
+ (`users`.`username`,`users`.`email`)
1142
+ VALUES
1143
+ ('ivsvtagyta86n571z9d81maz','fxcwkubccdi5ewos521uqexy'),
1144
+ ('rnr4esoki7fgekmdtarqewt','gv0mzb1m3rlbinsdyb6')
1145
+ */
1146
+
1147
+ // custom faker
1148
+ await new DB("users").faker(5, (row, index) => {
1149
+ return {
1150
+ username: `username-${index + 1}`,
1151
+ email: `email-${index + 1}`,
1152
+ };
1153
+ });
1154
+
1155
+ /**
1156
+
1157
+ INSERT INTO `users`
1158
+ (`users`.`username`,`users`.`email`)
1159
+ VALUES
1160
+ ('username-1','email-1'),
1161
+ ('username-2','email-2'),
1162
+ ('username-3','email-3'),
1163
+ ('username-4','email-4'),
1164
+ ('username-5','email-5');
1165
+
1166
+ */
1167
+
1168
+ // fast to create
1169
+ await new DB("users").faker(40_000);
1170
+ ```
1171
+
1172
+ ## Unset Statements
1173
+
1174
+ ```js
1175
+
1176
+ const userInstance = new User().where('email','test@gmail.com')
1177
+
1178
+ const exits = await userInstance.exists()
1179
+ // SELECT EXISTS (SELECT 1 FROM `users` WHERE `users`.`email` = 'test@gmail.com' LIMIT 1) AS `aggregate`;
1180
+
1181
+ const user = await userInstance.orderBy('id').findOne()
1182
+ // SELECT * FROM `users` WHERE `users`.`email` = 'test@gmail.com' ORDER BY `users`.`id` DESC LIMIT 1;
1183
+
1184
+ const users = await userInstance.select('id').unset({ limit : true }).findMany()
1185
+ // SELECT `users`.`id` FROM `users` WHERE `users`.`email` = 'test@gmail.com' ORDER BY `users`.`id` DESC;
1186
+
1187
+ const usersUnsetWhereStatement = await userInstance.unset({ select : true, where : true , orderBy : true }).findMany()
1188
+ // SELECT * FROM `users` WHERE `users`.`deletedAt` IS NULL;
1189
+
1190
+ ```
1191
+
1192
+ ## Common Table Expressions
1193
+
1194
+ ```js
1195
+
1196
+ const user = await new User()
1197
+ .CTEs('z', (query) => {
1198
+ return query
1199
+ .from('posts')
1200
+ })
1201
+ .CTEs('x', (query) => {
1202
+ return query
1203
+ .from('post_user')
1204
+ })
1205
+ .select('users.*','x.*','z.*')
1206
+ .join('users.id','x.user_id')
1207
+ .join('users.id','z.user_id')
1208
+ .findOne()
1209
+
1210
+ // WITH z AS (SELECT posts.* FROM `posts`),
1211
+ // x AS (SELECT * FROM `post_user`)
1212
+ // SELECT users.*, z.*, x.* FROM `users` INNER JOIN `x` ON `users`.`id` = `x`.`user_id` INNER JOIN `z` ON `users`.`id` = `z`.`user_id` WHERE `users`.`deleted_at` IS NULL LIMIT 1;
1213
+
1214
+ ```
1215
+
1216
+ ### Union
1217
+
1218
+ ```js
1219
+ const users = await new DB('users')
1220
+ .where('id',1)
1221
+ .union(new DB('users').whereIn('id',[2]))
1222
+ .union(new DB('users').whereIn('id',[3,4]))
1223
+ .findMany()
1224
+
1225
+ // (SELECT * FROM `users` WHERE `users`.`id` = 1)
1226
+ // UNION (SELECT * FROM `users` WHERE `users`.`id` IN (2))
1227
+ // UNION (SELECT * FROM `users` WHERE `users`.`id` IN (3,4));
1228
+
1229
+
1230
+ const users = await new DB('users')
1231
+ .unionAll(new DB('users'))
1232
+ .unionAll(new DB('users'))
1233
+ .findMany()
1234
+
1235
+ // (SELECT * FROM `users`)
1236
+ // UNION ALL (SELECT * FROM `users`)
1237
+ // UNION ALL (SELECT * FROM `users`);
1238
+
1239
+ ```
1240
+
1241
+ ## More Methods
1242
+
1243
+ ```js
1244
+ where(column , OP , value)
1245
+ whereSensitive(column , OP , value)
1246
+ whereId(id)
1247
+ whereUser(userId)
1248
+ whereEmail(value)
1249
+ whereIn(column , [])
1250
+ whereNotIn(column , [])
1251
+ whereNull(column)
1252
+ whereNotNull(column)
1253
+ whereBetween (column , [value1 , value2])
1254
+ whereQuery(callback)
1255
+ whereJson(column, { targetKey, value , OP })
1256
+ whereRaw(sql)
1257
+ whereExists(sql)
1258
+ whereSubQuery(colmn , rawSQL)
1259
+ whereNotSubQuery(colmn , rawSQL)
1260
+ orWhere(column , OP , value)
1261
+ orWhereRaw(sql)
1262
+ orWhereIn(column , [])
1263
+ orWhereSubQuery(colmn , rawSQL)
1264
+ when(contition , callback)
1265
+ select(column1 ,column2 ,...N)
1266
+ distinct()
1267
+ selectRaw(column1 ,column2 ,...N)
1268
+ except(column1 ,column2 ,...N)
1269
+ exceptTimestamp()
1270
+ only(column1 ,column2 ,...N)
1271
+ hidden(column1 ,column2 ,...N)
1272
+ join(primary key , table.foreign key)
1273
+ rightJoin (primary key , table.foreign key)
1274
+ leftJoin (primary key , table.foreign key)
1275
+ limit (limit)
1276
+ having (condition)
1277
+ havingRaw (condition)
1278
+ orderBy (column ,'ASC' || 'DSCE')
1279
+ orderByRaw(column ,'ASC' || 'DSCE')
1280
+ latest (column)
1281
+ latestRaw (column)
1282
+ oldest (column)
1283
+ oldestRaw (column)
1284
+ groupBy (column)
1285
+ groupByRaw (column)
1286
+ create(objects)
1287
+ createMultiple(array objects)
1288
+ update (objects)
1289
+ updateMany (objects)
1290
+ updateMultiple(array objects)
1291
+ createNotExists(objects)
1292
+ updateOrCreate (objects)
1293
+ onlyTrashed()
1294
+ connection(options)
1295
+ backup({ database , connection })
1296
+ backupToFile({ filePath, database , connection })
1297
+ hook((result) => ...) // callback result to function
1298
+ sleep(seconds)
1299
+
1300
+ /**
1301
+ * registry relation in your models
1302
+ * @relationship
1303
+ */
1304
+ hasOne({ name, model, localKey, foreignKey, freezeTable , as })
1305
+ hasMany({ name, model, localKey, foreignKey, freezeTable , as })
1306
+ belongsTo({ name, model, localKey, foreignKey, freezeTable , as })
1307
+ belongsToMany({ name, model, localKey, foreignKey, freezeTable, as, pivot })
1308
+ /**
1309
+ * @relation using registry in your models
1310
+ */
1311
+ relations(name1 , name2,...nameN) // with(name1, name2,...nameN)
1312
+ /**
1313
+ * @relation using registry in your models ignore soft delete
1314
+ */
1315
+ relationsAll(name1 , name2,...nameN) // withAll(name1, name2,...nameN)
1316
+ /**
1317
+ * @relation using registry in your models. if exists child data remove this data
1318
+ */
1319
+ relationsExists(name1 , name2,...nameN) // withExists(name1, name2,...nameN)
1320
+ /**
1321
+ * @relation using registry in your models return only in trash (soft delete)
1322
+ */
1323
+ relationsTrashed(name1 , name2,...nameN) // withTrashed(name1, name2,...nameN)
1324
+ /**
1325
+ * @relation call a name of relation in registry, callback query of data
1326
+ */
1327
+ relationQuery(name, (callback) ) // withQuery(name1, (callback))
1328
+
1329
+
1330
+ /**
1331
+ * queries statements
1332
+ * @execute data of statements
1333
+ */
1334
+ findMany() // get()
1335
+ findOne() // first()
1336
+ find(id)
1337
+ delelte()
1338
+ delelteMany()
1339
+ exists()
1340
+ toString()
1341
+ toJSON()
1342
+ toArray(column)
1343
+ count(column)
1344
+ sum(column)
1345
+ avg(column)
1346
+ max(column)
1347
+ min(column)
1348
+ pagination({ limit , page })
1349
+ save() /* for actions statements insert or update */
1350
+ makeSelectStatement()
1351
+ makeInsertStatement()
1352
+ makeUpdateStatement()
1353
+ makeDeleteStatement()
1354
+ makeCreateTableStatement()
1355
+
1356
+ ```
1357
+
1358
+ ## Database Transactions
1359
+
1360
+ Within a database transaction, you can utilize the following:
1361
+
1362
+ ```js
1363
+ import { DB } from 'tspace-mysql';
1364
+ import { User } from '../Models/User';
1365
+ import { Post } from '../Models/Post';
1366
+
1367
+ const trx = await new DB().beginTransaction();
1368
+
1369
+ try {
1370
+ /**
1371
+ *
1372
+ * @startTransaction start transaction in scopes function
1373
+ */
1374
+ await trx.startTransaction();
1375
+
1376
+ const user = await new User()
1377
+ .create({
1378
+ name: `tspace`,
1379
+ email: "tspace@example.com",
1380
+ })
1381
+ /**
1382
+ *
1383
+ * bind method for make sure this trx has same transaction in trx
1384
+ * @params {Function} trx
1385
+ */
1386
+ .bind(trx)
1387
+ .save();
1388
+
1389
+ const posts = await new Post()
1390
+ .createMultiple([
1391
+ {
1392
+ user_id: user.id,
1393
+ title: `tspace-post1`,
1394
+ },
1395
+ {
1396
+ user_id: user.id,
1397
+ title: `tspace-post2`,
1398
+ },
1399
+ {
1400
+ user_id: user.id,
1401
+ title: `tspace-post3`,
1402
+ },
1403
+ ])
1404
+ .bind(trx) // don't forget this
1405
+ .save();
1406
+
1407
+ /**
1408
+ *
1409
+ * @commit commit transaction to database
1410
+ */
1411
+ // After your use commit if use same trx for actions this transction will auto commit
1412
+ await trx.commit();
1413
+
1414
+ // If you need to start a new transaction again, just use wait trx.startTransaction();
1415
+
1416
+ const postsAfterCommited = await new Post()
1417
+ .createMultiple([
1418
+ {
1419
+ user_id: user.id,
1420
+ title: `tspace-post1`,
1421
+ },
1422
+ {
1423
+ user_id: user.id,
1424
+ title: `tspace-post2`,
1425
+ },
1426
+ {
1427
+ user_id: user.id,
1428
+ title: `tspace-post3`,
1429
+ },
1430
+ ])
1431
+ // Using this trx now will auto-commit to the database.
1432
+ .bind(trx) // If you need to perform additional operations, use await trx.startTransaction(); again.
1433
+ .save();
1434
+
1435
+
1436
+ // Do not perform any operations with this trx.
1437
+ // The transaction has already been committed, and the trx is closed.
1438
+ // Just ensure everything is handled at the end of the transaction.
1439
+ await trx.end();
1440
+
1441
+ } catch (err) {
1442
+ /**
1443
+ *
1444
+ * @rollback rollback transaction
1445
+ */
1446
+ await trx.rollback();
1447
+ }
1448
+ ```
1449
+ Or you can use transaction method for auto commit and rollback, you can utilize the following:
1450
+
1451
+ ```js
1452
+ import { DB } from 'tspace-mysql';
1453
+ import { User } from '../Models/User';
1454
+ import { Post } from '../Models/Post';
1455
+
1456
+ try {
1457
+
1458
+ const { user, posts } = await DB.transaction(async (trx) => {
1459
+
1460
+ const user = await new User()
1461
+ .create({
1462
+ name: `tspace`,
1463
+ email: "tspace@example.com",
1464
+ })
1465
+ .bind(trx) // don't forget this
1466
+ .save();
1467
+
1468
+ const posts = await new Post()
1469
+ .createMultiple([
1470
+ {
1471
+ user_id: user.id,
1472
+ title: `tspace-post1`,
1473
+ },
1474
+ {
1475
+ user_id: user.id,
1476
+ title: `tspace-post2`,
1477
+ },
1478
+ {
1479
+ user_id: user.id,
1480
+ title: `tspace-post3`,
1481
+ },
1482
+ ])
1483
+ .bind(trx) // don't forget this
1484
+ .save();
1485
+
1486
+ return { user, posts };
1487
+
1488
+ });
1489
+ } catch (err) {
1490
+ // error here is from transaction method, you don't need to worry about rollback, just catch error and handle it.
1491
+ console.error(err);
1492
+ }
1493
+
1494
+ ```
1495
+
1496
+ ## Race Condition
1497
+
1498
+ Within a race condition, you can utilize the following:
1499
+
1500
+ ```js
1501
+
1502
+ import { Model, DB } from 'tspace-mysql'
1503
+
1504
+ class Product extends Model {}
1505
+
1506
+ class Order extends Model {}
1507
+
1508
+ async function purchaseForUpdate({userId , productId , qty } : {
1509
+ userId: number;
1510
+ productId: number;
1511
+ qty: number
1512
+ }): Promise<void> {
1513
+ const trx = await DB.beginTransaction()
1514
+ try {
1515
+
1516
+ await trx.startTransaction()
1517
+
1518
+ const product = await new Product()
1519
+ .where('id',productId)
1520
+ .rowLock('FOR_UPDATE') // don't forget this, lock this product for update
1521
+ .bind(trx)
1522
+ .first()
1523
+
1524
+ if (product == null) throw new Error("Product not found");
1525
+
1526
+ if (product.stock < qty) throw new Error("Not enough stock");
1527
+
1528
+ await new Product()
1529
+ .where('id',productId)
1530
+ .update({
1531
+ stock : `${DB.raw('stock')} - ${qty}`,
1532
+ id: productId
1533
+ })
1534
+ .bind(trx)
1535
+ .save()
1536
+
1537
+ await new Order()
1538
+ .create({
1539
+ user_id : userId,
1540
+ product_id : productId,
1541
+ qty
1542
+ })
1543
+ .bind(trx)
1544
+ .save()
1545
+
1546
+ await trx.commit();
1547
+ console.log(`✅ [FOR UPDATE] User ${userId} purchased ${qty}`);
1548
+
1549
+ } catch (err: any) {
1550
+ await trx.rollback();
1551
+ console.log(`❌ [FOR UPDATE] User ${userId} failed: ${err.message}`);
1552
+ } finally {
1553
+ await trx.end();
1554
+ }
1555
+ }
1556
+
1557
+ async function simulateRaceConnection(): Promise<void> {
1558
+ const MAX_CONNECTION = 500;
1559
+ const TASKS: Function[] = [];
1560
+ const STOCK = MAX_CONNECTION * 10
1561
+
1562
+ await new Product()
1563
+ .where('id',1)
1564
+ .update({
1565
+ stock : STOCK,
1566
+ })
1567
+ .save()
1568
+
1569
+ const successes : number[] = []
1570
+ const fails : number[] = []
1571
+ let purchased : number = 0
1572
+ let outOfStock : number = 0
1573
+ for (let i = 1; i <= MAX_CONNECTION; i++) {
1574
+ TASKS.push(async () => {
1575
+ const qty = Math.floor(Math.random() * 30) + 1
1576
+ await purchaseForUpdate({
1577
+ userId : i,
1578
+ productId : 1 ,
1579
+ qty
1580
+ })
1581
+ .then(_ => {
1582
+ successes.push(1)
1583
+ purchased += qty
1584
+ })
1585
+ .catch(_ => {
1586
+ fails.push(1)
1587
+ outOfStock += qty
1588
+ })
1589
+ });
1590
+ }
1591
+
1592
+ console.log("=== Simulation ===");
1593
+ const start = Date.now();
1594
+ await Promise.all(TASKS.map(v => v()));
1595
+ const end = Date.now();
1596
+ console.log(`USING TIME TO TEST IN ${end - start} ms`)
1597
+ console.log(`ALL STOCK: ${STOCK} qty`)
1598
+ console.log(`✅ [SUCCESS(${successes.length})] [Purchased]: ${purchased} qty`);
1599
+ console.log(`❌ [FAIL(${fails.length})] [OutOfStock]: ${outOfStock} qty`);
1600
+ console.log('======== DONE ============')
1601
+ process.exit(0)
1602
+ }
1603
+
1604
+ simulateRaceConnection();
1605
+
1606
+ ```
1607
+
1608
+ ## Connection
1609
+
1610
+ When establishing a connection, you can specify options as follows:
1611
+
1612
+ ```js
1613
+ const connection = await new DB().getConnection({
1614
+ host: 'localhost',
1615
+ port : 3306,
1616
+ database: 'database'
1617
+ username: 'username',
1618
+ password: 'password',
1619
+ })
1620
+
1621
+ const users = await new DB('users')
1622
+ .bind(connection) // don't forget this
1623
+ .findMany()
1624
+ ```
1625
+
1626
+ ## Backup
1627
+
1628
+ To backup a database, you can perform the following steps:
1629
+
1630
+ ```js
1631
+ /**
1632
+ *
1633
+ * @param {string} database Database selected
1634
+ * @param {object | null} to defalut new current connection
1635
+ */
1636
+ const backup = await new DB().backup({
1637
+ database: 'try-to-backup', // clone current database to this database
1638
+ to ?: {
1639
+ host: 'localhost',
1640
+ port : 3306,
1641
+ username: 'username',
1642
+ password: 'password',
1643
+ }
1644
+ })
1645
+ /**
1646
+ *
1647
+ * @param {string} database Database selected
1648
+ * @param {string} filePath file path
1649
+ * @param {object | null} conection defalut current connection
1650
+ */
1651
+ const backupToFile = await new DB().backupToFile({
1652
+ database: 'try-to-backup',
1653
+ filePath: 'backup.sql',
1654
+ connection ?: {
1655
+ host: 'localhost',
1656
+ port : 3306,
1657
+ database: 'database'
1658
+ username: 'username',
1659
+ password: 'password',
1660
+ }
1661
+ })
1662
+ // backupToFile => backup.sql
1663
+
1664
+ /**
1665
+ *
1666
+ * @param {string} database new db name
1667
+ */
1668
+ await new DB().cloneDB('try-to-clone')
1669
+
1670
+ ```
1671
+
1672
+ ## Injection
1673
+
1674
+ The 'tspace-mysql' library is configured to automatically escape SQL injection by default.
1675
+ Let's example a escape SQL injection and XSs injection:
1676
+
1677
+ ```js
1678
+ const input = "admin' OR '1'='1";
1679
+ DB.escape(input);
1680
+ // "admin\' OR \'1\'=\'1"
1681
+
1682
+ //XSS
1683
+ const input = "text hello!<script>alert('XSS attack');</script>";
1684
+ DB.escapeXSS(input);
1685
+ // "text hello!"
1686
+ ```
1687
+
1688
+ ## Generating Model Classes
1689
+
1690
+ To get started, install the 'tspace-mysql' package globally using the following npm command:
1691
+
1692
+ ```js
1693
+ /**
1694
+ *
1695
+ * @install global command
1696
+ */
1697
+ npm install tspace-mysql -g
1698
+
1699
+ /**
1700
+ *
1701
+ * @make Model
1702
+ */
1703
+ tspace-mysql make:model <model name> --dir=< directory >
1704
+
1705
+ # tspace-mysql make:model User --dir=App/Models
1706
+ # App/Models/User.ts
1707
+ ```
1708
+
1709
+ ## Model Conventions
1710
+
1711
+ Your database schema using models. These models represent tables in the database
1712
+ Let's example a basic model class:
1713
+
1714
+ ```js
1715
+ import { Model } from "tspace-mysql";
1716
+ // If you want to specify a global setting for the 'Model'
1717
+ Model.global({
1718
+ uuid: true,
1719
+ softDelete: true,
1720
+ timestamp: true,
1721
+ logger: true,
1722
+ });
1723
+
1724
+ class User extends Model {
1725
+ constructor() {
1726
+ super();
1727
+ /**
1728
+ *
1729
+ * Assign setting global in your model
1730
+ * @useMethod
1731
+ * this.usePattern('camelCase') // => default 'snake_case'
1732
+ * this.useCamelCase()
1733
+ * this.useSnakeCase()
1734
+ * this.useLogger()
1735
+ * this.useDebug()
1736
+ * this.usePrimaryKey('id')
1737
+ * this.useTimestamp({
1738
+ * createdAt : 'created_at',
1739
+ * updatedAt : 'updated_at'
1740
+ * }) // runing a timestamp when insert or update
1741
+ * this.useSoftDelete('deletedAt') // => default target to colmun deleted_at
1742
+ * this.useTable('users')
1743
+ * this.useTableSingular() // => 'user'
1744
+ * this.useTablePlural() // => 'users'
1745
+ * this.useUUID('uuid') // => runing a uuid (universally unique identifier) when insert new data
1746
+ * this.useRegistry() // => build-in functions registry
1747
+ * this.useLoadRelationsInRegistry() // => auto generated result from relationship to results
1748
+ * this.useBuiltInRelationFunctions() // => build-in functions relationships to results
1749
+ * this.useHooks([(r) => console.log(r)])
1750
+ * this.useObserver(Observe)
1751
+ * this.useSchema ({
1752
+ * id : Blueprint.int().notNull().primary().autoIncrement(),
1753
+ * uuid : Blueprint.varchar(50).null(),
1754
+ * name : Blueprint.varchar(191).notNull(),
1755
+ * email : Blueprint.varchar(191).notNull(),
1756
+ * created_at : Blueprint.timestamp().null(),
1757
+ * updated_at : Blueprint.timestamp().null(),
1758
+ * deleted_at : Blueprint.timestamp().null()
1759
+ * }) // auto-generated table when table is not exists and auto-create column when column not exists
1760
+ *
1761
+ * // validate input when create or update reference to the schema in 'this.useSchema'
1762
+ * this.useValidateSchema({
1763
+ * id : Number,
1764
+ * uuid : Number,
1765
+ * name : {
1766
+ * type : String,
1767
+ * length : 191
1768
+ * require : true
1769
+ * },
1770
+ * email : {
1771
+ * type : String,
1772
+ * require : true,
1773
+ * length : 191,
1774
+ * match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
1775
+ * unique : true,
1776
+ * fn : (email : string) => !/^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
1777
+ * },
1778
+ * created_at : Date,
1779
+ * updated_at : Date,
1780
+ * deleted_at : Date
1781
+ * })
1782
+ */
1783
+
1784
+ /*
1785
+ * the "snake case", plural name of the class will be used as the table name
1786
+ *
1787
+ * @param {string} name The table associated with the model.
1788
+ */
1789
+ this.useTable("users");
1790
+ }
1791
+ }
1792
+ export { User };
1793
+ export default User;
1794
+ ```
1795
+
1796
+ ### Basic Model Setup
1797
+
1798
+ #### Table Name
1799
+
1800
+ ```js
1801
+ import { Model } from 'tspace-mysql'
1802
+ class User extends Model {
1803
+ constructor() {
1804
+ super()
1805
+ // By default, the model knows that the table name for this User is 'users'
1806
+
1807
+ this.useTable('fix_table') // fixtable
1808
+ this.useTablePlural() // users
1809
+ this.useTableSingular() // user
1810
+ }
1811
+ }
1812
+
1813
+ ```
1814
+
1815
+ #### Pattern
1816
+
1817
+ ```js
1818
+
1819
+ import { Model } from 'tspace-mysql'
1820
+ class UserPhone extends Model {
1821
+ constructor() {
1822
+ super()
1823
+ // By default, the model is pattern snake_case
1824
+ // The table name is user_phones
1825
+ this.useSnakeCase()
1826
+
1827
+ this.useCamelCase()
1828
+ // The table name is userPhones
1829
+ }
1830
+ }
1831
+
1832
+ // set the pattern CamelCase for the model
1833
+ const userPhone = await new UserPhone().where('user_id',1).findOne()
1834
+ // covert 'user_id' to 'userId'
1835
+ // SELECT * FROM `userPhones` WHERE `userPhones`.`userId` = '1' LIMIT 1;
1836
+
1837
+ // avoid the pattern CamelCase for the model
1838
+ const userPhone = await new UserPhone().where(DB.freeze('user_id'),1).findOne()
1839
+ // SELECT * FROM `userPhones` WHERE `userPhones`.`user_id` = '1' LIMIT 1;
1840
+
1841
+ ```
1842
+
1843
+ #### UUID
1844
+
1845
+ ```js
1846
+
1847
+ import { Model } from 'tspace-mysql'
1848
+ class User extends Model {
1849
+ constructor() {
1850
+ super()
1851
+ this.useUUID() // insert uuid when creating
1852
+ }
1853
+ }
1854
+
1855
+ ```
1856
+
1857
+ #### Timestamp
1858
+
1859
+ ```js
1860
+
1861
+ import { Model } from 'tspace-mysql'
1862
+ class User extends Model {
1863
+ constructor() {
1864
+ super()
1865
+ // insert created_at and updated_at when creating
1866
+ // update updated_at when updating
1867
+ // 'created_at' and 'updated_at' still relate to pettern the model
1868
+ // this.useCamelCase() will covert 'created_at' to 'createdAt' and 'updated_at' to 'updatedAt'
1869
+ this.useTimestamp()
1870
+
1871
+ // custom the columns
1872
+ this.useTimestamp({
1873
+ createdAt : 'createdAtCustom',
1874
+ updatedAt : 'updatedAtCustom'
1875
+ })
1876
+
1877
+ }
1878
+ }
1879
+
1880
+ ```
1881
+
1882
+ #### Debug
1883
+
1884
+ ```js
1885
+
1886
+ import { Model } from 'tspace-mysql'
1887
+ class User extends Model {
1888
+ constructor() {
1889
+ super()
1890
+ this.useDebug() // show the query sql in console when executing
1891
+ }
1892
+ }
1893
+
1894
+ ```
1895
+ #### Observer
1896
+
1897
+ ```js
1898
+
1899
+ class Observe {
1900
+
1901
+ public selected(results) {
1902
+ console.log({ results , selected : true })
1903
+ }
1904
+
1905
+ public created(results) {
1906
+ console.log({ results , created : true })
1907
+ }
1908
+
1909
+ public updated(results) {
1910
+ console.log({ results , updated : true })
1911
+ }
1912
+
1913
+ public deleted(results) {
1914
+ console.log({ results , deleted : true })
1915
+ }
1916
+ }
1917
+
1918
+ import { Model } from 'tspace-mysql'
1919
+ class User extends Model {
1920
+ constructor() {
1921
+ super()
1922
+ this.useObserver(Observe) // returning to the observers by statements
1923
+ }
1924
+ }
1925
+
1926
+ ```
1927
+
1928
+ #### Logger
1929
+
1930
+ ```js
1931
+
1932
+ import { Model } from 'tspace-mysql'
1933
+ class User extends Model {
1934
+ constructor() {
1935
+ super()
1936
+ // keep logging everything except select to the table '$loggers'
1937
+ // the table will automatically be created
1938
+ this.useLogger()
1939
+
1940
+ // keep logging everything
1941
+ this.useLogger({
1942
+ selected : true,
1943
+ inserted : true,
1944
+ updated : true,
1945
+ deleted : true,
1946
+ })
1947
+ }
1948
+ }
1949
+
1950
+ ```
1951
+
1952
+ #### Hooks
1953
+
1954
+ ```js
1955
+
1956
+ import { Model } from 'tspace-mysql'
1957
+ class User extends Model {
1958
+ constructor() {
1959
+ super()
1960
+ // when executed will returning the results to any hooks function
1961
+ this.useHooks([
1962
+ (results1) => console.log(results1),
1963
+ (results2) => console.log(results2),
1964
+ (results3) => console.log(results3)
1965
+ ])
1966
+ }
1967
+ }
1968
+
1969
+ ```
1970
+
1971
+ ### Global Scope
1972
+ ```js
1973
+
1974
+ class User extends Model {
1975
+ constructor() {
1976
+ super()
1977
+
1978
+ // Every query will have the global scope applied.
1979
+ this.globalScope((query : User) => {
1980
+ return query.select('id').where('id' , '>' , 10).orderBy('id')
1981
+ })
1982
+ }
1983
+ }
1984
+
1985
+ const user = await new User().findMany()
1986
+
1987
+ // SELECT `users`.`id` FROM `users` WHERE `users`.`id` > '10' ORDER BY `users`.`id` ASC LIMIT 1
1988
+
1989
+ ```
1990
+
1991
+ ## Joins Model
1992
+
1993
+ ### Inner Join Model Clause
1994
+
1995
+ ```js
1996
+ await new User().joinModel(User, Post).findMany();
1997
+ // SELECT `users`.`id`, `users`.`email`, `users`.`username` FROM `users` INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id`;
1998
+
1999
+ // if the model use soft delete
2000
+ await new User().joinModel(User, Post).findMany();
2001
+ // SELECT `users`.`id`, `users`.`email`, `users`.`username` FROM `users`
2002
+ // INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id`
2003
+ // WHERE `posts`.`deleted_at` IS NULL AND `users`.`deleted_at` IS NULL;
2004
+
2005
+ await new User().select(`${User.table}.*`,`${Post.table}.*`).joinModel(User, Post).findMany();
2006
+ // SELECT users.*, posts.* FROM `users`
2007
+ // INNER JOIN `posts` ON `users`.`id` = `posts`.`user_id`
2008
+ // WHERE `posts`.`deleted_at` IS NULL AND `users`.`deleted_at` IS NULL;
2009
+
2010
+ await new User().select('u.*','p.*')
2011
+ .joinModel({ model : User , key : 'id' , alias : 'u' }, { model : Post , key : 'user_id', alias : 'p'})
2012
+ .findMany();
2013
+ // SELECT u.*, p.* FROM `users` AS `u`
2014
+ // INNER JOIN `posts` AS `p` ON `u`.`id` = `p`.`user_id`
2015
+ // WHERE `p`.`deleted_at` IS NULL AND `u`.`deleted_at` IS NULL;
2016
+
2017
+ await new DB("posts")
2018
+ .join((join) => {
2019
+ return join
2020
+ .on('posts.user_id','users.id')
2021
+ .on('users.id','post_user.user_id')
2022
+ .and('users.id','posts.user_id')
2023
+ })
2024
+ .findMany()
2025
+ // SELECT * FROM `posts`
2026
+ // INNER JOIN `users` ON `posts`.`user_id` = `users`.`id`
2027
+ // INNER JOIN `post_user` ON `users`.`id` = `post_user`.`user_id` AND `users`.`id` = `posts`.`user_id`;
2028
+ ```
2029
+ ### Left Join, Right Join Model Clause
2030
+
2031
+ ```js
2032
+ await new User().leftJoinModel(User, Post).findMany();
2033
+ // SELECT `users`.`id`, `users`.`email`, `users`.`username` FROM `users` LEFT JOIN `posts` ON `users`.`id` = `posts`.`user_id`;
2034
+
2035
+ await new User().rightJoinModel(User, Post).findMany();
2036
+ // SELECT `users`.`id`, `users`.`email`, `users`.`username` FROM `users` RIGHT JOIN `posts` ON `users`.`id` = `posts`.`user_id`;
2037
+ ```
2038
+
2039
+ ### Cross Join Model Clause
2040
+
2041
+ ```js
2042
+ await new User().crossJoinModel(User, Post).findMany();
2043
+ // SELECT `users`.`id`, `users`.`email`, `users`.`username` FROM `users` CROSS JOIN `posts` ON `users`.`id` = `posts`.`user_id`;
2044
+ ```
2045
+
2046
+ ### Relationships
2047
+
2048
+ Relationships are defined as methods on your Model classes.
2049
+ Let's example a basic relationship:
2050
+
2051
+ #### One To One
2052
+
2053
+ A one-to-one relationship is used to define relationships where a single model is the parent to one child models
2054
+
2055
+ ```js
2056
+ import { Model } from 'tspace-mysql'
2057
+ import Phone from '../Phone'
2058
+ class User extends Model {
2059
+ constructor(){
2060
+ super()
2061
+ this.useTimestamp()
2062
+ /**
2063
+ *
2064
+ * @hasOne Get the phone associated with the user.
2065
+ * @relationship users.id -> phones.user_id
2066
+ */
2067
+ this.hasOne({ name : 'phone' , model : Phone })
2068
+ }
2069
+ /**
2070
+ * Mark a method for relationship
2071
+ * @hasOne Get the phone associated with the user. using function callback
2072
+ * @function
2073
+ */
2074
+ phone (callback) {
2075
+ return this.hasOneBuilder({ name : 'phone' , model : Phone } , callback)
2076
+ }
2077
+ }
2078
+ export default User
2079
+
2080
+ +--------------------------------------------------------------------------+
2081
+
2082
+ import User from '../User'
2083
+ const user = await new User().relations('phone').findOne() // You can also use the method .with('roles').
2084
+ // user?.phone => {...}
2085
+ const userUsingFunction = await new User().phone().findOne()
2086
+ // userUsingFunction?.phone => {...}
2087
+ ```
2088
+
2089
+ ### One To Many
2090
+
2091
+ A one-to-many relationship is used to define relationships where a single model is the parent to one or more child models.
2092
+
2093
+ ```js
2094
+ import { Model } from 'tspace-mysql'
2095
+ import Comment from '../Comment'
2096
+ class Post extends Model {
2097
+ constructor(){
2098
+ super()
2099
+ this.useTimestamp()
2100
+ /**
2101
+ *
2102
+ * @hasMany Get the comments for the post.
2103
+ * @relationship posts.id -> comments.post_id
2104
+ */
2105
+ this.hasMany({ name : 'comments' , model : Comment })
2106
+ }
2107
+ /**
2108
+ *
2109
+ * @hasManyQuery Get the comments for the post. using function callback
2110
+ * @function
2111
+ */
2112
+ comments (callback) {
2113
+ return this.hasManyBuilder({ name : 'comments' , model : Comment } , callback)
2114
+ }
2115
+ }
2116
+ export default Post
2117
+
2118
+ +--------------------------------------------------------------------------+
2119
+
2120
+ import Post from '../Post'
2121
+ const posts = await new Post().relations('comments').findOne()
2122
+ // posts?.comments => [{...}]
2123
+ const postsUsingFunction = await new Post().comments().findOne()
2124
+ // postsUsingFunction?.comments => [{...}]
2125
+ ```
2126
+
2127
+ #### Belongs To
2128
+
2129
+ A belongsto relationship is used to define relationships where a single model is the child to parent models.
2130
+
2131
+ ```js
2132
+ import { Model } from 'tspace-mysql'
2133
+ import User from '../User'
2134
+ class Phone extends Model {
2135
+ constructor(){
2136
+ super()
2137
+ this.useTimestamp()
2138
+ /**
2139
+ *
2140
+ * @belongsTo Get the user that owns the phone.
2141
+ * @relationship phones.user_id -> users.id
2142
+ */
2143
+ this.belognsTo({ name : 'user' , model : User })
2144
+ }
2145
+ /**
2146
+ *
2147
+ * @belongsToBuilder Get the user that owns the phone.. using function callback
2148
+ * @function
2149
+ */
2150
+ user (callback) {
2151
+ return this.belongsToBuilder({ name : 'user' , model : User }, callback)
2152
+ }
2153
+ }
2154
+ export default Phone
2155
+
2156
+ +--------------------------------------------------------------------------+
2157
+
2158
+ import Phone from '../Phone'
2159
+ const phone = await new Phone().relations('user').findOne()
2160
+ // phone?.user => {...}
2161
+ const phoneUsingFunction = await new Phone().user().findOne()
2162
+ // phoneUsingFunction?.user => {...}
2163
+ ```
2164
+
2165
+ #### Many To Many
2166
+
2167
+ Many-to-many relations are slightly more complicated than hasOne and hasMany relationships.
2168
+
2169
+ ```js
2170
+ import { Model } from 'tspace-mysql'
2171
+ import Role from '../Role'
2172
+ class User extends Model {
2173
+ constructor(){
2174
+ super()
2175
+ this.useTimestamp()
2176
+ /**
2177
+ *
2178
+ * @belongsToMany Get The roles that belong to the user.
2179
+ * @relationship users.id , roles.id => role_user.user_id , role_user.role_id
2180
+ */
2181
+ this.belognsToMany({ name : 'roles' , model : Role })
2182
+ }
2183
+ /**
2184
+ * @belongsToBuilder Get the user that owns the phone.. using function callback
2185
+ * @function
2186
+ */
2187
+ roles (callback) {
2188
+ return this.belognsToManyBuilder({ model : Role } , callback)
2189
+ }
2190
+ }
2191
+ export default User
2192
+
2193
+ +--------------------------------------------------------------------------+
2194
+
2195
+ import User from '../User'
2196
+ const user = await new User().relations('roles').findOne()
2197
+ // user?.roles => [{...}]
2198
+ const userUsingFunction = await new User().roles().findOne()
2199
+ // user?.roles => [{...}]
2200
+ ```
2201
+
2202
+ #### Relation
2203
+
2204
+ Relationships are connections between entities.
2205
+ Let's consider an example of a relationship:
2206
+
2207
+ ```js
2208
+
2209
+ +-------------+--------------+----------------------------+
2210
+ | table users |
2211
+ +-------------+--------------+----------------------------+
2212
+ | id | username | email |
2213
+ |-------------|--------------|----------------------------|
2214
+ | 1 | tspace1 | tspace1@gmail.com |
2215
+ | 2 | tspace2 | tspace2@gmail.com |
2216
+ | 3 | tspace3 | tspace3@gmail.com |
2217
+ +-------------+--------------+----------------------------+
2218
+
2219
+ +-------------+--------------+----------------------------+
2220
+ | table posts |
2221
+ +-------------+--------------+----------------------------+
2222
+ | id | user_id | title |
2223
+ |-------------|--------------|----------------------------|
2224
+ | 1 | 1 | posts 1 |
2225
+ | 2 | 1 | posts 2 |
2226
+ | 3 | 3 | posts 3 |
2227
+ +-------------+--------------+----------------------------+
2228
+
2229
+ import { Model } from 'tspace-mysql'
2230
+
2231
+ class User extends Model {
2232
+ constructor(){
2233
+ super()
2234
+ this.hasMany({ name : 'posts' , model : Post })
2235
+ }
2236
+ }
2237
+
2238
+ class Post extends Model {
2239
+ constructor(){
2240
+ super()
2241
+ this.belongsTo({ name : 'user' , model : User })
2242
+ }
2243
+ }
2244
+
2245
+ await new User()
2246
+ .relations('posts')
2247
+ .findOne()
2248
+ // SELECT * FROM `users` LIMIT 1;
2249
+ // SELECT * FROM `posts` WHERE `posts`.`userId` IN (...);
2250
+
2251
+ /*
2252
+ * @returns
2253
+ * {
2254
+ * id : 1,
2255
+ * username: "tspace1",
2256
+ * email : "tspace1@gmail.com",
2257
+ * posts : [
2258
+ * {
2259
+ * id : 1 ,
2260
+ * user_id : 1,
2261
+ * title : "post 1"
2262
+ * },
2263
+ * {
2264
+ * id : 2 ,
2265
+ * user_id : 1,
2266
+ * title : "post 2"
2267
+ * }
2268
+ * ]
2269
+ * }
2270
+ */
2271
+
2272
+ ```
2273
+
2274
+ #### Deeply Nested Relations
2275
+
2276
+ Relationships can involve deep connections.
2277
+ Let's consider an example of a deep relationship:
2278
+
2279
+ ```js
2280
+ import { Model } from 'tspace-mysql'
2281
+
2282
+ class User extends Model {
2283
+ constructor(){
2284
+ super()
2285
+ this.hasMany({ name : 'posts' , model : Post })
2286
+ }
2287
+ }
2288
+ +--------------------------------------------------------------------------+
2289
+ class Post extends Model {
2290
+ constructor(){
2291
+ super()
2292
+ this.hasMany({ name : 'comments' , model : Comment })
2293
+ this.belongsTo({ name : 'user' , model : User })
2294
+ this.belongsToMany({ name : 'users' , model : User , modelPivot : PostUser })
2295
+ }
2296
+ }
2297
+ +--------------------------------------------------------------------------+
2298
+ class Comment extends Model {
2299
+ constructor(){
2300
+ super()
2301
+ this.hasMany({ name : 'users' , model : User })
2302
+ this.belongsTo({ name : 'post' , model : Post })
2303
+ }
2304
+ }
2305
+
2306
+ class PostUser extends Model {}
2307
+ +--------------------------------------------------------------------------+
2308
+ // Deeply nested relations
2309
+ await new User()
2310
+ .relations('posts')
2311
+ .relationQuery('posts', (query : Post) => {
2312
+ return query
2313
+ .relations('comments','user','users')
2314
+ .relationQuery('comments', (query : Comment) => {
2315
+ return query.relations('user','post')
2316
+ })
2317
+ .relationQuery('user', (query : User) => {
2318
+ return query.relations('posts').relationQuery('posts',(query : Post)=> {
2319
+ return query.relations('comments','user')
2320
+ // relation n, n, ...n
2321
+ })
2322
+ })
2323
+ .relationQuery('users', (query : User) => {
2324
+ return query
2325
+ })
2326
+ .relationQuery('users', (query : PostUser) => {
2327
+ return query
2328
+ }, { pivot : true })
2329
+ })
2330
+ .findMany()
2331
+
2332
+ // Select some columns in nested relations
2333
+ await new User()
2334
+ .relations('posts')
2335
+ .relationQuery('posts', (query : Post) => query.select('id','user_id','title'))
2336
+ .findMany()
2337
+
2338
+ // Where some columns in nested relations
2339
+ await new User()
2340
+ .relations('posts')
2341
+ .relationQuery('posts', (query : Post) => query.whereIn('id',[1,3,5]))
2342
+ .findMany()
2343
+
2344
+ // Sort data in nested relations
2345
+ await new User()
2346
+ .relations('posts')
2347
+ .relationQuery('posts', (query : Post) => query.latest('id'))
2348
+ .findMany()
2349
+
2350
+ // Limit data in nested relations
2351
+ await new User()
2352
+ .relations('posts')
2353
+ .relationQuery('posts', (query : Post) => {
2354
+ return query
2355
+ .limit(1)
2356
+ .relations('comments')
2357
+ .relationQuery('comments', (query : Comment) => query.limit(1))
2358
+ })
2359
+ .findMany()
2360
+
2361
+ ```
2362
+
2363
+ #### Relation Exists
2364
+
2365
+ Relationships can return results only if they are not empty in relations, considering soft deletes.
2366
+ Let's illustrate this with an example of an existence check in relations:
2367
+
2368
+ ```js
2369
+ +-------------+--------------+----------------------------+--------------------+
2370
+ | table users | |
2371
+ +-------------+--------------+----------------------------+--------------------+
2372
+ | id | username | email | deleted_at |
2373
+ |-------------|--------------|----------------------------|--------------------|
2374
+ | 1 | tspace1 | tspace1@gmail.com | |
2375
+ | 2 | tspace2 | tspace2@gmail.com | |
2376
+ | 3 | tspace3 | tspace3@gmail.com | |
2377
+ +-------------+--------------+----------------------------+--------------------+
2378
+
2379
+
2380
+ +-------------+--------------+----------------------------+--------------------+
2381
+ | table posts | |
2382
+ +-------------+--------------+----------------------------+--------------------+
2383
+ | id | user_id | title | deleted_at |
2384
+ |-------------|--------------|----------------------------|--------------------|
2385
+ | 1 | 1 | posts 1 |2020-07-15 00:00:00 |
2386
+ | 2 | 2 | posts 2 | |
2387
+ | 3 | 3 | posts 3 |2020-07-15 00:00:00 |
2388
+ +-------------+--------------+----------------------------+--------------------+
2389
+
2390
+ import { Model } from 'tspace-mysql'
2391
+
2392
+ class User extends Model {
2393
+ constructor(){
2394
+ super()
2395
+ this.hasMany({ name : 'posts' , model : Post })
2396
+ this.useSoftDelete()
2397
+ }
2398
+ }
2399
+
2400
+ +--------------------------------------------------------------------------+
2401
+
2402
+ class Post extends Model {
2403
+ constructor(){
2404
+ super()
2405
+ this.hasMany({ name : 'comments' , model : Comment })
2406
+ this.belongsTo({ name : 'user' , model : User })
2407
+ this.useSoftDelete()
2408
+ }
2409
+ }
2410
+ // normal relations
2411
+ await new User().relations('posts').findMany()
2412
+ // SELECT * FROM `users` WHERE `users`.`deleted_at`;
2413
+ // SELECT * FROM `posts` WHERE `posts`.`userId` IN (...) AND `posts`.`deleted_at` IS NULL;
2414
+
2415
+ /*
2416
+ * @returns [
2417
+ * {
2418
+ * id : 1,
2419
+ * username: "tspace1",
2420
+ * email : "tspace1@gmail.com",
2421
+ * posts : []
2422
+ * },
2423
+ * {
2424
+ * id : 2,
2425
+ * username: "tspace2",
2426
+ * email : "tspace2@gmail.com",
2427
+ * posts : [
2428
+ * {
2429
+ * id : 2,
2430
+ * user_id : 2,
2431
+ * title : "posts 2"
2432
+ * }
2433
+ * ]
2434
+ * },
2435
+ * {
2436
+ * id : 3,
2437
+ * username: "tspace3",
2438
+ * email : "tspace3@gmail.com",
2439
+ * posts : []
2440
+ * }
2441
+ * ]
2442
+ */
2443
+
2444
+ await new User().relationsExists('posts').findMany()
2445
+ // SELECT * FROM `users` WHERE `users`.`deleted_at` IS NULL
2446
+ // AND EXISTS (SELECT 1 FROM `posts` WHERE `users`.`id` = `posts`.`user_id` AND `posts`.`deletedA_at` IS NULL);
2447
+
2448
+ // SELECT * FROM `posts` WHERE `posts`.`user_id` IN (...) AND `posts`.`deleted_at` IS NULL;
2449
+
2450
+ /*
2451
+ * @returns [
2452
+ * {
2453
+ * id : 2,
2454
+ * username: "tspace2",
2455
+ * email : "tspace2@gmail.com",
2456
+ * posts : [
2457
+ * {
2458
+ * id : 2,
2459
+ * user_id : 2,
2460
+ * title : "posts 2"
2461
+ * }
2462
+ * ]
2463
+ * }
2464
+ * ]
2465
+ * because posts id 1 and id 3 has been removed from database (using soft delete)
2466
+ */
2467
+
2468
+ ```
2469
+
2470
+ #### Relation Count
2471
+ Relationships will retrieving the count of related records without loading the data of related models
2472
+ Let's illustrate this with an example of an existence check in relations:
2473
+ ```js
2474
+
2475
+ +-------------+--------------+----------------------------+
2476
+ | table users |
2477
+ +-------------+--------------+----------------------------+
2478
+ | id | username | email |
2479
+ |-------------|--------------|----------------------------|
2480
+ | 1 | tspace1 | tspace1@gmail.com |
2481
+ | 2 | tspace2 | tspace2@gmail.com |
2482
+ +-------------+--------------+----------------------------+
2483
+
2484
+ +-------------+--------------+----------------------------+
2485
+ | table posts |
2486
+ +-------------+--------------+----------------------------+
2487
+ | id | user_id | title |
2488
+ |-------------|--------------|----------------------------|
2489
+ | 1 | 1 | posts 1 |
2490
+ | 2 | 1 | posts 2 |
2491
+ | 3 | 2 | posts 3 |
2492
+ +-------------+--------------+----------------------------+
2493
+
2494
+ import { Model } from 'tspace-mysql'
2495
+
2496
+ class User extends Model {
2497
+ constructor(){
2498
+ super()
2499
+ this.hasMany({ name : 'posts' , model : Post })
2500
+ this.useSoftDelete()
2501
+ }
2502
+ }
2503
+
2504
+ // you also use .withCount()
2505
+ await new User().relationsCount('posts').findMany()
2506
+ // SELECT * FROM `users` WHERE `users`.`deleted_at` IS NULL;
2507
+
2508
+ // SELECT `posts`.`user_id`, COUNT(`user_id`) AS `aggregate` FROM `posts`
2509
+ // WHERE `posts`.`user_id` IN ('1','2') AND `posts`.`deleted_at` IS NULL GROUP BY `posts`.`user_id`;
2510
+
2511
+ /*
2512
+ * @returns [
2513
+ * {
2514
+ * id : 1,
2515
+ * username: "tspace1",
2516
+ * email : "tspace1@gmail.com",
2517
+ * posts : 2
2518
+ * }
2519
+ * {
2520
+ * id : 2,
2521
+ * username: "tspace2",
2522
+ * email : "tspace2@gmail.com",
2523
+ * posts : 1
2524
+ * }
2525
+ * ]
2526
+ */
2527
+
2528
+ ```
2529
+
2530
+ #### Relation Trashed
2531
+ Relationships can return results only if they are deleted in table, considering soft deletes.
2532
+ Let's illustrate this with an example:
2533
+ ```js
2534
+
2535
+ +-------------+--------------+----------------------------+--------------------+
2536
+ | table users | |
2537
+ +-------------+--------------+----------------------------+--------------------+
2538
+ | id | username | email | deleted_at |
2539
+ |-------------|--------------|----------------------------|--------------------|
2540
+ | 1 | tspace1 | tspace1@gmail.com | |
2541
+ | 2 | tspace2 | tspace2@gmail.com | |
2542
+ | 3 | tspace3 | tspace3@gmail.com |2020-07-15 00:00:00 |
2543
+ +-------------+--------------+----------------------------+--------------------+
2544
+
2545
+ +-------------+--------------+----------------------------+--------------------+
2546
+ | table posts | |
2547
+ +-------------+--------------+----------------------------+--------------------+
2548
+ | id | user_id | title | deleted_at |
2549
+ |-------------|--------------|----------------------------|--------------------|
2550
+ | 1 | 1 | posts 1 |2020-07-15 00:00:00 |
2551
+ | 2 | 2 | posts 2 | |
2552
+ | 3 | 3 | posts 3 |2020-07-15 00:00:00 |
2553
+ +-------------+--------------+----------------------------+--------------------+
2554
+
2555
+ import { Model } from 'tspace-mysql'
2556
+
2557
+ class User extends Model {
2558
+ constructor(){
2559
+ super()
2560
+ this.hasMany({ name : 'posts' , model : Post })
2561
+ this.useSoftDelete()
2562
+ }
2563
+ }
2564
+
2565
+ +--------------------------------------------------------------------------+
2566
+
2567
+ class Post extends Model {
2568
+ constructor(){
2569
+ super()
2570
+ this.hasMany({ name : 'comments' , model : Comment })
2571
+ this.belongsTo({ name : 'user' , model : User })
2572
+ this.useSoftDelete()
2573
+ }
2574
+ }
2575
+
2576
+ // normal relations
2577
+ await new User().relations('posts').findMany()
2578
+ // SELECT * FROM `users` WHERE `users`.`deleted_at` IS NULL;
2579
+ // SELECT * FROM `posts` WHERE `posts`.`user_id` IN (...) AND `posts`.`deleted_at` IS NULL;
2580
+
2581
+ /*
2582
+ * @returns [
2583
+ * {
2584
+ * id : 1,
2585
+ * username: "tspace1",
2586
+ * email : "tspace1@gmail.com",
2587
+ * posts : []
2588
+ * }
2589
+ * {
2590
+ * id : 2,
2591
+ * username: "tspace2",
2592
+ * email : "tspace2@gmail.com",
2593
+ * posts : [
2594
+ * {
2595
+ * id : 2,
2596
+ * user_id : 2,
2597
+ * title : "posts 2"
2598
+ * }
2599
+ * ]
2600
+ * }
2601
+ * ]
2602
+ */
2603
+
2604
+ // relationsTrashed
2605
+ await new User().relationsTrashed('posts').findMany()
2606
+ // SELECT * FROM `users` WHERE `users`.`deleted_at` IS NULL;
2607
+ // SELECT * FROM `posts` WHERE `posts`.`user_id` IN (...) AND `posts`.`deleted_at` IS NOT NULL;
2608
+
2609
+ /*
2610
+ * @returns [
2611
+ * {
2612
+ * id : 1,
2613
+ * username: "tspace1",
2614
+ * email : "tspace1@gmail.com",
2615
+ * posts : [
2616
+ * {
2617
+ * id : 1,
2618
+ * user_id : 1,
2619
+ * title : "posts 1"
2620
+ * }
2621
+ * ]
2622
+ * }
2623
+ * {
2624
+ * id : 2,
2625
+ * username: "tspace2",
2626
+ * email : "tspace2@gmail.com",
2627
+ * posts : []
2628
+ * }
2629
+ * ]
2630
+ */
2631
+
2632
+ // relationsTrashed + trashed
2633
+ await new User().relationsTrashed('posts').trashed().findMany()
2634
+ // SELECT * FROM `users` WHERE `users`.`deleted_at` IS NOT NULL;
2635
+ // SELECT * FROM `posts` WHERE `posts`.`user_id` IN (...) AND `posts`.`deleted_at` IS NOT NULL;
2636
+ /*
2637
+ * @returns [
2638
+ * {
2639
+ * id : 3,
2640
+ * username: "tspace3",
2641
+ * email : "tspace3@gmail.com",
2642
+ * posts : [
2643
+ * {
2644
+ * id : 3,
2645
+ * user_id : 3,
2646
+ * title : "posts 3"
2647
+ * }
2648
+ * ]
2649
+ * }
2650
+ * ]
2651
+ */
2652
+
2653
+ ```
2654
+
2655
+ ### Built in Relation Functions
2656
+ Certainly, let's illustrate the use of a built-in function in the results of relationships:
2657
+
2658
+ ```js
2659
+ import { Model } from 'tspace-mysql'
2660
+
2661
+ class User extends Model {
2662
+ constructor(){
2663
+ super()
2664
+ this.hasMany({ name : 'posts' , model : Post })
2665
+ this.useBuiltInRelationFunctions()
2666
+ }
2667
+ }
2668
+ +--------------------------------------------------------------------------+
2669
+ class Post extends Model {
2670
+ constructor(){
2671
+ super()
2672
+ this.hasMany({ name : 'comments' , model : Comment })
2673
+ this.belongsTo({ name : 'user' , model : User })
2674
+ this.useBuiltInRelationFunctions()
2675
+ }
2676
+ }
2677
+ +--------------------------------------------------------------------------+
2678
+ class Comment extends Model {
2679
+ constructor(){
2680
+ super()
2681
+ this.hasMany({ name : 'users' , model : User })
2682
+ this.belongsTo({ name : 'post' , model : Post })
2683
+ this.useBuiltInRelationFunctions()
2684
+ }
2685
+ }
2686
+ +--------------------------------------------------------------------------+
2687
+ const user = await new User().findOne()
2688
+ const posts = await user.$posts()
2689
+
2690
+ /** Warning built-in function has Big-O effect */
2691
+ for (const post of posts) {
2692
+ const comments = await post.$comments()
2693
+ }
2694
+
2695
+ ```
2696
+
2697
+ ### Cache
2698
+
2699
+ Cache can be used in a Model.
2700
+ Let's illustrate this with an example of a cache:
2701
+
2702
+ ```js
2703
+ // support memory db and redis
2704
+ // set cache in file config .env , .env.development ... etc
2705
+ DB_CACHE = memory // by default
2706
+
2707
+ // for db
2708
+ DB_CACHE = db
2709
+
2710
+ // for redis
2711
+ DB_CACHE = redis://username:password@server:6379
2712
+
2713
+ const users = await new User()
2714
+ .cache({
2715
+ key : 'users1', // key of the cache
2716
+ expires : 1000 * 60, // cache expires in 60 seconds
2717
+ namespace : true // add namespace to the key of the cache like that 'db:users:users1' to avoid conflicts with other keys in cache
2718
+ })
2719
+ .sleep(5) // assume the query takes longer than 5 seconds...
2720
+ .findMany()
2721
+
2722
+ // delete cache by key
2723
+ User.cache.delete('users1', { namespace : true })
2724
+
2725
+ ```
2726
+
2727
+ ### Decorator
2728
+
2729
+ Decorators can be used in a Model.
2730
+ Let's illustrate this with an example of a decorators:
2731
+
2732
+ ```js
2733
+
2734
+ import {
2735
+ Blueprint, Model ,
2736
+ Table ,TableSingular, TablePlural,
2737
+ UUID, SoftDelete, Timestamp,
2738
+ Pattern, CamelCase , snakeCase ,
2739
+ Column, Validate, Observer
2740
+ } from 'tspace-mysql'
2741
+ import { Post } from './Post'
2742
+ import { PostUser } from './PostUser'
2743
+
2744
+ class UserObserve {
2745
+
2746
+ public selected(results) {
2747
+ console.log({ results , selected : true })
2748
+ }
2749
+
2750
+ public created(results) {
2751
+ console.log({ results , created : true })
2752
+ }
2753
+
2754
+ public updated(results) {
2755
+ console.log({ results , updated : true })
2756
+ }
2757
+
2758
+ public deleted(results) {
2759
+ console.log({ results , deleted : true })
2760
+ }
2761
+ }
2762
+
2763
+ @Pattern('camelCase')
2764
+ @Observer(UserObserve)
2765
+ @UUID()
2766
+ @SoftDelete()
2767
+ @Timestamp()
2768
+ @Table('users')
2769
+ class User extends Model {
2770
+
2771
+ @Column(() => Blueprint.int().notNull().primary().autoIncrement())
2772
+ public id!: number
2773
+
2774
+ @Column(() => Blueprint.varchar(50).null())
2775
+ public uuid!: string
2776
+
2777
+ @Column(() => Blueprint.varchar(50).null())
2778
+ @Validate({
2779
+ type : String,
2780
+ require : true,
2781
+ length : 50,
2782
+ match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
2783
+ unique : true,
2784
+ fn : (email : string) => /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
2785
+ })
2786
+ public email!: string
2787
+
2788
+ @Column(() => Blueprint.varchar(50).null())
2789
+ public name !: string
2790
+
2791
+ @Column(() => Blueprint.varchar(50).null())
2792
+ public username !: string
2793
+
2794
+ @Column(() => Blueprint.varchar(50).null())
2795
+ public password !: string
2796
+
2797
+ @Column(() => Blueprint.timestamp().null())
2798
+ public createdAt!: Date
2799
+
2800
+ @Column(() => Blueprint.timestamp().null())
2801
+ public updatedAt!: Date
2802
+
2803
+ @Column(() => Blueprint.timestamp().null())
2804
+ public deletedAt!: Date
2805
+
2806
+ }
2807
+
2808
+ export { User }
2809
+ export default User
2810
+
2811
+ ```
2812
+
2813
+ ### Schema
2814
+
2815
+ The schema refers to the structure of the database as it pertains to the objects and classes in the model.
2816
+ using the following:
2817
+
2818
+ #### Schema Model
2819
+
2820
+ ```js
2821
+ import { Model, Blueprint , type T } from "tspace-mysql";
2822
+
2823
+ const schema = {
2824
+ id: Blueprint.int().notNull().primary().autoIncrement(),
2825
+ uuid: Blueprint.varchar(50).null().index(),
2826
+ name: Blueprint.varchar(191).notNull(),
2827
+ email: Blueprint.varchar(191).notNull(),
2828
+ createdAt: Blueprint.timestamp().null(),
2829
+ updatedAt: Blueprint.timestamp().null(),
2830
+ deletedAt: Blueprint.timestamp().null()
2831
+ }
2832
+
2833
+
2834
+ // make type in TS
2835
+ type TS = T.Schema<typeof Schema>
2836
+
2837
+ // the TSchemaUser will be created like that
2838
+ /**
2839
+ {
2840
+ id : number,
2841
+ uuid : string | null,
2842
+ name : string,
2843
+ email : string,
2844
+ createdAt : Date | string | null,
2845
+ updatedAt : Date | string | null,
2846
+ deletedAt : Date | string | null
2847
+ }
2848
+ */
2849
+
2850
+
2851
+ class User extends Model<TS> // use the schema for this User model
2852
+ {
2853
+ constructor() {
2854
+ super();
2855
+ this.useCamelCase()
2856
+ this.useSchema(schema)
2857
+ }
2858
+ }
2859
+
2860
+ ```
2861
+
2862
+ #### Virtual Column
2863
+ ```js
2864
+
2865
+ import { Model, Blueprint , type T } from "tspace-mysql";
2866
+
2867
+ const schema = {
2868
+ id: Blueprint.int().notNull().primary().autoIncrement(),
2869
+ uuid: Blueprint.varchar(50).null().index(),
2870
+ firstName: Blueprint.varchar(191).notNull(),
2871
+ lastName : Blueprint.varchar(191).notNull(),
2872
+ email: Blueprint.varchar(191).notNull(),
2873
+ createdAt: Blueprint.timestamp().null(),
2874
+ updatedAt: Blueprint.timestamp().null(),
2875
+ deletedAt: Blueprint.timestamp().null(),
2876
+
2877
+ // Define you virtual column to schema
2878
+ fullName : new Blueprint().virtualColumn(`CONCAT(firstName,' ', lastName)`),
2879
+ countPosts : new Blueprint().virtualColumn(`(SELECT COUNT(*) FROM posts WHERE posts.userid = users.id)`)
2880
+
2881
+ // if you need to custom the virtualColumn column for some method.
2882
+ // fullName : new Blueprint().virtualColumn({
2883
+ // select : `CONCAT(firstName,' ', lastName)`,
2884
+ // where : `CONCAT(firstName,' ', lastName)`,
2885
+ // orderBy : `CONCAT(firstName,' ', lastName)`,
2886
+ // groupBy : `CONCAT(firstName,' ', lastName)`,
2887
+ // }),
2888
+ }
2889
+
2890
+ type TS = T.Schema<typeof Schema>
2891
+
2892
+ class User extends Model<TS> {
2893
+ constructor() {
2894
+ super();
2895
+ this.useSchema(schema)
2896
+ }
2897
+ }
2898
+ const users = await new User()
2899
+ .select('id','firstName','lastName','fullName','countPosts')
2900
+ .where('fullName','LIKE',`%tspace-mysql%`)
2901
+ .orderBy('fullName','desc')
2902
+ .groupBy('fullName')
2903
+ .findMany()
2904
+
2905
+ // SELECT
2906
+ // `users`.`id`, `users`.`firstName`, `users`.`lastName`,
2907
+ // CONCAT(firstName,' ', lastName) AS fullName ,
2908
+ // (SELECT COUNT(*) FROM posts WHERE posts.userid = users.id) AS countPosts
2909
+ // FROM `users`
2910
+ // WHERE CONCAT(firstName,' ', lastName) LIKE '%tspace-mysql%'
2911
+ // GROUP BY CONCAT(firstName,' ', lastName)
2912
+ // ORDER BY CONCAT(firstName,' ', lastName) DESC
2913
+
2914
+ ```
2915
+
2916
+ #### Validation
2917
+
2918
+ Validate the schema of Model
2919
+ let's example a validator model:
2920
+
2921
+ ```js
2922
+ import { Model, Blueprint } from "tspace-mysql";
2923
+ class User extends Model {
2924
+ constructor() {
2925
+ super();
2926
+ this.useCamelCase();
2927
+ this.useSchema({
2928
+ id: Blueprint.int().notNull().primary().autoIncrement(),
2929
+ uuid: Blueprint.varchar(50).null(),
2930
+ name: Blueprint.varchar(191).notNull(),
2931
+ email: Blueprint.varchar(191).notNull(),
2932
+ createdAt: Blueprint.timestamp().null(),
2933
+ updatedAt: Blueprint.timestamp().null(),
2934
+ deletedAt: Blueprint.timestamp().null(),
2935
+ });
2936
+
2937
+ // validate input when create or update reference to the schema in 'this.useSchema'
2938
+ this.useValidateSchema({
2939
+ id: Number,
2940
+ uuid: Number,
2941
+ name: {
2942
+ type: String,
2943
+ length: 191,
2944
+ require: true,
2945
+ json: true,
2946
+ },
2947
+ email: {
2948
+ type: String,
2949
+ require: true,
2950
+ length: 191,
2951
+ match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
2952
+ unique: true,
2953
+ fn: (email: string) => {
2954
+ return /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(email)
2955
+ }
2956
+ },
2957
+ createdAt: Date,
2958
+ updatedAt: Date,
2959
+ deletedAt: Date,
2960
+ });
2961
+ }
2962
+ }
2963
+ ```
2964
+
2965
+ #### Sync
2966
+
2967
+ Sync the schema with the "Models" setting in your directory.
2968
+ This process will verify and update table columns and foreign keys as needed.
2969
+ Ensure that the relationships are correctly established through the 'useSchema' method in your models.
2970
+ Let's examine a basic sync class:
2971
+
2972
+ ```js
2973
+ /**
2974
+ *
2975
+ * @Ex directory
2976
+ *
2977
+ * - node_modules
2978
+ * - src
2979
+ * - index.ts
2980
+ * - Models
2981
+ * - User.ts
2982
+ * - Post.ts
2983
+ */
2984
+
2985
+ // file User
2986
+ class User extends Model {
2987
+ constructor() {
2988
+ super();
2989
+ this.hasMany({ name: "posts", model: Post });
2990
+
2991
+ // if you need to initialize data when creating the table, you can use the following.
2992
+ this.whenCreatingTable(async () => {
2993
+ return await new User()
2994
+ .create({
2995
+ ...columns,
2996
+ })
2997
+ .void()
2998
+ .save();
2999
+ });
3000
+
3001
+ this.useSchema({
3002
+ id: Blueprint.int().notNull().primary().autoIncrement(),
3003
+ uuid: Blueprint.varchar(50).null(),
3004
+ email: Blueprint.int().notNull().unique(),
3005
+ name: Blueprint.varchar(255).null(),
3006
+ created_at: Blueprint.timestamp().null(),
3007
+ updated_at: Blueprint.timestamp().null(),
3008
+ deleted_at: Blueprint.timestamp().null(),
3009
+ });
3010
+ }
3011
+ }
3012
+
3013
+ // file Post
3014
+ import User from "./User";
3015
+ class Post extends Model {
3016
+ constructor() {
3017
+ super();
3018
+ this.hasMany({ name: "comments", model: Comment });
3019
+ this.belongsTo({ name: "user", model: User });
3020
+ this.useSchema({
3021
+ id: Blueprint.int().notNull().primary().autoIncrement(),
3022
+ uuid: Blueprint.varchar(50).null(),
3023
+ user_id: Blueprint.int().notNull().foreign({
3024
+ references: "id",
3025
+ on: User,
3026
+ onDelete: "CASCADE",
3027
+ onUpdate: "CASCADE",
3028
+ }),
3029
+ title: Blueprint.varchar(255).null(),
3030
+ created_at: Blueprint.timestamp().null(),
3031
+ updated_at: Blueprint.timestamp().null(),
3032
+ deleted_at: Blueprint.timestamp().null(),
3033
+ });
3034
+ }
3035
+ }
3036
+
3037
+ await Schema.sync(`/src/Models`, {
3038
+ force: true,
3039
+ log: true,
3040
+ foreign: true,
3041
+ changed: true,
3042
+ });
3043
+
3044
+ // You can also synchronize using the Model.
3045
+ await new User().sync({ force: true, foreign: true, changed: true });
3046
+ ```
3047
+
3048
+ ### SoftDelete
3049
+
3050
+ ```js
3051
+
3052
+ import { Model } from 'tspace-mysql'
3053
+ class User extends Model {
3054
+ constructor() {
3055
+ super()
3056
+ this.useSoftDelete() // All query will be where 'deleted_at' is null
3057
+
3058
+ // You can also use patterns camelCase to covert the 'deleted_at' to 'deletedAt'
3059
+ // You can also customize the column 'deleted_at'
3060
+ this.useSoftDelete('deletedAtCustom')
3061
+ }
3062
+ }
3063
+
3064
+ const user = await new User().where('user_id',1).findOne()
3065
+ // SELECT * FROM `users` WHERE `users`.`userId` = '1' and `users`.`deletedAtCustom` IS NULL LIMIT 1;
3066
+
3067
+ // find in trashed
3068
+ const user = await new User().trashed().findMany()
3069
+ // SELECT * FROM `users` WHERE `users`.`userId` = '1' and `users`.`deletedAtCustom` IS NOT NULL;
3070
+
3071
+ ```
3072
+
3073
+ ### Type Safety
3074
+ Type Type Safety in TypeScript refers to the ability of the language to detect and prevent type errors during compile-time.
3075
+ Type Type Safety still works when you add additional types to your model, using the following:
3076
+
3077
+ ```js
3078
+ // in file User.ts
3079
+ import { Model , Blueprint , type T } from 'tspace-mysql'
3080
+ import Phone from '../Phone'
3081
+
3082
+ const schemaUser = {
3083
+ id :Blueprint.int().notNull().primary().autoIncrement(),
3084
+ uuid :Blueprint.varchar(50).null(),
3085
+ email :Blueprint.varchar(50).null(),
3086
+ name :Blueprint.varchar(255).null(),
3087
+ username : Blueprint.varchar(255).null(),
3088
+ password : Blueprint.varchar(255).null(),
3089
+ createdAt :Blueprint.timestamp().null(),
3090
+ updatedAt :Blueprint.timestamp().null()
3091
+ }
3092
+
3093
+ type TSchemaUser = T.SchemaStatic<typeof schemaUser>
3094
+ // TSchemaUser = T.Schema<typeof schemaUser>
3095
+
3096
+ // TSchema allowed to set any new keys without in the schema to results
3097
+ // TSchemaStatic not allowed to set any new keys without in the schema to results
3098
+
3099
+ class User extends Model<TSchemaUser> { // Add this '<TSchemaUser>' to activate the type for the Model.
3100
+ constructor() {
3101
+ super()
3102
+ this.useSchema(schemaUser)
3103
+ this.hasOne({ model : Phone, name : 'phone' })
3104
+ this.hasMany({ model : Phone, name : 'phones' })
3105
+ }
3106
+ }
3107
+
3108
+ export { User }
3109
+ export default User
3110
+
3111
+ +--------------------------------------------------------------------------+
3112
+
3113
+ // in file Phone.ts
3114
+ import { Model , Blueprint , type T } from 'tspace-mysql'
3115
+ import { User } from './User.ts'
3116
+ const schemaPhone = {
3117
+ id :Blueprint.int().notNull().primary().autoIncrement(),
3118
+ uuid :Blueprint.varchar(50).null(),
3119
+ userId : Blueprint.int().notNull(),
3120
+ number :Blueprint.varchar(50).notNull(),
3121
+ createdAt :Blueprint.timestamp().null(),
3122
+ updatedAt :Blueprint.timestamp().null()
3123
+ }
3124
+
3125
+ type TSchemaPhone = T.SchemaStatic<typeof schemaPhone>
3126
+
3127
+ class Phone extends Model<TSchemaPhone> {
3128
+ constructor() {
3129
+ super()
3130
+ this.useSchema(schemaPhone)
3131
+ this.useBelongsTo({ model : User, name : 'user'})
3132
+ }
3133
+ }
3134
+
3135
+ export { Phone }
3136
+ export default Phone
3137
+
3138
+ // example basic
3139
+ type TS = T.Schema<typeof TSchemaUser>
3140
+ type TR = T.Relation<{ phone : Phone }>
3141
+
3142
+ type TSM = T.SchemaModel<User>
3143
+ type TRM = T.RelationModel<User>
3144
+
3145
+ type TColumn = T.Column<User>
3146
+
3147
+ type TResults = T.Results<User>
3148
+ type TPaginateResults = T.Results<User, { paginate : true }>
3149
+
3150
+ type TRepository = T.Repository<User>
3151
+ type TRepositoryTypeOf = T.RepositoryTypeOf<User>
3152
+
3153
+ +--------------------------------------------------------------------------+
3154
+ ```
3155
+
3156
+ ### Type Safety Select
3157
+
3158
+ ```js
3159
+ import { User } from './User.ts'
3160
+ import { Phone } from './Phone.ts'
3161
+
3162
+ const user = await new User().select('id','username').findOne() ✅
3163
+ const user = await new User().select('idx','username').findOne() ❌
3164
+
3165
+ const user = await new User().except('id','username').findOne() ✅
3166
+ const user = await new User().except('idx','username').findOne() ❌
3167
+
3168
+ // T.SchemaStatic not allowed to set any new keys without in the schema to results
3169
+ user.withoutSchema = 1 ✅ // T.Schema<User>
3170
+ user.withoutSchema = 1 ❌ // T.SchemaStatic<User>
3171
+ // But can you make like this for cases
3172
+ const user = await new User().except('idx','username').findOne<{ withoutSchema : number }>()
3173
+ user.withoutSchema = 1 ✅
3174
+ ```
3175
+
3176
+ ### Type Safety OrderBy
3177
+
3178
+ ```js
3179
+ import { User } from './User.ts'
3180
+ import { Phone } from './Phone.ts'
3181
+
3182
+ const users = await new User().orderBy('id','DESC').findMany() ✅
3183
+ const users = await new User().orderBy('idx','DESC').findMany() ❌
3184
+
3185
+ const users = await new User().latest('id').findMany() ✅
3186
+ const users = await new User().latest('idx').findMany() ❌
3187
+
3188
+ const users = await new User().oldest('id').findMany() ✅
3189
+ const users = await new User().oldest('idx').findMany() ❌
3190
+
3191
+ ```
3192
+
3193
+ ### Type Safety GroupBy
3194
+
3195
+ ```js
3196
+ import { User } from './User.ts'
3197
+ import { Phone } from './Phone.ts'
3198
+
3199
+ const users = await new User().groupBy('id').findMany() ✅
3200
+ const users = await new User().groupBy('idx').findMany() ❌
3201
+
3202
+ ```
3203
+
3204
+ ### Type Safety Where
3205
+
3206
+ ```js
3207
+ import { User } from './User.ts'
3208
+ import { Phone } from './Phone.ts'
3209
+
3210
+ const users = await new User().where('id',1).findMany() ✅
3211
+ const users = await new User().where('idxx',1).findMany() ❌
3212
+
3213
+ const users = await new User().where('id',1).orWhere('id',5).findMany() ✅
3214
+ const users = await new User().where('id',1).orWhere('idxx',5).findMany() ❌
3215
+
3216
+ const users = await new User().whereIn('id',[1]).findMany() ✅
3217
+ const users = await new User().whereIn('idx',[1]).findMany() ❌
3218
+
3219
+ const users = await new User().whereNull('id').findMany() ✅
3220
+ const users = await new User().whereNull('idx').findMany() ❌
3221
+
3222
+ const users = await new User().whereNotNull('id').findMany()
3223
+ const users = await new User().whereNotNull('idx').findMany()
3224
+
3225
+ const users = await new User().whereBetween('id',[1,2]).findMany() ✅
3226
+ const users = await new User().whereBetween('idx',[1,2]).findMany() ❌
3227
+
3228
+ const users = await new User()
3229
+ .whereSubQuery(
3230
+ 'id',
3231
+ new User().select('id').toString()
3232
+ ).findMany() ✅
3233
+
3234
+ const users = await new User()
3235
+ .whereSubQuery(
3236
+ 'idx',
3237
+ new User().select('id').toString()
3238
+ ).findMany() ❌
3239
+
3240
+ ```
3241
+
3242
+ ### Type Safety Insert
3243
+
3244
+ ```js
3245
+ import { User } from './User.ts'
3246
+ import { Phone } from './Phone.ts'
3247
+
3248
+ const users = await new User().create({ id : 10 }).save() ✅
3249
+
3250
+ const users = await new User().create({ id : "10" }).save() ❌
3251
+
3252
+ const users = await new User().create({ idx : 10 }).save() ❌
3253
+
3254
+ ```
3255
+
3256
+ ### Type Safety Update
3257
+
3258
+ ```js
3259
+ import { User } from './User.ts'
3260
+ import { Phone } from './Phone.ts'
3261
+
3262
+ const users = await new User().update({ id : 10 }).where('id',1).save() ✅
3263
+ const users = await new User().update({ id : 10 }).where('idx',1).save() ❌
3264
+ const users = await new User().update({ id : "10" }).where('id',1).save() ❌
3265
+ const users = await new User().update({ idx : 10 }).where('idx',1).save() ❌
3266
+
3267
+ ```
3268
+
3269
+ ### Type Safety Delete
3270
+
3271
+ ```js
3272
+ import { User } from './User.ts'
3273
+ import { Phone } from './Phone.ts'
3274
+
3275
+ const users = await new User().where('id',1).delete() ✅
3276
+ const users = await new User().where('idx',1).delete() ❌
3277
+
3278
+ ```
3279
+
3280
+ ### Type Safety Relationships
3281
+
3282
+ ```js
3283
+ import { type T } from 'tspace-mysql'
3284
+ import { User } from './User.ts'
3285
+ import { Phone } from './Phone.ts'
3286
+ // Case #1 : Relationship with 2 relations 'phone' and 'phones'
3287
+ const users = await new User()
3288
+ .relations('phone','phones')
3289
+ .findMany()
3290
+
3291
+ for(const user of users) {
3292
+ user.phone ❌
3293
+ user.phones ❌
3294
+ }
3295
+
3296
+ // You can also specify the type for the results.
3297
+ // bad 👎👎👎
3298
+ const users = await new User()
3299
+ .relations('phone','phones')
3300
+ .findMany<{ phone : Record<string,any> , phones : any[]}>()
3301
+
3302
+ for(const user of users) {
3303
+ user.phone ✅
3304
+ user.phones ✅
3305
+ user.phone.id ✅
3306
+ user.phone.idx ✅💩💩💩
3307
+ user.phones.map(phone => phone.id) ✅
3308
+ user.phones.map(phone => phone.idx) ✅💩💩💩
3309
+ }
3310
+
3311
+ // good 👍👍👍
3312
+ const users = await new User()
3313
+ .relations('phone','phones')
3314
+ .findMany<{ phone : T.SchemaModel<Phone> , phones : T.SchemaModel<Phone>[] }>()
3315
+
3316
+ for(const user of users) {
3317
+ user.phone ✅
3318
+ user.phones ✅
3319
+ user.phone?.id ✅
3320
+ user.phone?.idx ❌
3321
+ user.phones.map(phone => phone?.id) ✅
3322
+ user.phones.map(phone => phone?.idx) ❌
3323
+ }
3324
+
3325
+ +--------------------------------------------------------------------------+
3326
+
3327
+ // Case #2 : There is a relationship between two entities, 'phone' and 'phones', both of which are related to the 'user' entity through nested relations
3328
+ const users = await new User()
3329
+ .relations('phone','phones')
3330
+ .relationQuery('phone' , (query : Phone) => query.relations('user'))
3331
+ .relationQuery('phones' , (query : Phone) => query.relations('user'))
3332
+ .findMany<{ phone : T.SchemaModel<Phone> , phones : T.SchemaModel<Phone>[] }>()
3333
+
3334
+ for(const user of users) {
3335
+ user.phone.user ❌
3336
+ user.phones.map(phone =>phone.user) ❌
3337
+ }
3338
+
3339
+ // You can also specify the type for the results.
3340
+ // bad 👎👎👎
3341
+ const users = await new User()
3342
+ .relations('phone','phones')
3343
+ .relationQuery('phone' , (query : Phone) => query.relations('user'))
3344
+ .relationQuery('phones' , (query : Phone) => query.relations('user'))
3345
+ .findMany<{ phone : Record<string,any> , phones : Record<string,any>[] }>()
3346
+
3347
+ for(const user of users) {
3348
+ user.phone.user ✅💩💩💩
3349
+ user.phones.map(phone =>phone.user) ✅💩💩💩
3350
+ user.phone.user.idx ✅💩💩💩
3351
+ user.phones.map(phone =>phone.user.idx) ✅💩💩💩
3352
+ }
3353
+
3354
+ // good 👍👍👍
3355
+ const users = await new User()
3356
+ .relations('phone','phones')
3357
+ .relationQuery('phone' , (query : Phone) => query.relations('user'))
3358
+ .relationQuery('phones' , (query : Phone) => query.relations('user'))
3359
+ .findMany<{
3360
+ phone : Partial<T.SchemaModel<Phone>> & { user : T.SchemaModel<User>};
3361
+ phones : (Partial<T.SchemaModel<Phone>> & { user : T.SchemaModel<User>})[];
3362
+ }>()
3363
+
3364
+ for(const user of users) {
3365
+ user.phone.user ✅
3366
+ user.phone.user.id ✅
3367
+ user.phone.userx ❌
3368
+ user.phone.user.idx ❌
3369
+ user.phones.map(phone =>phone.user.id) ✅
3370
+ user.phones.map(phone =>phone.user.idx) ❌
3371
+ }
3372
+
3373
+ +--------------------------------------------------------------------------+
3374
+ // If you don't want to set types for every returning method such as 'findOne', 'findMany', and so on...
3375
+
3376
+ import { Model , Blueprint , type T } from 'tspace-mysql'
3377
+ import { Phone } from '../Phone'
3378
+
3379
+ const schemaUser = {
3380
+ id :Blueprint.int().notNull().primary().autoIncrement(),
3381
+ uuid :Blueprint.varchar(50).null(),
3382
+ email :Blueprint.varchar(50).null(),
3383
+ name :Blueprint.varchar(255).null(),
3384
+ username :Blueprint.varchar(255).null(),
3385
+ password :Blueprint.varchar(255).null(),
3386
+ createdAt :Blueprint.timestamp().null(),
3387
+ updatedAt :Blueprint.timestamp().null()
3388
+ }
3389
+
3390
+ type TSchemaUser = T.SchemaStatic<typeof schemaUser>
3391
+
3392
+ type TRelationUser = T.Relation<{
3393
+ phones : Phone[]
3394
+ phone : Phone
3395
+ }>
3396
+
3397
+ // Add this '<TSchemaUser, RelationUserType>' to activate the type for the Model.
3398
+ class User extends Model< TSchemaUser, TRelationUser > {
3399
+ constructor() {
3400
+ super()
3401
+ this.useSchema(schemaUser)
3402
+ this.hasOne({ model : Phone, name : 'phonex' }) ❌
3403
+ this.hasMany({ model : Phone, name : 'phonesx' }) ❌
3404
+ this.hasOne({ model : Phone, name : 'phone' }) ✅
3405
+ this.hasMany({ model : Phone, name : 'phones' }) ✅
3406
+ }
3407
+ }
3408
+
3409
+ export { User }
3410
+
3411
+ +--------------------------------------------------------------------------+
3412
+
3413
+ // in file Phone.ts
3414
+ import { Model , Blueprint , type T } from 'tspace-mysql'
3415
+ import { User } from './User.ts'
3416
+
3417
+ const schemaPhone = {
3418
+ id :Blueprint.int().notNull().primary().autoIncrement(),
3419
+ uuid :Blueprint.varchar(50).null(),
3420
+ userId :Blueprint.int().notNull(),
3421
+ number :Blueprint.varchar(50).notNull(),
3422
+ createdAt :Blueprint.timestamp().null(),
3423
+ updatedAt :Blueprint.timestamp().null()
3424
+ }
3425
+
3426
+ type TSchemaPhone = T.Schema<typeof schemaPhone>
3427
+
3428
+ type TRelationPhone = T.Relation<{
3429
+ user : User[]
3430
+ }>
3431
+
3432
+ class Phone extends Model<TSchemaPhone,TRelationPhone> {
3433
+ constructor() {
3434
+ super()
3435
+ this.useSchema(schemaPhone)
3436
+ this.useBelongsTo({ model : User, name : 'userx'}) ❌
3437
+ this.useBelongsTo({ model : User, name : 'user'}) ✅
3438
+ }
3439
+ }
3440
+
3441
+ export { Phone }
3442
+
3443
+ +--------------------------------------------------------------------------+
3444
+
3445
+ const users = await new User()
3446
+ .relations('phonex','phonesx') ❌
3447
+ .relationQuery('phonex' ❌ , (query : Phone) => query.relations('user')) ✅
3448
+ .relationQuery('phonesx' ❌ , (query : Phone) => query.relations('user')) ✅
3449
+ .findMany()
3450
+
3451
+ const users = await new User()
3452
+ .relations('phone','phones') ✅
3453
+ .relationQuery('phonex' ❌ , (query : Phone) => query.relations('user')) ✅
3454
+ .relationQuery('phonesx' ❌ , (query : Phone) => query.relations('user')) ✅
3455
+ .findMany()
3456
+
3457
+ const users = await new User()
3458
+ .relations('phone','phones')
3459
+ .relationQuery('phone' , (query : Phone) => query.relations('userx')) ❌
3460
+ .relationQuery('phones' , (query : Phone) => query.relations('userx')) ❌
3461
+ .findMany()
3462
+
3463
+ const users = await new User()
3464
+ .relations('phone','phones') ✅
3465
+ .relationQuery('phone' ✅ , (query : Phone) => query.relations('user')) ✅
3466
+ .relationQuery('phones'✅ , (query : Phone) => query.relations('user')) ✅
3467
+ .findMany()
3468
+
3469
+ for(const user of users) {
3470
+ user.phone.user ❌
3471
+ user.phone?.user ✅
3472
+ user.phone?.user.id ✅
3473
+ user.phone?.userx ❌
3474
+ user.phone?.user.idx ❌
3475
+ user.phones.map(phone =>phone?.user.id) ❌
3476
+ user.phones?.map(phone =>phone?.user.id) ✅
3477
+ user.phones?.map(phone =>phone?.user.idx) ❌
3478
+ }
3479
+
3480
+ ```
3481
+
3482
+ ## Type Safety Results
3483
+ ```js
3484
+ import { type T } from 'tspace-mysql'
3485
+
3486
+ const fError = async () : Promise<T.Results<User>[]> => {
3487
+
3488
+ const users = [{
3489
+ id : 1,
3490
+ uuid: "12d4f08a-a20d-4f41-abac-81391e135d60",
3491
+ email: "tspace@example.com"
3492
+ }]
3493
+
3494
+ return users // ❌
3495
+ }
3496
+
3497
+ const fCorrect = async () : Promise<T.Results<User>[]> => {
3498
+
3499
+ const users = await new User().findMany()
3500
+
3501
+ return users // ✅
3502
+ }
3503
+
3504
+ ```
3505
+
3506
+ ## Metadata
3507
+ Get the metadata of a Model works only when a schema is added to the Model.
3508
+
3509
+ ```js
3510
+ import { Meta, Model , Blueprint , type T } from 'tspace-mysql';
3511
+
3512
+ const schema = {
3513
+ id : Blueprint.int().notNull().primary().autoIncrement(),
3514
+ uuid : Blueprint.varchar(50).null(),
3515
+ email : Blueprint.varchar(255).notNull().index('users.email@index'),
3516
+ name : Blueprint.varchar(255).null(),
3517
+ username : Blueprint.varchar(255).notNull(),
3518
+ password : Blueprint.varchar(255).notNull(),
3519
+ status : Blueprint.tinyInt().notNull().default(0),
3520
+ role : Blueprint.enum('admin','user').default('user'),
3521
+ createdAt : Blueprint.timestamp().null(),
3522
+ updatedAt : Blueprint.timestamp().null()
3523
+ }
3524
+
3525
+ type TS = T.Schema<typeof schema>
3526
+
3527
+ class User extends Model<TS> {
3528
+ constructor() {
3529
+ super()
3530
+ this.useSchema(schema)
3531
+ }
3532
+ }
3533
+
3534
+ const meta = Meta(User)
3535
+
3536
+ const table = meta.table() // 'users'
3537
+ const column = meta.column('id') // 'id'
3538
+ const columnRef = meta.columnReference('id') // `users`.`id`
3539
+ const columnTypeOf = meta.columnTypeOf('id') // number
3540
+ const columnType = meta.columnType('id') // Int
3541
+ const columns = meta.columns() // ['id','uuid',...'updatedAt']
3542
+ const hasColumn = meta.hasColumn('idx') // false
3543
+ const primaryKey = meta.primaryKey() // 'id'
3544
+ const indexes = meta.indexes() // ['users.email@index']
3545
+ const nullable = meta.nullable() // ['uuid','name','createdAt','updatedAt']
3546
+ const defaults = meta.defaults() // { id : null, uuid : null, ..., status : 0, role: 'user' ,..updatedAt : null }
3547
+ const enums = meta.enums('role') // [ 'admin', 'user' ]
3548
+ const enumsObj = meta.enum('role') // { admin: 'admin', user: 'user' }
3549
+ ```
3550
+
3551
+ ## Audit
3552
+ Keeps a complete history of database changes, tracking who made changes and what was changed.
3553
+
3554
+ ```js
3555
+ await new User()
3556
+ // support actions SELECT, INSERT, UPDATE, and DELETE.
3557
+ // so you have a complete history of data changes and queries.
3558
+ .audit(99 , { name : 'userNumber-99' })
3559
+ .create({
3560
+ username : 'hi audit',
3561
+ email : 'tspace-mysql@gmail.com',
3562
+ // ...
3563
+ })
3564
+ .save()
3565
+ ```
3566
+
3567
+ ## Repository
3568
+ ```js
3569
+ Repository is a mechanism that encapsulates all database operations related to a specific model.
3570
+ It provides methods for querying, inserting, updating, and deleting records in the database associated with the model.
3571
+
3572
+ ** The Repository check always type Type Safety if model is used the type of schema
3573
+
3574
+ ```
3575
+ ### Repository Select Statements
3576
+ ```js
3577
+ import { Repository, OP , type T } from 'tspace-mysql'
3578
+ import { User } from '../Models/User'
3579
+
3580
+ // Create repository instance for User entity
3581
+ const userRepository = Repository(User)
3582
+
3583
+ // Or Use static methods for flexible querying
3584
+ // const user = await User.findOne({ ... }) // traditional way without repository
3585
+
3586
+ // Fetch a single user with flexible query options
3587
+ const user = await userRepository.findOne({
3588
+ /**
3589
+ * 🎯 SELECT
3590
+ * Specify which columns should be returned.
3591
+ * Supports nested selection for relations.
3592
+ */
3593
+ select: {
3594
+ id: true,
3595
+ name: true,
3596
+ username: true,
3597
+
3598
+ // Nested relation field selection
3599
+ phone: {
3600
+ id: true,
3601
+ name: true,
3602
+ user_id: true,
3603
+ }
3604
+ },
3605
+
3606
+ /**
3607
+ * 🚫 EXCEPT
3608
+ * Exclude specific columns from the result.
3609
+ * Useful for hiding audit fields or sensitive data.
3610
+ */
3611
+ // except: {
3612
+ // deleted_at: true,
3613
+ // created_at: true,
3614
+ // updated_at: true,
3615
+ // },
3616
+
3617
+ /**
3618
+ * 🧮 SELECT RAW
3619
+ * Add computed/raw SQL fields to the result.
3620
+ * Automatically extends the return type.
3621
+ */
3622
+ // selectRaw: {
3623
+ // fullName: DB.raw('CONCAT(?,"@",?)', ['name', 'id'])
3624
+ // },
3625
+
3626
+ /**
3627
+ * 🧩 EXTEND
3628
+ * Manually extend the result type with additional fields.
3629
+ * Supports nested objects and arrays.
3630
+ */
3631
+ // extend: {
3632
+ // myNumber: Number,
3633
+ // myProfile: {
3634
+ // id: Number,
3635
+ // name: String
3636
+ // },
3637
+ // myOtherData: [
3638
+ // {
3639
+ // id: Number,
3640
+ // name: String
3641
+ // }
3642
+ // ]
3643
+ // },
3644
+
3645
+ /**
3646
+ * 🔎 WHERE
3647
+ * Define filtering conditions.
3648
+ */
3649
+ where: {
3650
+ id: 1
3651
+ },
3652
+
3653
+ /**
3654
+ * ⚡ WHEN
3655
+ * Conditionally modify the query.
3656
+ * Only applied if `condition` is true.
3657
+ */
3658
+ when: {
3659
+ condition: true,
3660
+ query: () => ({
3661
+ relations: {
3662
+ phone: true
3663
+
3664
+ /**
3665
+ * You can also customize relation query:
3666
+ *
3667
+ * phone: {
3668
+ * where: { id: 41 },
3669
+ * select: {
3670
+ * id: true,
3671
+ * user_id: true
3672
+ * }
3673
+ * }
3674
+ */
3675
+ }
3676
+ })
3677
+ },
3678
+
3679
+ /**
3680
+ * 🛠 USING
3681
+ * Direct access to the underlying query builder.
3682
+ * Allows advanced customization using model methods.
3683
+ */
3684
+ using: (query) => {
3685
+ return query
3686
+
3687
+ // Examples:
3688
+ // query.where('id', 1)
3689
+ // query.customMethodWhereUser(1)
3690
+ }
3691
+ })
3692
+
3693
+
3694
+ // Use static methods for flexible querying
3695
+ // const users = await User.findMany({ limit: 3 }) // traditional way without repository
3696
+ const users = await userRepository.findMany({
3697
+ select : {
3698
+ id : true,
3699
+ name : true,
3700
+ username : true,
3701
+ },
3702
+ limit : 3,
3703
+ orderBy : {
3704
+ id : 'ASC',
3705
+ name : 'DESC'
3706
+ },
3707
+ groupBy : {
3708
+ id : true
3709
+ },
3710
+ where : {
3711
+ id: OP.in([1,2,3])
3712
+ }
3713
+ })
3714
+
3715
+ // Use static methods for flexible querying
3716
+ // const userPaginate = await User.pagination() // traditional way without repository
3717
+ const userPaginate = await userRepository.pagination({
3718
+ select : {
3719
+ id : true,
3720
+ name : true,
3721
+ username : true,
3722
+ },
3723
+ page : 1,
3724
+ limit : 3,
3725
+ where : {
3726
+ id: OP.in([1,2,3])
3727
+ }
3728
+ })
3729
+
3730
+ const findFullName = await userRepository.findOne({
3731
+ select : {
3732
+ name : true,
3733
+ [`${DB.raw('CONCAT(firstName," ",lastName) as fullName')}`]: true
3734
+ },
3735
+ whereRaw : [
3736
+ `CONCAT(firstName," ",lastName) LIKE '%${search}%'`
3737
+ ]
3738
+ })
3739
+ ```
3740
+ ### Repository Insert Statements
3741
+ ```js
3742
+ // Use static methods for flexible querying
3743
+ // const created = await User.create({...}) // traditional way without repository
3744
+
3745
+ const userRepository = Repository(User)
3746
+
3747
+ const created = await userRepository.create({
3748
+ data : {
3749
+ name : "repository-name",
3750
+ // ....
3751
+ }
3752
+ })
3753
+
3754
+ const createdMultiple = await u.createMultiple({
3755
+ data : [
3756
+ {
3757
+ name: "tspace4",
3758
+ // ....
3759
+ },
3760
+ {
3761
+ name: "tspace5",
3762
+ // ....
3763
+ },
3764
+ {
3765
+ name: "tspace6",
3766
+ // ....
3767
+ }
3768
+ // ....
3769
+ ]
3770
+ })
3771
+
3772
+ const createdNotExists = await userRepository.createNotExists({
3773
+ data : {
3774
+ name : "repository-name",
3775
+ // ....
3776
+ },
3777
+ where : {
3778
+ id : 1
3779
+ }
3780
+ })
3781
+
3782
+ const createdOrSelected = await userRepository.createOrSelect({
3783
+ data : {
3784
+ name : "repository-name",
3785
+ // ....
3786
+ },
3787
+ where : {
3788
+ id : 1
3789
+ }
3790
+ })
3791
+
3792
+
3793
+ ```
3794
+ ### Repository Update Statements
3795
+ ```js
3796
+
3797
+ // Use static methods for flexible querying
3798
+ // const updated = await User.update({...}) // traditional way without repository
3799
+
3800
+ const userRepository = Repository(User)
3801
+ const updated = await userRepository.update({
3802
+ data : {
3803
+ name : "repository-name",
3804
+ // ....
3805
+ },
3806
+ where : {
3807
+ id : 1
3808
+ }
3809
+ })
3810
+
3811
+ ```
3812
+ ### Repository Delete Statements
3813
+ ```js
3814
+
3815
+ // Use static methods for flexible querying
3816
+ // const deleted = await User.delete({...}) // traditional way without repository
3817
+
3818
+ const userRepository = Repository(User)
3819
+ const deleted = await userRepository.delete({
3820
+ where : {
3821
+ id : 1
3822
+ }
3823
+ })
3824
+
3825
+ ```
3826
+
3827
+ ### Repository Transactions
3828
+
3829
+ ```js
3830
+ import { DB , Repository } from 'tspace-mysql'
3831
+ import { User } from '../Models/User'
3832
+ const userRepository = Repository(User)
3833
+
3834
+ const transaction = await DB.beginTransaction()
3835
+
3836
+ try {
3837
+ await transaction.startTransaction()
3838
+
3839
+ const created = await userRepository.create({
3840
+ data : {
3841
+ name : "repository-name",
3842
+ // ....
3843
+ },
3844
+ transaction // add this for the transaction
3845
+ })
3846
+
3847
+ const updated = await userRepository.update({
3848
+ data : {
3849
+ name : "repository-name",
3850
+ // ....
3851
+ },
3852
+ where : {
3853
+ id : created.id
3854
+ },
3855
+ transaction
3856
+ })
3857
+
3858
+ // after your use commit if use same transction for actions this transction will auto commit
3859
+ await transaction.commit()
3860
+
3861
+ // ensure the nothing with transction just use end of transction
3862
+ await transaction.end();
3863
+
3864
+ } catch (err) {
3865
+
3866
+ await transaction.rollback()
3867
+ }
3868
+
3869
+ ```
3870
+
3871
+ ### Repository Relations
3872
+ ```js
3873
+ import { Repository , OP } from 'tspace-mysql'
3874
+ import { User } from '../Models/User'
3875
+ import { Phone } from '../Models/Phone'
3876
+
3877
+ // Use static methods for flexible querying
3878
+ // const userHasPhones = await User.findOne({...}) // traditional way without repository
3879
+
3880
+ const userRepository = Repository(User)
3881
+ const userHasPhones = await userRepository.findOne({
3882
+ select : {
3883
+ id : true,
3884
+ name : true,
3885
+ username : true,
3886
+ phone : {
3887
+ id : true,
3888
+ user_id : true,
3889
+ name: true
3890
+ }
3891
+ },
3892
+ where : {
3893
+ id: 1
3894
+ },
3895
+ relations: {
3896
+ phone: {
3897
+ user : true
3898
+ }
3899
+ }
3900
+ });
3901
+
3902
+ const phoneRepository = Repository(Phone)
3903
+
3904
+ const phoneBelongUser = await phoneRepository.findOne({
3905
+ select : '*',
3906
+ where : {
3907
+ id: 1
3908
+ },
3909
+ relations : {
3910
+ user : true
3911
+ }
3912
+ })
3913
+
3914
+ ```
3915
+
3916
+ ## Queue
3917
+ A lightweight, high-performance job queue built for ORM-based systems,
3918
+ designed to run on top of database layers with support for concurrency,
3919
+ retries, priorities, and job inspection.
3920
+
3921
+ - Concurrency Each worker can process multiple jobs at the same time.
3922
+
3923
+ - Priority Higher priority jobs are executed first.
3924
+
3925
+ - Retry Failed jobs are automatically retried up to maxAttempts.
3926
+
3927
+ - Delay Jobs can be scheduled for future execution using delayMs.
3928
+
3929
+ - Idle / Wake Workers automatically go idle when no jobs are available, and wake up instantly when new jobs arrive.
3930
+
3931
+ ```js
3932
+ import { Queue, Job } from 'tspace-mysql';
3933
+
3934
+ const fakeSendEmail = async (job: Job) => {
3935
+ if(Math.random() < 0.5) throw new Error(`Failed job ${job.id}`)
3936
+ await new Promise<void>((ok) => setTimeout(ok, 2000));
3937
+ return `Send email Completed job ${job.id}`;
3938
+ }
3939
+
3940
+ // start the Queue
3941
+ await Queue.start({
3942
+ inspect : true,
3943
+ flush : false, // flush = true -> remove all jobs
3944
+ hostname: 'pod1'
3945
+ });
3946
+
3947
+ const worker = 20;
3948
+
3949
+ // register process send email 20
3950
+ for(let i = 1; i <= worker; i++) {
3951
+
3952
+ Queue.process(`send-email-(${i})`, async(job) => {
3953
+ return await fakeSendEmail(job)
3954
+ } , { concurrency : 10 }) // 1 process / 10 concurrency
3955
+
3956
+ }
3957
+
3958
+ // add jobs 10_000 records
3959
+ for(let j = 1; j <= worker * 500; j++) {
3960
+
3961
+ const i = Math.floor((Math.random() * worker) + 1);
3962
+
3963
+ Queue.add(`send-email-(${i})`, {
3964
+ email: `John-${i}@gmail.com`,
3965
+ name: `John-${i}`
3966
+ }, {
3967
+ delayMs : 1000 * Math.random() * 10,
3968
+ priority : i % 2 ? 9999 + Math.floor((Math.random() * 9999) + 1) : 0,
3969
+ maxAttempts : 3,
3970
+ metadata : {
3971
+ userId : j,
3972
+ name : `John-${i}`
3973
+ }
3974
+ })
3975
+ }
3976
+
3977
+ // for view stats Jobs
3978
+ // await Queue.getJobOverallStats()
3979
+ // await Queue.getJobStats()
3980
+
3981
+ // if you want to end the Queue
3982
+ // await Queue.end()
3983
+
3984
+ ```
3985
+
3986
+ ## View
3987
+
3988
+ Your database schema can also use views. These views are represented by classes that behave similarly to models,
3989
+ but they are based on stored SQL queries instead of actual tables.
3990
+ Let's look at a basic view class example:
3991
+ ```js
3992
+
3993
+ import { type T, Blueprint, Model , View , Meta } from 'tspace-mysql'
3994
+
3995
+ const schemaUser = {
3996
+ id: Blueprint.int().notNull().primary().autoIncrement(),
3997
+ uuid: Blueprint.varchar(50).null().index(),
3998
+ name: Blueprint.varchar(191).notNull(),
3999
+ email: Blueprint.varchar(191).notNull()
4000
+ }
4001
+
4002
+ type TUser = T.Schema<typeof schemaUser>
4003
+
4004
+ class User extends Model<TUser> {
4005
+ protected boot(): void {
4006
+ this.useSchema(schemaUser)
4007
+ }
4008
+ }
4009
+
4010
+ const schemaPost = {
4011
+ id: Blueprint.int().notNull().primary().autoIncrement(),
4012
+ uuid: Blueprint.varchar(50).null().index(),
4013
+ user_id :Blueprint.int().notnull(),
4014
+ title: Blueprint.varchar(191).notNull(),
4015
+ content: Blueprint.varchar(191).notNull()
4016
+ }
4017
+
4018
+ type TPost = T.Schema<typeof schemaPost>
4019
+
4020
+ class Post extends Model<TPost> {
4021
+ protected boot(): void {
4022
+ this.useSchema(schemaPost)
4023
+ }
4024
+ }
4025
+
4026
+ const schemaUserPostCountView = {
4027
+ id :Blueprint.int().notNull().primary().autoIncrement(),
4028
+ user_id :Blueprint.int().notnull(),
4029
+ name :Blueprint.varchar(255).null(),
4030
+ post_count : Blueprint.int().notnull()
4031
+ }
4032
+
4033
+ type TSUserPostCountView = T.Schema<typeof schemaUserPostCountView>
4034
+ type TRUserPostCountView = T.Relation<{
4035
+ user: User
4036
+ }>
4037
+
4038
+ class UserPostCountView extends View<TSUserPostCountView,TRUserPostCountView> {
4039
+
4040
+ protected boot(): void {
4041
+ this.useSchema(schemaUserPostCountView)
4042
+ const metaUser = Meta(User)
4043
+ const metaPost = Meta(Post)
4044
+
4045
+ this.createView({
4046
+ synchronize: true,
4047
+ expression : new User()
4048
+ .selectRaw(`ROW_NUMBER() OVER (ORDER BY ${metaUser.columnRef('id')}) AS id`)
4049
+ .selectRaw(`${metaUser.columnRef('id')} AS user_id`)
4050
+ .selectRaw(metaUser.columnRef('name'))
4051
+ .select(metaUser.columnRef('email'))
4052
+ .selectRaw(`COUNT(${metaPost.columnRef('id')}) AS post_count`)
4053
+ .leftJoin(metaUser.columnRef('id'),metaPost.columnRef('user_id'))
4054
+ .groupBy(metaUser.columnRef('id'))
4055
+ .groupBy(metaUser.columnRef('name'))
4056
+ .toString()
4057
+
4058
+ // Look like this
4059
+ // expression :
4060
+ // SELECT
4061
+ // ROW_NUMBER() OVER (ORDER BY `users`.`id`) AS id,
4062
+ // `users`.`id` AS user_id, `users`.`name`, `users`.`email`,
4063
+ // COUNT(`posts`.`id`) AS post_count
4064
+ // FROM `users`
4065
+ // LEFT JOIN `posts` ON `users`.`id` = `posts`.`user_id`
4066
+ // GROUP BY `users`.`id`, `users`.`name`
4067
+ })
4068
+
4069
+ this.belongsTo({ name : 'user' , model : User })
4070
+ }
4071
+ }
4072
+
4073
+ new UserPostCountView()
4074
+ .with('user')
4075
+ .get()
4076
+ .then( v=> {
4077
+ console.log(v)
4078
+ })
4079
+
4080
+ ```
4081
+
4082
+ ## Stored Procedure
4083
+ StoredProcedure is a predefined set of SQL statements stored in the database that you can call (execute) by name.
4084
+ ```js
4085
+
4086
+ import { StoredProcedure } from 'tspace-mysql'
4087
+
4088
+ type T = {
4089
+ AddUser: {
4090
+ params: {
4091
+ name : string;
4092
+ email: string;
4093
+ } | [string,string];
4094
+ result: {
4095
+ fieldCount: number;
4096
+ affectedRows: number;
4097
+ insertId: number;
4098
+ info: string;
4099
+ serverStatus: number;
4100
+ warningStatus: number;
4101
+ changedRows: number;
4102
+ }
4103
+ };
4104
+ GetUser: {
4105
+ params: [number];
4106
+ result: any[]
4107
+ },
4108
+ GetUsers: {
4109
+ params: [];
4110
+ result: any[]
4111
+ }
4112
+ };
4113
+
4114
+ class MyStoreProcedure extends StoredProcedure<T> {
4115
+ protected boot(): void {
4116
+
4117
+ this.createProcedure({
4118
+ name: 'AddUser',
4119
+ expression: `
4120
+ CREATE PROCEDURE AddUser(IN name VARCHAR(255), IN email VARCHAR(255))
4121
+ BEGIN
4122
+ INSERT INTO users (name, email) VALUES (name, email);
4123
+ END;
4124
+ `,
4125
+ synchronize: true
4126
+ });
4127
+
4128
+ this.createProcedure({
4129
+ name: 'GetUsers',
4130
+ expression: `
4131
+ CREATE PROCEDURE GetUsers()
4132
+ BEGIN
4133
+ SELECT * FROM users LIMIT 5;
4134
+ END;
4135
+ `,
4136
+ synchronize: true
4137
+ });
4138
+
4139
+ this.createProcedure({
4140
+ name: 'GetUser',
4141
+ expression: `
4142
+ CREATE PROCEDURE GetUser(IN userId INT)
4143
+ BEGIN
4144
+ SELECT * FROM users WHERE id = userId LIMIT 1;
4145
+ END;
4146
+ `,
4147
+ synchronize: true
4148
+ })
4149
+ }
4150
+ }
4151
+
4152
+ const storeProcedure = new MyStoreProcedure()
4153
+
4154
+ storeProcedure.call('AddUser', { name : 'tspace-mysql' , email : 'tspace-mysql@example.com'})
4155
+ .then(r => console.log(r))
4156
+ .catch(e => console.log(e))
4157
+
4158
+ storeProcedure.call('GetUser',[1])
4159
+ .then(r => console.log(r))
4160
+ .catch(e => console.log(e))
4161
+
4162
+ storeProcedure.call('GetUsers',[])
4163
+ .then(r => console.log(r))
4164
+ .catch(e => console.log(e))
4165
+
4166
+ ```
4167
+ ## Blueprint
4168
+
4169
+ Blueprint is a tool used for defining database schemas programmatically.
4170
+ It allows developers to describe the structure of their database tables using a simple and intuitive syntax rather than writing SQL queries directly., you may use the:
4171
+
4172
+ ```js
4173
+ import { Schema , Blueprint , DB } from 'tspace-mysql'
4174
+ (async () => {
4175
+ await new Schema().table('users', {
4176
+ id : Blueprint.int().notNull().primary().autoIncrement(),
4177
+ // or id : Blueprint.serial().primary(),
4178
+ uuid : Blueprint.varchar(120).null()
4179
+ name : Blueprint.varchar(120).default('name'),
4180
+ email : Blueprint.varchar(255).unique().notNull(),
4181
+ email_verify : Blueprint.tinyInt(),
4182
+ password : Blueprint.varchar(255),
4183
+ json : Blueprint.json(),
4184
+ created_at : Blueprint.null().timestamp(),
4185
+ updated_at : Blueprint.null().timestamp(),
4186
+ deleted_at : Blueprint.null().timestamp()
4187
+ })
4188
+ /**
4189
+ *
4190
+ * @Faker fake data 5 raw
4191
+ * await new DB().table('users').faker(5)
4192
+ */
4193
+ })()
4194
+
4195
+ /**
4196
+ * To add types of the schema to the database
4197
+ * @Types
4198
+ *
4199
+ */
4200
+ int (number)
4201
+ tinyInt (number)
4202
+ bigInt (number)
4203
+ double ()
4204
+ float ()
4205
+ json ()
4206
+ varchar (number)
4207
+ char (number)
4208
+ longText()
4209
+ mediumText()
4210
+ tinyText()
4211
+ text()
4212
+ enum(...n)
4213
+ date()
4214
+ dateTime()
4215
+ timestamp ()
4216
+
4217
+ /**
4218
+ * To add attributes of the schema to the database
4219
+ * @Attrbuites
4220
+ *
4221
+ */
4222
+ unsigned()
4223
+ unique()
4224
+ null()
4225
+ notNull()
4226
+ primary()
4227
+ default(string)
4228
+ defaultTimestamp()
4229
+ autoIncrement()
4230
+
4231
+ /**
4232
+ * To add a foreign key to the column
4233
+ * @ForeginKey
4234
+ */
4235
+ foreign({ references : ${COLUMN} , on : ${TABLE-NAME OR MODEL CLASSES} })
4236
+
4237
+ /**
4238
+ * To add a index key to the column
4239
+ * @indexKey
4240
+ */
4241
+ index()
4242
+ ```
4243
+
4244
+ ## Cli
4245
+
4246
+ To get started, let's install tspace-mysql
4247
+ you may use a basic cli :
4248
+
4249
+ ```sh
4250
+ npm install tspace-mysql -g
4251
+
4252
+ ```
4253
+
4254
+ ## Make Model
4255
+
4256
+ The command will be placed Model in the specific directory.
4257
+
4258
+ ```sh
4259
+
4260
+ /**
4261
+ *
4262
+ * @make Model
4263
+ * @options
4264
+ * @arg --m => created scheme table for migrate. short cut migration table like Make Migration
4265
+ * @arg --dir=directory => created model in directory. default root directory
4266
+ * @arg --type=js // extension js. default ts
4267
+ */
4268
+ tspace-mysql make:model <model name> --m --dir=.... --type=....
4269
+
4270
+ tspace-mysql make:model User --m --dir=app/Models
4271
+ /**
4272
+ *
4273
+ * @Ex directory
4274
+ */
4275
+ - node_modules
4276
+ - app
4277
+ - Models
4278
+ User.ts
4279
+ ```
4280
+
4281
+ ## Make Migration
4282
+
4283
+ The command will be placed Migration in the specific directory.
4284
+
4285
+ ```sh
4286
+ /**
4287
+ *
4288
+ * @make Migration Table
4289
+ * @options
4290
+ * @arg --dir=directory => created scheme table in directory. default root directory
4291
+ * @arg --type=js // extension js default ts
4292
+ */
4293
+ tspace-mysql make:migration <table name> --type=... --dir=....
4294
+
4295
+ tspace-mysql make:migration users --dir=app/Models/Migrations
4296
+ /**
4297
+ *
4298
+ * @Ex directory
4299
+ */
4300
+ - node_modules
4301
+ - app
4302
+ - Models
4303
+ - Migrations
4304
+ create_users_table.ts
4305
+ User.ts
4306
+ ```
4307
+
4308
+ ## Migrate
4309
+
4310
+ ```sh
4311
+ /**
4312
+ *
4313
+ * @run Migrate table
4314
+ * @options
4315
+ * @arg --dir=directory => find migrate in directory. default find in root folder
4316
+ * @arg --type=js // extension js default ts
4317
+ */
4318
+ tspace-mysql migrate <folder> --type=<type file js or ts> --dir=<directory for migrate>
4319
+
4320
+ tspace-mysql migrate --dir=app/Models/Migrations --type=js
4321
+
4322
+ /**
4323
+ *
4324
+ * @Ex directory
4325
+ */
4326
+ - node_modules
4327
+ - app
4328
+ - Models
4329
+ - Migrations
4330
+ create_users_table.ts
4331
+ create_posts_table.ts
4332
+ User.ts
4333
+ Post.ts
4334
+ // => migrate all schemas in folder <Migrations>. created into database
4335
+ ```
4336
+
4337
+ # Query
4338
+
4339
+ The command will execute a query.
4340
+
4341
+ ```sh
4342
+ tspace-mysql query "SELECT * FROM users"
4343
+
4344
+ ```
4345
+
4346
+ # Dump
4347
+
4348
+ The command will dump the database or table into a file.
4349
+
4350
+ ```sh
4351
+ tspace-mysql dump:db --dir=<folder for dump> --values // backup with values in the tables
4352
+
4353
+ tspace-mysql dump:table "table_name" --dir=<folder for dump> --values // backup with values in the table
4354
+
4355
+ ```
4356
+
4357
+ # Generate Models
4358
+
4359
+ The command will generate models from tables in the database.
4360
+
4361
+ ```sh
4362
+ tspace-mysql generate:models --dir=<folder for creating>
4363
+
4364
+ tspace-mysql generate:models --dir=app/Models --env=development --decorators
4365
+
4366
+ ```
4367
+
4368
+ # Migration Models
4369
+
4370
+ The command will generate migrations based on the schema in your models to a .sql file,
4371
+ can also push the migration files to the database.
4372
+
4373
+ ```sh
4374
+ /**
4375
+ *
4376
+ * @arg --push will push the migration files to the database
4377
+ * @arg --generate will generate the migration files
4378
+ */
4379
+ tspace-mysql migrations:models --dir=<path-to-migration> --models=<path to your models> --generate
4380
+ tspace-mysql migrations:models --dir=<path-to-migration> --push
4381
+
4382
+ tspace-mysql migrations:models --models=src/app/models --dir=migrations --generate
4383
+ tspace-mysql migrations:models --dir=migrations --push
4384
+
4385
+ ```
4386
+
4387
+ # Migration DB
4388
+
4389
+ The command will generate migrations based on the schema in your database to a .sql file,
4390
+ can also push the migration files to the database.
4391
+
4392
+ ```sh
4393
+ /**
4394
+ *
4395
+ * @arg --push will push the migration files to the database
4396
+ * @arg --generate will generate the migration files
4397
+ */
4398
+ tspace-mysql migrations:db --dir=<path-to-migration> --generate --env=<YOUR_ENV> -filename=<YOUR_FILENAME>
4399
+ tspace-mysql migrations:db --dir=<path-to-migration> --push
4400
+
4401
+ tspace-mysql migrations:db --dir=migrations --generate --filename=dump.sql --env=development
4402
+ tspace-mysql migrations:db --dir=migrations --push --filename=dump.sql --env=development
57
4403
 
58
- - [Getting Started](https://thanathip41.github.io/tspace-mysql/#/)
59
- - [Install](https://thanathip41.github.io/tspace-mysql/#/?id=install)
60
- - [Configuration](https://thanathip41.github.io/tspace-mysql/#/?id=configuration)
61
- - [Integrations](https://thanathip41.github.io/tspace-mysql/#/integrations)
62
- - [Http](https://thanathip41.github.io/tspace-mysql/#/integrations?id=http)
63
- - [Expressjs](https://thanathip41.github.io/tspace-mysql/#/integrations)
64
- - [Fastify](https://thanathip41.github.io/tspace-mysql/#/integrations?id=expressjs)
65
- - [Nestjs](https://thanathip41.github.io/tspace-mysql/#/integrations?id=nestjs)
66
- - [Bun](https://thanathip41.github.io/tspace-mysql/#/integrations?id=bun-native)
67
- - [Elysia](https://thanathip41.github.io/tspace-mysql/#/integrations?id=elysia)
68
- - [Hono](https://thanathip41.github.io/tspace-mysql/#/integrations?id=hono)
69
- - [SQL Like](https://thanathip41.github.io/tspace-mysql/#/sql-like)
70
- - [Select Statements](https://thanathip41.github.io/tspace-mysql/#/sql-like?id=select-statements)
71
- - [Insert Statements](https://thanathip41.github.io/tspace-mysql/#/sql-like?id=insert-statements)
72
- - [Update Statements](https://thanathip41.github.io/tspace-mysql/#/sql-like?id=update-statements)
73
- - [Delete Statements](https://thanathip41.github.io/tspace-mysql/#/sql-like?id=delete-statements)
74
- - [Query Builder](https://thanathip41.github.io/tspace-mysql/#/query-builder)
75
- - [Table Name & Alias Name](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=table-name--alias-name)
76
- - [Returning Results](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=returning-results)
77
- - [Query Statement](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=query-statements)
78
- - [Select Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=select-statements)
79
- - [Insert Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=insert-statements)
80
- - [Update Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=update-statements)
81
- - [Delete Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=delete-statements)
82
- - [Raw Expressions](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=raw-expressions)
83
- - [Ordering, Grouping, Limit and Offset](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=ordering-grouping-limit-and-offset)
84
- - [Ordering](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=ordering)
85
- - [Grouping](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=grouping)
86
- - [Limit and Offset](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=limit-and-offset)
87
- - [Joins](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=joins)
88
- - [Inner Join Clause](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=inner-join-clause)
89
- - [Left Join, Right Join Clause](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=left-join-right-join-clause)
90
- - [Cross Join Clause](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=cross-join-clause)
91
- - [Basic Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=basic-where-clauses)
92
- - [Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=where-clauses)
93
- - [Or Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=or-where-clauses)
94
- - [Where cases](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=where-cases)
95
- - [Where Object Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=where-object-clauses)
96
- - [JSON Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=json-where-clauses)
97
- - [Additional Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=additional-where-clauses)
98
- - [Logical Grouping](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=logical-grouping)
99
- - [Advanced Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=advanced-where-clauses)
100
- - [Where Exists Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=where-exists-clauses)
101
- - [Subquery Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=subquery-where-clauses)
102
- - [Conditional Where Clauses](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=conditional-where-clauses)
103
- - [GetGroupBy](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=getgroupby)
104
- - [Paginating](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=paginating)
105
- - [Hook Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=hook-statements)
106
- - [Faker Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=faker-statements)
107
- - [Unset Statements](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=unset-statements)
108
- - [Common Table Expressions](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=common-table-expressions)
109
- - [Union](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=union)
110
- - [More Methods](https://thanathip41.github.io/tspace-mysql/#/query-builder?id=more-methods)
111
- - [Database Transactions](https://thanathip41.github.io/tspace-mysql/#/database-transactions)
112
- - [Race Condition](https://thanathip41.github.io/tspace-mysql/#/race-condition)
113
- - [Connection](https://thanathip41.github.io/tspace-mysql/#/connection)
114
- - [Backup](https://thanathip41.github.io/tspace-mysql/#/backup)
115
- - [Injection](https://thanathip41.github.io/tspace-mysql/#/injection)
116
- - [Model](https://thanathip41.github.io/tspace-mysql/#/model)
117
- - [Basic Model Setup](https://thanathip41.github.io/tspace-mysql/#/model?id=basic-model-setup)
118
- - [Table Name](https://thanathip41.github.io/tspace-mysql/#/model?id=table-name)
119
- - [Pattern](https://thanathip41.github.io/tspace-mysql/#/model?id=pattern)
120
- - [UUID](https://thanathip41.github.io/tspace-mysql/#/model?id=uuid)
121
- - [Timestamp](https://thanathip41.github.io/tspace-mysql/#/model?id=timestamp)
122
- - [Debug](https://thanathip41.github.io/tspace-mysql/#/model?id=debug)
123
- - [Observer](https://thanathip41.github.io/tspace-mysql/#/model?id=observer)
124
- - [Logger](https://thanathip41.github.io/tspace-mysql/#/model?id=logger)
125
- - [Hooks](https://thanathip41.github.io/tspace-mysql/#/model?id=hooks)
126
- - [Global Scope](https://thanathip41.github.io/tspace-mysql/#/model?id=global-scope)
127
- - [Schema](https://thanathip41.github.io/tspace-mysql/#/model?id=schema)
128
- - [Schema Model](https://thanathip41.github.io/tspace-mysql/#/model?id=schema-model)
129
- - [Virtual Column](https://thanathip41.github.io/tspace-mysql/#/model?id=virtual-column)
130
- - [Validation](https://thanathip41.github.io/tspace-mysql/#/model?id=validation)
131
- - [Sync](https://thanathip41.github.io/tspace-mysql/#/model?id=sync)
132
- - [SoftDelete](https://thanathip41.github.io/tspace-mysql/#/model?id=softdelete)
133
- - [Joins Model](https://thanathip41.github.io/tspace-mysql/#/model?id=joins-model)
134
- - [Inner Join Model Clause](https://thanathip41.github.io/tspace-mysql/#/model?id=inner-join-model-clause)
135
- - [Left Join , Right Join Model Clause](https://thanathip41.github.io/tspace-mysql/#/model?id=left-join-right-join-model-clause)
136
- - [Cross Join Model Clause](https://thanathip41.github.io/tspace-mysql/#/model?id=cross-join-model-clause)
137
- - [Relationships](https://thanathip41.github.io/tspace-mysql/#/model?id=relationships)
138
- - [One To One](https://thanathip41.github.io/tspace-mysql/#/model?id=one-to-one)
139
- - [One To Many](https://thanathip41.github.io/tspace-mysql/#/model?id=one-to-many)
140
- - [Belongs To](https://thanathip41.github.io/tspace-mysql/#/model?id=belongs-to)
141
- - [Many To Many](https://thanathip41.github.io/tspace-mysql/#/model?id=many-to-many)
142
- - [Relation](https://thanathip41.github.io/tspace-mysql/#/model?id=relation)
143
- - [Deeply Nested Relations](https://thanathip41.github.io/tspace-mysql/#/model?id=deeply-nested-relations)
144
- - [Relation Exists](https://thanathip41.github.io/tspace-mysql/#/model?id=relation-exists)
145
- - [Relation Count](https://thanathip41.github.io/tspace-mysql/#/model?id=relation-count)
146
- - [Relation Trashed](https://thanathip41.github.io/tspace-mysql/#/model?id=relation-trashed)
147
- - [Built in Relation Functions](https://thanathip41.github.io/tspace-mysql/#/model?id=built-in-relation-functions)
148
- - [Cache](https://thanathip41.github.io/tspace-mysql/#/model?id=cache)
149
- - [Decorator](https://thanathip41.github.io/tspace-mysql/#/model?id=decorator)
150
- - [Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=type-safety)
151
- - [Select Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=select-type-safety-type-safety)
152
- - [OrderBy Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=order-by-type-safety)
153
- - [GroupBy Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=group-by-type-safety)
154
- - [Where Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=where-type-safety)
155
- - [Insert Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=insert-type-safety)
156
- - [Update Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=update-type-safety)
157
- - [Delete Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=delete-type-safety)
158
- - [Relationships Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=relationships-type-safety)
159
- - [Results Type Safety](https://thanathip41.github.io/tspace-mysql/#/model?id=results-type-safety)
160
- - [Metadata](https://thanathip41.github.io/tspace-mysql/#/model?id=metadata)
161
- - [Audit](https://thanathip41.github.io/tspace-mysql/#/model?id=audit)
162
- - [Repository](https://thanathip41.github.io/tspace-mysql/#/repository)
163
- - [Select Statements](https://thanathip41.github.io/tspace-mysql/#/repository?id=select-statements)
164
- - [Insert Statements](https://thanathip41.github.io/tspace-mysql/#/repository?id=insert-statements)
165
- - [Update Statements](https://thanathip41.github.io/tspace-mysql/#/repository?id=update-statements)
166
- - [Delete Statements](https://thanathip41.github.io/tspace-mysql/#/repository?id=delete-statements)
167
- - [Transactions](https://thanathip41.github.io/tspace-mysql/#/repository?id=transactions)
168
- - [Relations](https://thanathip41.github.io/tspace-mysql/#/repository?id=relations)
169
- - [View](https://thanathip41.github.io/tspace-mysql/#/view)
170
- - [Stored Procedure](https://thanathip41.github.io/tspace-mysql/#/stored-procedure)
171
- - [Blueprint](https://thanathip41.github.io/tspace-mysql/#/blueprint)
172
- - [Cli](https://thanathip41.github.io/tspace-mysql/#/cli)
173
- - [Make Model](https://thanathip41.github.io/tspace-mysql/#/cli?id=make-model)
174
- - [Make Migration](https://thanathip41.github.io/tspace-mysql/#/cli?id=make-migration)
175
- - [Migrate](https://thanathip41.github.io/tspace-mysql/#/cli?id=migrate)
176
- - [Query](https://thanathip41.github.io/tspace-mysql/#/cli?id=query)
177
- - [Dump](https://thanathip41.github.io/tspace-mysql/#/cli?id=dump)
178
- - [Generate Models](https://thanathip41.github.io/tspace-mysql/#/cli?id=generate-models)
179
- - [Migration Models](https://thanathip41.github.io/tspace-mysql/#/cli?id=migration-models)
180
- - [Migration DB](https://thanathip41.github.io/tspace-mysql/#/cli?id=migration-db)
4404
+ ```