drizzle-orm 0.9.13 → 0.9.14

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 (2) hide show
  1. package/README.md +385 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,385 @@
1
+ # DrizzleORM
2
+
3
+ **DrizzleORM** is an ORM framework for
4
+ [TypeScript](https://www.typescriptlang.org/).
5
+ It offers you several levels of Database communication:
6
+ * Typesafe Table View approach
7
+ * Typesafe Query Builder
8
+ * Simple SQL query execution
9
+
10
+ Drizzle ORM is highly influenced by [Exposed](https://github.com/JetBrains/Exposed) and Jetbrains development methodology
11
+
12
+ ## Supported Databases
13
+
14
+ * PostgreSQL
15
+
16
+ ## Links
17
+
18
+ In Progress
19
+
20
+ ## Installing
21
+
22
+ ```bash
23
+ npm install drizzle-orm drizzle-kit
24
+ ```
25
+ #### **In Progress**
26
+ ```bash
27
+ yarn add drizzle-orm drizzle-kit
28
+ bower install drizzle-orm drizzle-kit
29
+ ```
30
+
31
+ ## Connecting to database
32
+
33
+ ```tsx
34
+ import { DbConnector } from "drizzle-orm";
35
+
36
+ // connect via postgresql connection url
37
+ const db = await new DbConnector()
38
+ .connectionString("postgres://user:password@host:port/db")
39
+ .connect();
40
+
41
+ // or by params
42
+ const db = await new DbConnector()
43
+ .params({
44
+ host: '0.0.0.0',
45
+ port: 5432,
46
+ user: 'user',
47
+ password: 'password',
48
+ db: 'optional_db_name'
49
+ }).connect();
50
+ ```
51
+ ## Project structure
52
+ - tables folder
53
+ - migrations folder
54
+
55
+ ## Create tables
56
+ ### Users Table
57
+ ---
58
+ ```typescript
59
+
60
+ export const rolesEnum = createEnum({ alias: 'test-enum', values: ['user', 'guest', 'admin'] });
61
+
62
+ export default class UsersTable extends AbstractTable<UsersTable> {
63
+ public id = this.int('id').autoIncrement().primaryKey();
64
+ public fullName = this.text('full_name');
65
+
66
+ public phone = this.varchar('phone', { size: 256 });
67
+ public media = this.jsonb<string[]>('media');
68
+ public decimalField = this.decimal('test', { notNull: true, precision: 100, scale: 2 });
69
+ public bigIntField = this.bigint('test1');
70
+ public role = this.type(rolesEnum, 'name_in_table', { notNull: true });
71
+
72
+ public createdAt = this.timestamp('created_at', { notNull: true });
73
+ public updatedAt = this.timestamp('updated_at');
74
+ public isArchived = this.bool('is_archived').defaultValue(false);
75
+
76
+ public phoneFullNameIndex = this.index([this.phone, this.fullName]);
77
+ public phoneIndex = this.uniqueIndex(this.phone);
78
+
79
+ public tableName(): string {
80
+ return 'users';
81
+ }
82
+ }
83
+ ```
84
+ ### Cities Table
85
+ ---
86
+ ```typescript
87
+ interface CityMeta {
88
+ population: number,
89
+ connection: string,
90
+ }
91
+
92
+ export default class CitiesTable extends AbstractTable<CitiesTable> {
93
+ public id = this.int('id').autoIncrement().primaryKey();
94
+
95
+ public foundationDate = this.timestamp('name', { notNull: true });
96
+ public location = this.varchar('page', { size: 256 });
97
+
98
+ public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, OnDelete.CASCADE);
99
+
100
+ public metadata = this.jsonb<CityMeta>('metadata');
101
+
102
+ public tableName(): string {
103
+ return 'cities';
104
+ }
105
+ }
106
+ ```
107
+ ### User Groups Table
108
+ ---
109
+ ```typescript
110
+ export default class UserGroupsTable extends AbstractTable<UserGroupsTable> {
111
+ public id = this.int('id').autoIncrement().primaryKey();
112
+
113
+ public name = this.varchar('name');
114
+ public description = this.varchar('description');
115
+
116
+ public tableName(): string {
117
+ return 'user_groups';
118
+ }
119
+ }
120
+ ```
121
+ ### User to User Groups Table
122
+ ---
123
+ #### Many to many connection between Users and User Groups
124
+ ```typescript
125
+ export default class UsersToUserGroupsTable extends AbstractTable<UsersToUserGroupsTable> {
126
+ public groupId = this.int('city_id').foreignKey(UserGroupsTable, (table) => table.id, OnDelete.CASCADE);
127
+ public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, OnDelete.CASCADE);
128
+
129
+ public manyToManyIndex = this.index([this.groupId, this.userId]);
130
+
131
+ public tableName(): string {
132
+ return 'users_to_user_groups';
133
+ }
134
+ }
135
+ ```
136
+
137
+ ## CRUD
138
+ ### **SELECT**
139
+ ---
140
+ ```typescript
141
+ const db = await new DbConnector()
142
+ .connectionString('postgresql://postgres@127.0.0.1/drizzle')
143
+ .connect();
144
+
145
+ const usersTable = new UsersTable(db);
146
+
147
+ // select all
148
+ const allSelect = await usersTable.select().all();
149
+
150
+ // select first
151
+ const firstSelect = await usersTable.select().first();
152
+ ```
153
+ #### **Sorting and Filtering**
154
+ ---
155
+ ##### Select all records from `Users` where phone is `"hello"`
156
+ ```typescript
157
+ const eqSelect = await usersTable.select().where(
158
+ eq(usersTable.phone, 'hello')
159
+ ).all();
160
+ ```
161
+ ##### Select all records from `Users` where **both** phone is `"hello"` **and** phone is `"hello"`
162
+ ```typescript
163
+ const andSelect = await usersTable.select().where(
164
+ and([
165
+ eq(usersTable.phone, 'hello'),
166
+ eq(usersTable.phone, 'hello')
167
+ ]),
168
+ ).all();
169
+ ```
170
+ ##### Select all records from `Users` where **either** phone is `"hello"` **or** phone is `"hello"`
171
+ ```typescript
172
+ const orSelect = await usersTable.select().where(
173
+ or([eq(usersTable.phone, 'hello')]),
174
+ ).all();
175
+ ```
176
+ ##### Select all records from `Users` using **LIMIT** and **OFFSET**
177
+ ```typescript
178
+ const limitOffsetSelect = await usersTable.select({ limit: 10, offset: 10 }).all();
179
+ ```
180
+ ##### Select all records from `Users` where `phone` contains `"hello"`
181
+ ```typescript
182
+ const likeSelect = await usersTable.select().where(
183
+ like(usersTable.phone, '%hello%')
184
+ ).all();
185
+ ```
186
+ ##### Select all records from `Users` where `phone` equals to some of values from array
187
+ ```typescript
188
+ const inArraySelect = usersTable.select().where(
189
+ inArray(usersTable.phone, ['hello'])
190
+ ).all();
191
+ ```
192
+ ##### Select all records from `Users` where `phone` greater(**>**) than `"hello"`
193
+ ```typescript
194
+ const greaterSelect = usersTable.select().where(
195
+ greater(usersTable.phone, 'hello')
196
+ ).all();
197
+ ```
198
+ ##### Select all records from `Users` where `phone` less(**<**) than `"hello"`
199
+ ```typescript
200
+ const lessSelect = usersTable.select().where(
201
+ less(usersTable.phone, 'hello')
202
+ ).all();
203
+ ```
204
+ ##### Select all records from `Users` where `phone` greater or equals(**>=**) than `"hello"`
205
+ ```typescript
206
+ const greaterEqSelect = usersTable.select().where(
207
+ greaterEq(usersTable.phone, 'hello')
208
+ ).all();
209
+ ```
210
+ ##### Select all records from `Users` where `phone` less or equals(**<=**)
211
+ ```typescript
212
+ const lessEqSelect = usersTable.select().where(
213
+ lessEq(usersTable.phone, 'hello')
214
+ ).all();
215
+ ```
216
+ ##### Select all records from `Users` where `phone` is **NULL**
217
+ ```typescript
218
+ const isNullSelect = usersTable.select().where(
219
+ isNull(usersTable.phone)
220
+ ).all();
221
+ ```
222
+ ##### Select all records from `Users` where `phone` not equals to `"hello"`
223
+ ```typescript
224
+ const notEqSelect = usersTable.select().where(
225
+ notEq(usersTable.phone, 'hello')
226
+ ).all();
227
+ ```
228
+ ##### Select all records from `Users` ordered by `phone` in ascending order
229
+ ```typescript
230
+ const ordered = await usersTable.select().orderBy((table) => table.phone, Order.ASC).all();
231
+ ```
232
+
233
+ ### **Update**
234
+ ---
235
+ ##### Update `fullName` to `newName` in `Users` where phone is `"hello"`
236
+ ```typescript
237
+ await usersTable.update()
238
+ .where(eq(usersTable.phone, 'hello'))
239
+ .set({ fullName: 'newName' })
240
+ .execute();
241
+ ```
242
+ ##### Update `fullName` to `newName` in `Users` where phone is `"hello"` returning updated `User` model
243
+ ```typescript
244
+ await usersTable.update()
245
+ .where(eq(usersTable.phone, 'hello'))
246
+ .set({ fullName: 'newName' })
247
+ .all();
248
+ ```
249
+ ##### Update `fullName` to `newName` in `Users` where phone is `"hello"` returning updated `User` model
250
+ ```typescript
251
+ await usersTable.update()
252
+ .where(eq(usersTable.phone, 'hello'))
253
+ .set({ fullName: 'newName' })
254
+ .first();
255
+ ```
256
+
257
+ ### **Delete**
258
+ ##### Delete `user` where phone is `"hello"`
259
+ ```typescript
260
+ await usersTable.delete()
261
+ .where(eq(usersTable.phone, 'hello'))
262
+ .execute();
263
+ ```
264
+ ##### Delete `user` where phone is `"hello"` returning updated `User` model
265
+ ```typescript
266
+ await usersTable.delete()
267
+ .where(eq(usersTable.phone, 'hello'))
268
+ .all();
269
+ ```
270
+ ##### Delete `user` where phone is `"hello"` returning updated `User` model
271
+ ```typescript
272
+ await usersTable.delete()
273
+ .where(eq(usersTable.phone, 'hello'))
274
+ .first();
275
+ ```
276
+
277
+ ### **Insert**
278
+ ##### Insert `user` with required fields
279
+ ```typescript
280
+ await usersTable.insert({
281
+ test: 1,
282
+ createdAt: new Date(),
283
+ }).execute();
284
+ ```
285
+ ##### Insert `user` with required fields and get all rows as array
286
+ ```typescript
287
+ const user = await usersTable.insert({
288
+ test: 1,
289
+ createdAt: new Date(),
290
+ }).all();
291
+ ```
292
+ ##### Insert `user` with required fields and get inserted entity
293
+ ```typescript
294
+ const user = await usersTable.insert({
295
+ test: 1,
296
+ createdAt: new Date(),
297
+ }).first();
298
+ ```
299
+ ##### Insert many `users` with required fields and get all inserted entities
300
+ ```typescript
301
+ const users = await usersTable.insertMany([{
302
+ test: 1,
303
+ createdAt: new Date(),
304
+ }, {
305
+ test: 2,
306
+ createdAt: new Date(),
307
+ }]).all();
308
+ ```
309
+ ##### Insert many `users` with required fields and get all inserted entities. If such user already exists - update `phone` field
310
+ ```typescript
311
+ await usersTable.insertMany([{
312
+ test: 1,
313
+ createdAt: new Date(),
314
+ }, {
315
+ test: 2,
316
+ createdAt: new Date(),
317
+ }])
318
+ .onConflict(
319
+ (table) => table.phoneIndex,
320
+ { phone: 'confilctUpdate' },
321
+ ).all();
322
+ ```
323
+
324
+ ## Joins
325
+ ### Join One-To-Many Tables
326
+ ##### Join Cities with Users and map to city object with full user
327
+ ```typescript
328
+ const usersTable = new UsersTable(db);
329
+ const citiesTable = new CitiesTable(db);
330
+
331
+ const userWithCities = await citiesTable.select()
332
+ .where(eq(citiesTable.id, 1))
333
+ .leftJoin(UsersTable,
334
+ (city) => city.userId,
335
+ (users) => users.id)
336
+ .execute();
337
+
338
+ const citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));
339
+ ```
340
+
341
+ ### Join Many-To-Many Tables
342
+ ##### Join User Groups with Users, using many-to-many table and map response to get user object with groups array
343
+ ```typescript
344
+ const usersWithUserGroups = await usersToUserGroupsTable.select()
345
+ .where(eq(userGroupsTable.id, 1))
346
+ .leftJoin(UsersTable,
347
+ (userToGroup) => userToGroup.userId,
348
+ (users) => users.id)
349
+ .leftJoin(UserGroupsTable,
350
+ (userToGroup) => userToGroup.groupId,
351
+ (users) => users.id)
352
+ .execute();
353
+
354
+ const userGroupWithUsers = usersWithUserGroups.group({
355
+ one: (_, dbUser, dbUserGroup) => dbUser!,
356
+ many: (_, dbUser, dbUserGroup) => dbUserGroup!,
357
+ });
358
+
359
+ const userWithGroups: ExtractModel<UsersTable> & { groups: ExtractModel<UserGroupsTable>[] } = {
360
+ ...userGroupWithUsers.one,
361
+ groups: userGroupWithUsers.many,
362
+ };
363
+ ```
364
+ ##### Join User Groups with Users, using many-to-many table and map response to get user group object with users array
365
+ ```typescript
366
+ const usersWithUserGroups = await usersToUserGroupsTable.select()
367
+ .where(eq(userGroupsTable.id, 1))
368
+ .leftJoin(UsersTable,
369
+ (userToGroup) => userToGroup.userId,
370
+ (users) => users.id)
371
+ .leftJoin(UserGroupsTable,
372
+ (userToGroup) => userToGroup.groupId,
373
+ (users) => users.id)
374
+ .execute();
375
+
376
+ const userGroupWithUsers = usersWithUserGroups.group({
377
+ one: (_, dbUser, dbUserGroup) => dbUserGroup!,
378
+ many: (_, dbUser, dbUserGroup) => dbUser!,
379
+ });
380
+
381
+ const userWithGroups: ExtractModel<UserGroupsTable> & { users: ExtractModel<UsersTable>[] } = {
382
+ ...userGroupWithUsers.one,
383
+ users: userGroupWithUsers.many,
384
+ };
385
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drizzle-orm",
3
- "version": "0.9.13",
3
+ "version": "0.9.14",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",