drizzle-orm 0.10.41 → 0.10.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +439 -0
- package/builders/aggregators/deleteAggregator.js +1 -1
- package/builders/aggregators/insertAggregator.js +5 -2
- package/builders/aggregators/selectAggregator.js +1 -1
- package/builders/aggregators/updateAggregator.js +5 -2
- package/builders/highLvlBuilders/deleteRequestBuilder.js +1 -1
- package/builders/highLvlBuilders/insertRequestBuilder.js +1 -1
- package/builders/highLvlBuilders/selectRequestBuilder.js +5 -5
- package/builders/highLvlBuilders/updateRequestBuilder.js +1 -1
- package/builders/joinBuilders/builders/abstractJoinBuilder.d.ts +3 -1
- package/builders/joinBuilders/builders/abstractJoinBuilder.js +7 -2
- package/builders/joinBuilders/builders/selectWithFiveJoins.d.ts +2 -1
- package/builders/joinBuilders/builders/selectWithFiveJoins.js +2 -2
- package/builders/joinBuilders/builders/selectWithFourJoins.d.ts +2 -1
- package/builders/joinBuilders/builders/selectWithFourJoins.js +6 -6
- package/builders/joinBuilders/builders/selectWithJoin.d.ts +2 -1
- package/builders/joinBuilders/builders/selectWithJoin.js +6 -6
- package/builders/joinBuilders/builders/selectWithThreeJoins.d.ts +2 -1
- package/builders/joinBuilders/builders/selectWithThreeJoins.js +6 -6
- package/builders/joinBuilders/builders/selectWithTwoJoins.d.ts +2 -1
- package/builders/joinBuilders/builders/selectWithTwoJoins.js +6 -6
- package/builders/requestBuilders/updates/combine.d.ts +5 -1
- package/builders/requestBuilders/updates/combine.js +2 -2
- package/builders/requestBuilders/updates/increment.d.ts +5 -1
- package/builders/requestBuilders/updates/increment.js +1 -1
- package/builders/requestBuilders/updates/setObjects.d.ts +5 -1
- package/builders/requestBuilders/updates/setObjects.js +2 -2
- package/builders/requestBuilders/updates/updates.d.ts +5 -1
- package/builders/requestBuilders/updates/updates.js +0 -1
- package/builders/requestBuilders/where/and.d.ts +8 -3
- package/builders/requestBuilders/where/and.js +2 -2
- package/builders/requestBuilders/where/const.d.ts +8 -1
- package/builders/requestBuilders/where/const.js +4 -5
- package/builders/requestBuilders/where/constArray.d.ts +8 -1
- package/builders/requestBuilders/where/constArray.js +4 -4
- package/builders/requestBuilders/where/eqWhere.d.ts +8 -3
- package/builders/requestBuilders/where/eqWhere.js +3 -3
- package/builders/requestBuilders/where/greater.d.ts +8 -3
- package/builders/requestBuilders/where/greater.js +3 -3
- package/builders/requestBuilders/where/greaterEq.d.ts +8 -3
- package/builders/requestBuilders/where/greaterEq.js +3 -3
- package/builders/requestBuilders/where/in.d.ts +8 -3
- package/builders/requestBuilders/where/in.js +3 -3
- package/builders/requestBuilders/where/isNotNull.d.ts +8 -3
- package/builders/requestBuilders/where/isNotNull.js +2 -2
- package/builders/requestBuilders/where/isNull.d.ts +8 -3
- package/builders/requestBuilders/where/isNull.js +2 -2
- package/builders/requestBuilders/where/less.d.ts +8 -3
- package/builders/requestBuilders/where/less.js +3 -3
- package/builders/requestBuilders/where/lessEq.d.ts +8 -3
- package/builders/requestBuilders/where/lessEq.js +3 -3
- package/builders/requestBuilders/where/like.d.ts +8 -3
- package/builders/requestBuilders/where/like.js +3 -3
- package/builders/requestBuilders/where/notEqWhere.d.ts +8 -3
- package/builders/requestBuilders/where/notEqWhere.js +3 -3
- package/builders/requestBuilders/where/or.d.ts +8 -3
- package/builders/requestBuilders/where/or.js +2 -2
- package/builders/requestBuilders/where/rawWhere.d.ts +8 -1
- package/builders/requestBuilders/where/rawWhere.js +1 -1
- package/builders/requestBuilders/where/var.d.ts +8 -3
- package/builders/requestBuilders/where/var.js +1 -1
- package/builders/requestBuilders/where/where.d.ts +7 -2
- package/builders/requestBuilders/where/where.js +0 -1
- package/columns/types/pgJsonb.js +1 -1
- package/columns/types/pgText.js +1 -1
- package/columns/types/pgVarChar.js +1 -1
- package/db/session.d.ts +3 -0
- package/db/session.js +6 -0
- package/errors/builderError.d.ts +2 -1
- package/errors/builderError.js +3 -3
- package/package.json +3 -2
- package/test.js +42 -5
package/README.md
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
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.serial('id').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', { precision: 100, scale: 2 }).notNull();
|
|
69
|
+
public bigIntField = this.bigint('test1', 'max_bytes_53');
|
|
70
|
+
public role = this.type(rolesEnum, 'name_in_table').notNull();
|
|
71
|
+
|
|
72
|
+
public createdAt = this.timestamp('created_at').notNull();
|
|
73
|
+
|
|
74
|
+
public createdAtWithTimezone = this.timestamptz('created_at_time_zone');
|
|
75
|
+
|
|
76
|
+
public updatedAt = this.timestamp('updated_at').defaultValue(Defaults.CURRENT_TIMESTAMP);
|
|
77
|
+
public isArchived = this.bool('is_archived').defaultValue(false);
|
|
78
|
+
|
|
79
|
+
public phoneFullNameIndex = this.index([this.phone, this.fullName]);
|
|
80
|
+
public phoneIndex = this.uniqueIndex(this.phone);
|
|
81
|
+
|
|
82
|
+
public tableName(): string {
|
|
83
|
+
return 'users';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
```
|
|
87
|
+
### Cities Table
|
|
88
|
+
---
|
|
89
|
+
```typescript
|
|
90
|
+
interface CityMeta {
|
|
91
|
+
population: number,
|
|
92
|
+
connection: string,
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export default class CitiesTable extends AbstractTable<CitiesTable> {
|
|
96
|
+
public id = this.serial('id').primaryKey();
|
|
97
|
+
|
|
98
|
+
public foundationDate = this.timestamp('name').notNull();
|
|
99
|
+
public location = this.varchar('page', { size: 256 });
|
|
100
|
+
|
|
101
|
+
public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, { onUpdate: 'CASCADE' });
|
|
102
|
+
|
|
103
|
+
public metadata = this.jsonb<CityMeta>('metadata');
|
|
104
|
+
|
|
105
|
+
public tableName(): string {
|
|
106
|
+
return 'cities';
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
### User Groups Table
|
|
111
|
+
---
|
|
112
|
+
```typescript
|
|
113
|
+
export default class UserGroupsTable extends AbstractTable<UserGroupsTable> {
|
|
114
|
+
public id = this.serial('id').primaryKey();
|
|
115
|
+
|
|
116
|
+
public name = this.varchar('name');
|
|
117
|
+
public description = this.varchar('description');
|
|
118
|
+
|
|
119
|
+
public tableName(): string {
|
|
120
|
+
return 'user_groups';
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
### User to User Groups Table
|
|
125
|
+
---
|
|
126
|
+
#### Many to many connection between Users and User Groups
|
|
127
|
+
```typescript
|
|
128
|
+
export default class UsersToUserGroupsTable extends AbstractTable<UsersToUserGroupsTable> {
|
|
129
|
+
public groupId = this.int('city_id').foreignKey(UserGroupsTable, (table) => table.id, { onDelete: 'CASCADE' });
|
|
130
|
+
public userId = this.int('user_id').foreignKey(UsersTable, (table) => table.id, { onDelete: 'CASCADE' });
|
|
131
|
+
|
|
132
|
+
public manyToManyIndex = this.index([this.groupId, this.userId]);
|
|
133
|
+
|
|
134
|
+
public tableName(): string {
|
|
135
|
+
return 'users_to_user_groups';
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## CRUD
|
|
141
|
+
### **SELECT**
|
|
142
|
+
---
|
|
143
|
+
```typescript
|
|
144
|
+
const db = await new DbConnector()
|
|
145
|
+
.connectionString('postgresql://postgres@127.0.0.1/drizzle')
|
|
146
|
+
.connect();
|
|
147
|
+
|
|
148
|
+
const usersTable = new UsersTable(db);
|
|
149
|
+
|
|
150
|
+
// select all
|
|
151
|
+
const allSelect = await usersTable.select().all();
|
|
152
|
+
|
|
153
|
+
// select first
|
|
154
|
+
const firstSelect = await usersTable.select().findOne();
|
|
155
|
+
```
|
|
156
|
+
#### **Sorting and Filtering**
|
|
157
|
+
---
|
|
158
|
+
##### Select all records from `Users` where phone is `"hello"`
|
|
159
|
+
```typescript
|
|
160
|
+
const eqSelect = await usersTable.select().where(
|
|
161
|
+
eq(usersTable.phone, 'hello')
|
|
162
|
+
).all();
|
|
163
|
+
```
|
|
164
|
+
##### Select all records from `Users` where **both** phone is `"hello"` **and** phone is `"hello"`
|
|
165
|
+
```typescript
|
|
166
|
+
const andSelect = await usersTable.select().where(
|
|
167
|
+
and([
|
|
168
|
+
eq(usersTable.phone, 'hello'),
|
|
169
|
+
eq(usersTable.phone, 'hello')
|
|
170
|
+
]),
|
|
171
|
+
).all();
|
|
172
|
+
```
|
|
173
|
+
##### Select all records from `Users` where **either** phone is `"hello"` **or** phone is `"hello"`
|
|
174
|
+
```typescript
|
|
175
|
+
const orSelect = await usersTable.select().where(
|
|
176
|
+
or([eq(usersTable.phone, 'hello')]),
|
|
177
|
+
).all();
|
|
178
|
+
```
|
|
179
|
+
##### Select all records from `Users` using **LIMIT** and **OFFSET**
|
|
180
|
+
```typescript
|
|
181
|
+
const limitOffsetSelect = await usersTable.select().limit(10).offset(10).all();
|
|
182
|
+
```
|
|
183
|
+
##### Select all records from `Users` where `phone` contains `"hello"`
|
|
184
|
+
```typescript
|
|
185
|
+
const likeSelect = await usersTable.select().where(
|
|
186
|
+
like(usersTable.phone, '%hello%')
|
|
187
|
+
).all();
|
|
188
|
+
```
|
|
189
|
+
##### Select all records from `Users` where `phone` equals to some of values from array
|
|
190
|
+
```typescript
|
|
191
|
+
const inArraySelect = usersTable.select().where(
|
|
192
|
+
inArray(usersTable.phone, ['hello'])
|
|
193
|
+
).all();
|
|
194
|
+
```
|
|
195
|
+
##### Select all records from `Users` where `phone` greater(**>**) than `"hello"`
|
|
196
|
+
```typescript
|
|
197
|
+
const greaterSelect = usersTable.select().where(
|
|
198
|
+
greater(usersTable.phone, 'hello')
|
|
199
|
+
).all();
|
|
200
|
+
```
|
|
201
|
+
##### Select all records from `Users` where `phone` less(**<**) than `"hello"`
|
|
202
|
+
```typescript
|
|
203
|
+
const lessSelect = usersTable.select().where(
|
|
204
|
+
less(usersTable.phone, 'hello')
|
|
205
|
+
).all();
|
|
206
|
+
```
|
|
207
|
+
##### Select all records from `Users` where `phone` greater or equals(**>=**) than `"hello"`
|
|
208
|
+
```typescript
|
|
209
|
+
const greaterEqSelect = usersTable.select().where(
|
|
210
|
+
greaterEq(usersTable.phone, 'hello')
|
|
211
|
+
).all();
|
|
212
|
+
```
|
|
213
|
+
##### Select all records from `Users` where `phone` less or equals(**<=**)
|
|
214
|
+
```typescript
|
|
215
|
+
const lessEqSelect = usersTable.select().where(
|
|
216
|
+
lessEq(usersTable.phone, 'hello')
|
|
217
|
+
).all();
|
|
218
|
+
```
|
|
219
|
+
##### Select all records from `Users` where `phone` is **NULL**
|
|
220
|
+
```typescript
|
|
221
|
+
const isNullSelect = usersTable.select().where(
|
|
222
|
+
isNull(usersTable.phone)
|
|
223
|
+
).all();
|
|
224
|
+
```
|
|
225
|
+
##### Select all records from `Users` where `phone` not equals to `"hello"`
|
|
226
|
+
```typescript
|
|
227
|
+
const notEqSelect = usersTable.select().where(
|
|
228
|
+
notEq(usersTable.phone, 'hello')
|
|
229
|
+
).all();
|
|
230
|
+
```
|
|
231
|
+
##### Select all records from `Users` ordered by `phone` in ascending order
|
|
232
|
+
```typescript
|
|
233
|
+
const ordered = await usersTable.select().orderBy((table) => table.phone, Order.ASC).all();
|
|
234
|
+
```
|
|
235
|
+
#### **Partial Selecting**
|
|
236
|
+
```typescript
|
|
237
|
+
const partialSelect = await usersTable.select({
|
|
238
|
+
mappedId: usersTable.id,
|
|
239
|
+
mappedPhone: usersTable.phone,
|
|
240
|
+
}).all();
|
|
241
|
+
|
|
242
|
+
// Usage
|
|
243
|
+
const { mappedId, mappedPhone } = partialSelect;
|
|
244
|
+
```
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
### **Update**
|
|
248
|
+
---
|
|
249
|
+
##### Update `fullName` to `newName` in `Users` where phone is `"hello"`
|
|
250
|
+
```typescript
|
|
251
|
+
await usersTable.update()
|
|
252
|
+
.where(eq(usersTable.phone, 'hello'))
|
|
253
|
+
.set({ fullName: 'newName' })
|
|
254
|
+
.execute();
|
|
255
|
+
```
|
|
256
|
+
##### Update `fullName` to `newName` in `Users` where phone is `"hello"` returning updated `User` model
|
|
257
|
+
```typescript
|
|
258
|
+
await usersTable.update()
|
|
259
|
+
.where(eq(usersTable.phone, 'hello'))
|
|
260
|
+
.set({ fullName: 'newName' })
|
|
261
|
+
.all();
|
|
262
|
+
```
|
|
263
|
+
##### Update `fullName` to `newName` in `Users` where phone is `"hello"` returning updated `User` model
|
|
264
|
+
```typescript
|
|
265
|
+
await usersTable.update()
|
|
266
|
+
.where(eq(usersTable.phone, 'hello'))
|
|
267
|
+
.set({ fullName: 'newName' })
|
|
268
|
+
.findOne();
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### **Delete**
|
|
272
|
+
##### Delete `user` where phone is `"hello"`
|
|
273
|
+
```typescript
|
|
274
|
+
await usersTable.delete()
|
|
275
|
+
.where(eq(usersTable.phone, 'hello'))
|
|
276
|
+
.execute();
|
|
277
|
+
```
|
|
278
|
+
##### Delete `user` where phone is `"hello"` returning updated `User` model
|
|
279
|
+
```typescript
|
|
280
|
+
await usersTable.delete()
|
|
281
|
+
.where(eq(usersTable.phone, 'hello'))
|
|
282
|
+
.all();
|
|
283
|
+
```
|
|
284
|
+
##### Delete `user` where phone is `"hello"` returning updated `User` model
|
|
285
|
+
```typescript
|
|
286
|
+
await usersTable.delete()
|
|
287
|
+
.where(eq(usersTable.phone, 'hello'))
|
|
288
|
+
.findOne();
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
### **Insert**
|
|
292
|
+
##### Insert `user` with required fields
|
|
293
|
+
```typescript
|
|
294
|
+
await usersTable.insert({
|
|
295
|
+
test: 1,
|
|
296
|
+
createdAt: new Date(),
|
|
297
|
+
}).execute();
|
|
298
|
+
```
|
|
299
|
+
##### Insert `user` with required fields and get all rows as array
|
|
300
|
+
```typescript
|
|
301
|
+
const user = await usersTable.insert({
|
|
302
|
+
test: 1,
|
|
303
|
+
createdAt: new Date(),
|
|
304
|
+
}).all();
|
|
305
|
+
```
|
|
306
|
+
##### Insert `user` with required fields and get inserted entity
|
|
307
|
+
```typescript
|
|
308
|
+
const user = await usersTable.insert({
|
|
309
|
+
test: 1,
|
|
310
|
+
createdAt: new Date(),
|
|
311
|
+
}).findOne();
|
|
312
|
+
```
|
|
313
|
+
##### Insert many `users` with required fields and get all inserted entities
|
|
314
|
+
```typescript
|
|
315
|
+
const users = await usersTable.insertMany([{
|
|
316
|
+
test: 1,
|
|
317
|
+
createdAt: new Date(),
|
|
318
|
+
}, {
|
|
319
|
+
test: 2,
|
|
320
|
+
createdAt: new Date(),
|
|
321
|
+
}]).all();
|
|
322
|
+
```
|
|
323
|
+
##### Insert many `users` with required fields and get all inserted entities. If such user already exists - update `phone` field
|
|
324
|
+
```typescript
|
|
325
|
+
await usersTable.insertMany([{
|
|
326
|
+
test: 1,
|
|
327
|
+
createdAt: new Date(),
|
|
328
|
+
}, {
|
|
329
|
+
test: 2,
|
|
330
|
+
createdAt: new Date(),
|
|
331
|
+
}])
|
|
332
|
+
.onConflict(
|
|
333
|
+
(table) => table.phoneIndex,
|
|
334
|
+
{ phone: 'confilctUpdate' },
|
|
335
|
+
).all();
|
|
336
|
+
```
|
|
337
|
+
|
|
338
|
+
## Joins
|
|
339
|
+
### Join One-To-Many Tables
|
|
340
|
+
##### Join Cities with Users and map to city object with full user
|
|
341
|
+
```typescript
|
|
342
|
+
const usersTable = new UsersTable(db);
|
|
343
|
+
const citiesTable = new CitiesTable(db);
|
|
344
|
+
|
|
345
|
+
const userWithCities = await citiesTable.select()
|
|
346
|
+
.where(eq(citiesTable.id, 1))
|
|
347
|
+
.leftJoin(UsersTable,
|
|
348
|
+
(city) => city.userId,
|
|
349
|
+
(users) => users.id)
|
|
350
|
+
.execute();
|
|
351
|
+
|
|
352
|
+
const citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
### Join Many-To-Many Tables
|
|
356
|
+
##### Join User Groups with Users, using many-to-many table and map response to get user object with groups array
|
|
357
|
+
```typescript
|
|
358
|
+
const usersWithUserGroups = await usersToUserGroupsTable.select()
|
|
359
|
+
.where(eq(userGroupsTable.id, 1))
|
|
360
|
+
.leftJoin(UsersTable,
|
|
361
|
+
(userToGroup) => userToGroup.userId,
|
|
362
|
+
(users) => users.id)
|
|
363
|
+
.leftJoin(UsersToUserGroupsTable, UserGroupsTable,
|
|
364
|
+
(userToGroup) => userToGroup.groupId,
|
|
365
|
+
(users) => users.id)
|
|
366
|
+
.execute();
|
|
367
|
+
|
|
368
|
+
const userGroupWithUsers = usersWithUserGroups.group({
|
|
369
|
+
one: (_, dbUser, dbUserGroup) => dbUser!,
|
|
370
|
+
many: (_, dbUser, dbUserGroup) => dbUserGroup!,
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
const userWithGroups: ExtractModel<UsersTable> & { groups: ExtractModel<UserGroupsTable>[] } = {
|
|
374
|
+
...userGroupWithUsers.one,
|
|
375
|
+
groups: userGroupWithUsers.many,
|
|
376
|
+
};
|
|
377
|
+
```
|
|
378
|
+
##### Join User Groups with Users, using many-to-many table and map response to get user group object with users array
|
|
379
|
+
```typescript
|
|
380
|
+
const usersWithUserGroups = await usersToUserGroupsTable.select()
|
|
381
|
+
.where(eq(userGroupsTable.id, 1))
|
|
382
|
+
.leftJoin(UsersTable,
|
|
383
|
+
(userToGroup) => userToGroup.userId,
|
|
384
|
+
(users) => users.id)
|
|
385
|
+
.leftJoin(UsersToUserGroupsTable, UserGroupsTable,
|
|
386
|
+
(userToGroup) => userToGroup.groupId,
|
|
387
|
+
(users) => users.id)
|
|
388
|
+
.execute();
|
|
389
|
+
|
|
390
|
+
const userGroupWithUsers = usersWithUserGroups.group({
|
|
391
|
+
one: (_, dbUser, dbUserGroup) => dbUserGroup!,
|
|
392
|
+
many: (_, dbUser, dbUserGroup) => dbUser!,
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
const userWithGroups: ExtractModel<UserGroupsTable> & { users: ExtractModel<UsersTable>[] } = {
|
|
396
|
+
...userGroupWithUsers.one,
|
|
397
|
+
users: userGroupWithUsers.many,
|
|
398
|
+
};
|
|
399
|
+
```
|
|
400
|
+
### Join using partial field select
|
|
401
|
+
##### Join Cities with Users getting only needed fields form request
|
|
402
|
+
```typescript
|
|
403
|
+
await citiesTable.select({
|
|
404
|
+
id: citiesTable.id,
|
|
405
|
+
userId: citiesTable.userId,
|
|
406
|
+
})
|
|
407
|
+
.where(eq(citiesTable.id, 1))
|
|
408
|
+
.leftJoin(UsersTable,
|
|
409
|
+
(city) => city.userId,
|
|
410
|
+
(users) => users.id,
|
|
411
|
+
{
|
|
412
|
+
id: usersTable.id,
|
|
413
|
+
})
|
|
414
|
+
.execute();
|
|
415
|
+
|
|
416
|
+
const citiesWithUserObject = userWithCities.map((city, user) => ({ ...city, user }));
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
## Migrations
|
|
421
|
+
#### To run migrations generated by drizzle-kit you could use `Migrator` class
|
|
422
|
+
##### Provide drizzle-kit config path
|
|
423
|
+
```typescript
|
|
424
|
+
await drizzle.migrator(db).migrate('src/drizzle.config.yaml');
|
|
425
|
+
```
|
|
426
|
+
##### Another possibility is to provide object with path to folder with migrations
|
|
427
|
+
```typescript
|
|
428
|
+
await drizzle.migrator(db).migrate({ migrationFolder: 'drizzle' });
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
|
|
432
|
+
## Raw query usage
|
|
433
|
+
#### If you have some complex queries to execute and drizzle-orm can't handle them yet, then you could use `rawQuery` execution
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
##### Execute custom raw query
|
|
437
|
+
```typescript
|
|
438
|
+
const res: QueryResult<any> = await db.session().execute('SELECT * FROM users WHERE user.id = $1', [1]);
|
|
439
|
+
```
|
|
@@ -13,7 +13,7 @@ class DeleteAggregator extends abstractAggregator_1.default {
|
|
|
13
13
|
this._delete = ['DELETE'];
|
|
14
14
|
this.filters = (filters) => {
|
|
15
15
|
if (filters) {
|
|
16
|
-
const filterQuery = filters.toQuery();
|
|
16
|
+
const filterQuery = filters.toQuery({ session: this._table.db.session() });
|
|
17
17
|
this._filters.push('WHERE ');
|
|
18
18
|
this._filters.push(filterQuery.query);
|
|
19
19
|
this._values = filterQuery.values;
|
|
@@ -43,7 +43,7 @@ class InsertAggregator extends abstractAggregator_1.default {
|
|
|
43
43
|
if (isKeyExistsInValue) {
|
|
44
44
|
if (valueToInsert !== undefined && valueToInsert !== null) {
|
|
45
45
|
position += 1;
|
|
46
|
-
this._query.push(
|
|
46
|
+
this._query.push(this._table.db.session().parametrized(position));
|
|
47
47
|
this._values.push(column.getColumnType().insertStrategy(valueToInsert));
|
|
48
48
|
}
|
|
49
49
|
else {
|
|
@@ -73,7 +73,10 @@ class InsertAggregator extends abstractAggregator_1.default {
|
|
|
73
73
|
if (updates) {
|
|
74
74
|
const currentPointerPosition = this._values.length > 0
|
|
75
75
|
? this._values.length + 1 : undefined;
|
|
76
|
-
const updatesQuery = updates.toQuery(
|
|
76
|
+
const updatesQuery = updates.toQuery({
|
|
77
|
+
position: currentPointerPosition,
|
|
78
|
+
session: this._table.db.session(),
|
|
79
|
+
});
|
|
77
80
|
this._onConflict.push('DO UPDATE\n');
|
|
78
81
|
this._onConflict.push(`SET ${updatesQuery.query}`);
|
|
79
82
|
this._values.push(...updatesQuery.values);
|
|
@@ -24,7 +24,7 @@ class SelectAggregator extends abstractAggregator_1.default {
|
|
|
24
24
|
this._joinCache = {};
|
|
25
25
|
this.filters = (filters) => {
|
|
26
26
|
if (filters) {
|
|
27
|
-
const queryBuilder = filters.toQuery(1, this._joinCache);
|
|
27
|
+
const queryBuilder = filters.toQuery({ position: 1, tableCache: this._joinCache, session: this._table.db.session() });
|
|
28
28
|
this._filters.push('WHERE ');
|
|
29
29
|
this._filters.push(queryBuilder.query);
|
|
30
30
|
this._values = queryBuilder.values;
|
|
@@ -15,7 +15,10 @@ class UpdateAggregator extends abstractAggregator_1.default {
|
|
|
15
15
|
this.where = (filters) => {
|
|
16
16
|
if (filters) {
|
|
17
17
|
const currentPointerPosition = this._values.length > 0 ? this._values.length + 1 : undefined;
|
|
18
|
-
const filterQuery = filters.toQuery(
|
|
18
|
+
const filterQuery = filters.toQuery({
|
|
19
|
+
position: currentPointerPosition,
|
|
20
|
+
session: this._table.db.session(),
|
|
21
|
+
});
|
|
19
22
|
this._filters.push('WHERE ');
|
|
20
23
|
this._filters.push(filterQuery.query);
|
|
21
24
|
this._values.push(...filterQuery.values);
|
|
@@ -28,7 +31,7 @@ class UpdateAggregator extends abstractAggregator_1.default {
|
|
|
28
31
|
return this;
|
|
29
32
|
};
|
|
30
33
|
this.set = (updates) => {
|
|
31
|
-
const setQuery = updates.toQuery();
|
|
34
|
+
const setQuery = updates.toQuery({ session: this._table.db.session() });
|
|
32
35
|
this._updates.push(`\nSET ${setQuery.query}`);
|
|
33
36
|
this._values.push(...setQuery.values);
|
|
34
37
|
return this;
|
|
@@ -48,7 +48,7 @@ class DeleteTRB extends abstractRequestBuilder_1.default {
|
|
|
48
48
|
values = builderResult.values;
|
|
49
49
|
}
|
|
50
50
|
catch (e) {
|
|
51
|
-
throw new builderError_1.default(builderError_1.BuilderType.DELETE, this._table.tableName(), this._columns, e, this._filter);
|
|
51
|
+
throw new builderError_1.default(builderError_1.BuilderType.DELETE, this._table.tableName(), this._columns, e, this._session, this._filter);
|
|
52
52
|
}
|
|
53
53
|
if (this._logger) {
|
|
54
54
|
this._logger.info(`Deleting from ${this._table.tableName()} using query:\n ${query}`);
|
|
@@ -59,7 +59,7 @@ class InsertTRB extends abstractRequestBuilder_1.default {
|
|
|
59
59
|
values = builderResult.values;
|
|
60
60
|
}
|
|
61
61
|
catch (e) {
|
|
62
|
-
throw new builderError_1.default(builderError_1.BuilderType.INSERT, this._table.tableName(), this._columns, e);
|
|
62
|
+
throw new builderError_1.default(builderError_1.BuilderType.INSERT, this._table.tableName(), this._columns, e, this._session);
|
|
63
63
|
}
|
|
64
64
|
if (this._logger) {
|
|
65
65
|
this._logger.info(`Inserting to ${this._table.tableName()} using query:\n ${query}\n${values}`);
|
|
@@ -68,7 +68,7 @@ class SelectTRB extends abstractRequestBuilder_1.default {
|
|
|
68
68
|
values = builderResult.values;
|
|
69
69
|
}
|
|
70
70
|
catch (e) {
|
|
71
|
-
throw new builderError_1.default(builderError_1.BuilderType.SELECT, this._table.tableName(), this._columns, e, this._filter);
|
|
71
|
+
throw new builderError_1.default(builderError_1.BuilderType.SELECT, this._table.tableName(), this._columns, e, this._session, this._filter);
|
|
72
72
|
}
|
|
73
73
|
if (this._logger) {
|
|
74
74
|
this._logger.info(`Selecting from ${this._table.tableName()} using query:\n ${query}`);
|
|
@@ -99,7 +99,7 @@ class SelectTRB extends abstractRequestBuilder_1.default {
|
|
|
99
99
|
const toColumn = to(toTable);
|
|
100
100
|
const join = new __1.JoinWith(toTable.tableName(), toTable.mapServiceToDb())
|
|
101
101
|
.columns(fromColumn, toColumn).joinStrategy(join_1.JoinStrategy.INNER_JOIN);
|
|
102
|
-
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial);
|
|
102
|
+
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial, this._logger);
|
|
103
103
|
}
|
|
104
104
|
leftJoin(table, from, to, partial) {
|
|
105
105
|
const toTable = this._table.db.create(table);
|
|
@@ -107,7 +107,7 @@ class SelectTRB extends abstractRequestBuilder_1.default {
|
|
|
107
107
|
const toColumn = to(toTable);
|
|
108
108
|
const join = new __1.JoinWith(toTable.tableName(), toTable.mapServiceToDb())
|
|
109
109
|
.columns(fromColumn, toColumn).joinStrategy(join_1.JoinStrategy.LEFT_JOIN);
|
|
110
|
-
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial);
|
|
110
|
+
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial, this._logger);
|
|
111
111
|
}
|
|
112
112
|
rightJoin(table, from, to, partial) {
|
|
113
113
|
const toTable = this._table.db.create(table);
|
|
@@ -115,7 +115,7 @@ class SelectTRB extends abstractRequestBuilder_1.default {
|
|
|
115
115
|
const toColumn = to(toTable);
|
|
116
116
|
const join = new __1.JoinWith(toTable.tableName(), toTable.mapServiceToDb())
|
|
117
117
|
.columns(fromColumn, toColumn).joinStrategy(join_1.JoinStrategy.RIGHT_JOIN);
|
|
118
|
-
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial);
|
|
118
|
+
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial, this._logger);
|
|
119
119
|
}
|
|
120
120
|
fullJoin(table, from, to, partial) {
|
|
121
121
|
const toTable = this._table.db.create(table);
|
|
@@ -123,7 +123,7 @@ class SelectTRB extends abstractRequestBuilder_1.default {
|
|
|
123
123
|
const toColumn = to(toTable);
|
|
124
124
|
const join = new __1.JoinWith(toTable.tableName(), toTable.mapServiceToDb())
|
|
125
125
|
.columns(fromColumn, toColumn).joinStrategy(join_1.JoinStrategy.FULL_JOIN);
|
|
126
|
-
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial);
|
|
126
|
+
return new selectWithJoin_1.default(this._table, this._session, this._filter, join, this.props, this.__orderBy, this.__order, this.__distinct, this.__partial, partial, this._logger);
|
|
127
127
|
}
|
|
128
128
|
}
|
|
129
129
|
exports.default = SelectTRB;
|
|
@@ -66,7 +66,7 @@ class UpdateTRB extends abstractRequestBuilder_1.default {
|
|
|
66
66
|
values = builderResult.values;
|
|
67
67
|
}
|
|
68
68
|
catch (e) {
|
|
69
|
-
throw new builderError_1.default(builderError_1.BuilderType.UPDATE, this._table.tableName(), this._columns, e, this._filter);
|
|
69
|
+
throw new builderError_1.default(builderError_1.BuilderType.UPDATE, this._table.tableName(), this._columns, e, this._session, this._filter);
|
|
70
70
|
}
|
|
71
71
|
if (this._logger) {
|
|
72
72
|
this._logger.info(`Updating ${this._table.tableName()} using query:\n ${query}`);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import BaseLogger from 'orm/src/logger/abstractLogger';
|
|
1
2
|
import { QueryResult } from 'pg';
|
|
2
3
|
import { AbstractColumn } from '../../../columns/column';
|
|
3
4
|
import ColumnType from '../../../columns/types/columnType';
|
|
@@ -19,10 +20,11 @@ export default abstract class AbstractJoined<TTable extends AbstractTable<TTable
|
|
|
19
20
|
protected _orderBy?: AbstractColumn<ColumnType, boolean, boolean>;
|
|
20
21
|
protected _order?: Order;
|
|
21
22
|
protected _partial?: TPartial;
|
|
23
|
+
protected _logger?: BaseLogger;
|
|
22
24
|
constructor(table: TTable, filter: Expr, session: ISession, props: {
|
|
23
25
|
limit?: number;
|
|
24
26
|
offset?: number;
|
|
25
|
-
}, orderBy?: AbstractColumn<ColumnType, boolean, boolean>, order?: Order, distinct?: AbstractColumn<ColumnType, boolean, boolean>, tablePartial?: TPartial);
|
|
27
|
+
}, orderBy?: AbstractColumn<ColumnType, boolean, boolean>, order?: Order, distinct?: AbstractColumn<ColumnType, boolean, boolean>, tablePartial?: TPartial, logger?: BaseLogger);
|
|
26
28
|
limit: (limit: number) => this;
|
|
27
29
|
offset: (offset: number) => this;
|
|
28
30
|
execute: () => Promise<TRes>;
|
|
@@ -26,7 +26,7 @@ const builderError_1 = __importStar(require("../../../errors/builderError"));
|
|
|
26
26
|
const responseMapper_1 = __importDefault(require("../../../mappers/responseMapper"));
|
|
27
27
|
const select_1 = __importDefault(require("../../lowLvlBuilders/selects/select"));
|
|
28
28
|
class AbstractJoined {
|
|
29
|
-
constructor(table, filter, session, props, orderBy, order, distinct, tablePartial) {
|
|
29
|
+
constructor(table, filter, session, props, orderBy, order, distinct, tablePartial, logger) {
|
|
30
30
|
this.limit = (limit) => {
|
|
31
31
|
this._props.limit = limit;
|
|
32
32
|
return this;
|
|
@@ -52,7 +52,11 @@ class AbstractJoined {
|
|
|
52
52
|
values = builderResult.values;
|
|
53
53
|
}
|
|
54
54
|
catch (e) {
|
|
55
|
-
throw new builderError_1.default(builderError_1.BuilderType.JOINED_SELECT, this._table.tableName(), Object.values(this._table.mapServiceToDb()), e, this._filter);
|
|
55
|
+
throw new builderError_1.default(builderError_1.BuilderType.JOINED_SELECT, this._table.tableName(), Object.values(this._table.mapServiceToDb()), e, this._session, this._filter);
|
|
56
|
+
}
|
|
57
|
+
if (this._logger) {
|
|
58
|
+
this._logger.info(`Selecting from ${this._table.tableName()} using query:\n ${query}`);
|
|
59
|
+
this._logger.info(`Values for query:\n ${values}`);
|
|
56
60
|
}
|
|
57
61
|
const result = await this._session.execute(query, values);
|
|
58
62
|
return this.mapResponse(result);
|
|
@@ -65,6 +69,7 @@ class AbstractJoined {
|
|
|
65
69
|
this._orderBy = orderBy;
|
|
66
70
|
this._distinct = distinct;
|
|
67
71
|
this._partial = tablePartial;
|
|
72
|
+
this._logger = logger;
|
|
68
73
|
}
|
|
69
74
|
fullOrPartial(mappedServiceToDb, result, partial, joinId) {
|
|
70
75
|
if (partial) {
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import BaseLogger from 'orm/src/logger/abstractLogger';
|
|
1
2
|
import { QueryResult } from 'pg';
|
|
2
3
|
import { AbstractColumn } from '../../../columns/column';
|
|
3
4
|
import ColumnType from '../../../columns/types/columnType';
|
|
@@ -23,7 +24,7 @@ export default class SelectTRBWithFiveJoins<TTable extends AbstractTable<TTable>
|
|
|
23
24
|
constructor(table: TTable, session: ISession, filter: Expr, join1: Join<TTable1>, join2: Join<TTable2>, join3: Join<TTable3>, join4: Join<TTable4>, join5: Join<TTable5>, props: {
|
|
24
25
|
limit?: number;
|
|
25
26
|
offset?: number;
|
|
26
|
-
}, orderBy?: AbstractColumn<ColumnType, boolean, boolean>, order?: Order, distinct?: AbstractColumn<ColumnType, boolean, boolean>, tablePartial?: TPartial, joinedPartial?: TPartial1, joinedPartial1?: TPartial2, joinedPartial2?: TPartial3, joinedPartial3?: TPartial4, joinedPartial4?: TPartial5);
|
|
27
|
+
}, orderBy?: AbstractColumn<ColumnType, boolean, boolean>, order?: Order, distinct?: AbstractColumn<ColumnType, boolean, boolean>, tablePartial?: TPartial, joinedPartial?: TPartial1, joinedPartial1?: TPartial2, joinedPartial2?: TPartial3, joinedPartial3?: TPartial4, joinedPartial4?: TPartial5, logger?: BaseLogger);
|
|
27
28
|
protected joins(): Array<{
|
|
28
29
|
join: Join<any>;
|
|
29
30
|
partial?: {
|
|
@@ -6,8 +6,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
6
6
|
const selectResponseFiveJoins_1 = __importDefault(require("../responses/selectResponseFiveJoins"));
|
|
7
7
|
const abstractJoinBuilder_1 = __importDefault(require("./abstractJoinBuilder"));
|
|
8
8
|
class SelectTRBWithFiveJoins extends abstractJoinBuilder_1.default {
|
|
9
|
-
constructor(table, session, filter, join1, join2, join3, join4, join5, props, orderBy, order, distinct, tablePartial, joinedPartial, joinedPartial1, joinedPartial2, joinedPartial3, joinedPartial4) {
|
|
10
|
-
super(table, filter, session, props, orderBy, order, distinct, tablePartial);
|
|
9
|
+
constructor(table, session, filter, join1, join2, join3, join4, join5, props, orderBy, order, distinct, tablePartial, joinedPartial, joinedPartial1, joinedPartial2, joinedPartial3, joinedPartial4, logger) {
|
|
10
|
+
super(table, filter, session, props, orderBy, order, distinct, tablePartial, logger);
|
|
11
11
|
this._join1 = join1;
|
|
12
12
|
this._join2 = join2;
|
|
13
13
|
this._join3 = join3;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import BaseLogger from 'orm/src/logger/abstractLogger';
|
|
1
2
|
import { QueryResult } from 'pg';
|
|
2
3
|
import { AbstractColumn } from '../../../columns/column';
|
|
3
4
|
import ColumnType from '../../../columns/types/columnType';
|
|
@@ -23,7 +24,7 @@ export default class SelectTRBWithFourJoins<TTable extends AbstractTable<TTable>
|
|
|
23
24
|
constructor(table: TTable, session: ISession, filter: Expr, join1: Join<TTable1>, join2: Join<TTable2>, join3: Join<TTable3>, join4: Join<TTable4>, props: {
|
|
24
25
|
limit?: number;
|
|
25
26
|
offset?: number;
|
|
26
|
-
}, orderBy?: AbstractColumn<ColumnType, boolean, boolean>, order?: Order, distinct?: AbstractColumn<ColumnType, boolean, boolean>, tablePartial?: TPartial, joinedPartial?: TPartial1, joinedPartial1?: TPartial2, joinedPartial2?: TPartial3, joinedPartial3?: TPartial4);
|
|
27
|
+
}, orderBy?: AbstractColumn<ColumnType, boolean, boolean>, order?: Order, distinct?: AbstractColumn<ColumnType, boolean, boolean>, tablePartial?: TPartial, joinedPartial?: TPartial1, joinedPartial1?: TPartial2, joinedPartial2?: TPartial3, joinedPartial3?: TPartial4, logger?: BaseLogger);
|
|
27
28
|
innerJoin<InputTable extends AbstractTable<InputTable>, TColumn extends ColumnType, TToColumn extends ColumnType, IToTable extends AbstractTable<IToTable>, IToPartial extends PartialFor<IToTable> = {}>(fromTable: {
|
|
28
29
|
new (db: DB): InputTable;
|
|
29
30
|
}, table: {
|