drizzle-orm 0.10.11 → 0.10.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.
- package/README.md +439 -0
- package/builders/aggregators/selectAggregator.js +2 -1
- package/builders/requestBuilders/where/constArray.js +2 -2
- package/columns/column.js +9 -1
- package/columns/types/pgInteger.js +3 -0
- package/package.json +1 -1
- package/tables/aggregators.d.ts +27 -0
- package/tables/aggregators.js +56 -0
- package/tables/inferTypes.d.ts +1 -1
- package/test.d.ts +1 -0
- package/test.js +50 -0
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
|
+
```
|
|
@@ -45,7 +45,8 @@ class SelectAggregator extends abstractAggregator_1.default {
|
|
|
45
45
|
this.orderBy = (column, order) => {
|
|
46
46
|
if (column !== null && column !== undefined) {
|
|
47
47
|
this._orderBy.push('ORDER BY ');
|
|
48
|
-
this.
|
|
48
|
+
const columnParent = this._joinCache[column.getParent().tableName()] ? this._joinCache[column.getParent().tableName()] : column.getParent();
|
|
49
|
+
this._orderBy.push(`${columnParent}.${ecranate_1.ecranate(column.getColumnName())} `);
|
|
49
50
|
this._orderBy.push(order_1.default[order]);
|
|
50
51
|
}
|
|
51
52
|
return this;
|
|
@@ -15,7 +15,7 @@ class ConstArray extends where_1.default {
|
|
|
15
15
|
finalArray.push(`$${nextPosition}`);
|
|
16
16
|
finalValues.push(`${value.toISOString()}`);
|
|
17
17
|
}
|
|
18
|
-
if (ecranate_1.shouldEcranate(value)) {
|
|
18
|
+
else if (ecranate_1.shouldEcranate(value)) {
|
|
19
19
|
finalArray.push(`$${nextPosition}`);
|
|
20
20
|
finalValues.push(`${value.toString()}`);
|
|
21
21
|
}
|
|
@@ -28,7 +28,7 @@ class ConstArray extends where_1.default {
|
|
|
28
28
|
}
|
|
29
29
|
nextPosition += 1;
|
|
30
30
|
}
|
|
31
|
-
return { query: finalArray.join('
|
|
31
|
+
return { query: finalArray.join(''), values: finalValues };
|
|
32
32
|
};
|
|
33
33
|
this.values = values;
|
|
34
34
|
}
|
package/columns/column.js
CHANGED
|
@@ -16,7 +16,15 @@ class AbstractColumn {
|
|
|
16
16
|
this.getParent = () => this.parent;
|
|
17
17
|
this.getParentName = () => this.parentTableName;
|
|
18
18
|
this.defaultValue = (value) => {
|
|
19
|
-
|
|
19
|
+
if (Defaults[value] !== undefined) {
|
|
20
|
+
this.defaultParam = value;
|
|
21
|
+
}
|
|
22
|
+
else if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'bigint') {
|
|
23
|
+
this.defaultParam = value;
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
this.defaultParam = `'${value}'`;
|
|
27
|
+
}
|
|
20
28
|
return this;
|
|
21
29
|
};
|
|
22
30
|
this.unique = () => {
|
package/package.json
CHANGED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { AbstractColumn } from '../columns/column';
|
|
2
|
+
import ColumnType from '../columns/types/columnType';
|
|
3
|
+
import { DB } from '../db';
|
|
4
|
+
import AbstractTable from './abstractTable';
|
|
5
|
+
export declare class AggregatedColumn<T extends ColumnType, TNullable extends boolean = true, TAutoIncrement extends boolean = false, TParent extends AbstractTable<any> = any> extends AbstractColumn<T, TNullable, TAutoIncrement, TParent> {
|
|
6
|
+
columnToAggregate?: AbstractColumn<ColumnType<any>, boolean, boolean>;
|
|
7
|
+
constructor(parent: TParent, columnName: string, columnType: T, columnToAggregate?: AbstractColumn<ColumnType<any>, boolean, boolean>);
|
|
8
|
+
foreignKey<ITable extends AbstractTable<ITable>>(table: new (db: DB) => ITable, callback: (table: ITable) => AbstractColumn<T, boolean, boolean, TParent>, onConstraint: {
|
|
9
|
+
onDelete?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'SET DEFAULT' | undefined;
|
|
10
|
+
onUpdate?: 'CASCADE' | 'RESTRICT' | 'SET NULL' | 'SET DEFAULT' | undefined;
|
|
11
|
+
}): AbstractColumn<T, TNullable, TAutoIncrement, any>;
|
|
12
|
+
primaryKey(): AbstractColumn<T, boolean, boolean, TParent>;
|
|
13
|
+
notNull(): AbstractColumn<T, boolean, boolean, TParent>;
|
|
14
|
+
getAlias(): string;
|
|
15
|
+
}
|
|
16
|
+
export declare abstract class PgAggregatedColumnType<TType, T extends AbstractColumn<ColumnType<any>, boolean, boolean> = any> extends ColumnType<TType> {
|
|
17
|
+
protected dbName: string;
|
|
18
|
+
protected column?: T;
|
|
19
|
+
constructor(column?: T);
|
|
20
|
+
insertStrategy(value: TType): string;
|
|
21
|
+
}
|
|
22
|
+
export declare class PgCount<T extends AbstractColumn<ColumnType<any>, boolean, boolean> = any> extends PgAggregatedColumnType<number, T> {
|
|
23
|
+
constructor(column?: T);
|
|
24
|
+
getDbName(): string;
|
|
25
|
+
selectStrategy(value: any): number | undefined;
|
|
26
|
+
}
|
|
27
|
+
export declare const count: <TType extends ColumnType<any>, T extends AbstractColumn<TType, boolean, boolean, any>>(column?: T | undefined) => AggregatedColumn<PgCount<any>, false, true, any>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/* eslint-disable import/no-cycle */
|
|
3
|
+
/* eslint-disable @typescript-eslint/no-unused-vars */
|
|
4
|
+
/* eslint-disable max-len */
|
|
5
|
+
/* eslint-disable max-classes-per-file */
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.count = exports.PgCount = exports.PgAggregatedColumnType = exports.AggregatedColumn = void 0;
|
|
8
|
+
const column_1 = require("../columns/column");
|
|
9
|
+
const columnType_1 = require("../columns/types/columnType");
|
|
10
|
+
const ecranate_1 = require("../utils/ecranate");
|
|
11
|
+
class AggregatedColumn extends column_1.AbstractColumn {
|
|
12
|
+
constructor(parent, columnName, columnType, columnToAggregate) {
|
|
13
|
+
super(parent, columnName, columnType);
|
|
14
|
+
this.columnToAggregate = columnToAggregate;
|
|
15
|
+
}
|
|
16
|
+
foreignKey(table, callback, onConstraint) {
|
|
17
|
+
throw new Error('Method not implemented.');
|
|
18
|
+
}
|
|
19
|
+
primaryKey() {
|
|
20
|
+
throw new Error('Method not implemented.');
|
|
21
|
+
}
|
|
22
|
+
notNull() {
|
|
23
|
+
throw new Error('Method not implemented.');
|
|
24
|
+
}
|
|
25
|
+
getAlias() {
|
|
26
|
+
super.getAlias();
|
|
27
|
+
return `${this.columnName}`;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.AggregatedColumn = AggregatedColumn;
|
|
31
|
+
class PgAggregatedColumnType extends columnType_1.default {
|
|
32
|
+
constructor(column) {
|
|
33
|
+
super();
|
|
34
|
+
this.column = column;
|
|
35
|
+
}
|
|
36
|
+
insertStrategy(value) {
|
|
37
|
+
throw new Error('Method not implemented.');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
exports.PgAggregatedColumnType = PgAggregatedColumnType;
|
|
41
|
+
class PgCount extends PgAggregatedColumnType {
|
|
42
|
+
constructor(column) {
|
|
43
|
+
super(column);
|
|
44
|
+
}
|
|
45
|
+
getDbName() {
|
|
46
|
+
const tableName = this.column ? `${this.column.getParentName()}.` : '*';
|
|
47
|
+
const columnName = this.column ? ecranate_1.ecranate(this.column.getColumnName()) : '';
|
|
48
|
+
return `COUNT(${tableName}${columnName})`;
|
|
49
|
+
}
|
|
50
|
+
selectStrategy(value) {
|
|
51
|
+
return value ? parseInt(value, 10) : undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
exports.PgCount = PgCount;
|
|
55
|
+
const count = (column) => new AggregatedColumn(column ? column.getParent() : undefined, 'count', new PgCount(column), column);
|
|
56
|
+
exports.count = count;
|
package/tables/inferTypes.d.ts
CHANGED
|
@@ -25,7 +25,7 @@ export declare type ExtractUpdateModel<TTable> = {
|
|
|
25
25
|
} & {
|
|
26
26
|
[Key in ExtractOptionalFieldNames<TTable>]?: ExtractCodeType<TTable[Key]> | UpdateCustomExpr<TTable[Key]>;
|
|
27
27
|
};
|
|
28
|
-
export declare type ExtractCodeType<T extends AbstractColumn<ColumnType<any>, boolean, boolean>> = T extends AbstractColumn<ColumnType<infer TCodeType>, infer TNullable, infer TAutoIncrement> ? TCodeType : never;
|
|
28
|
+
export declare type ExtractCodeType<T extends AbstractColumn<ColumnType<any>, boolean, boolean>> = T extends AbstractColumn<ColumnType<infer TCodeType>, infer TNullable, infer TAutoIncrement, any> ? TCodeType : never;
|
|
29
29
|
export declare type ExtractTypeEnum<T extends Type<any>> = T extends Type<infer TEnum> ? TEnum : never;
|
|
30
30
|
export declare type Indexing = IndexedColumn<ColumnType, boolean, boolean> | TableIndex;
|
|
31
31
|
export declare type AnyColumn = Column<ColumnType, boolean, boolean> | IndexedColumn<ColumnType, boolean, boolean>;
|
package/test.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/test.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
const dbConnector_1 = require("./db/dbConnector");
|
|
4
|
+
const usersTable_1 = require("./docs/tables/usersTable");
|
|
5
|
+
const consoleLogger_1 = require("./logger/consoleLogger");
|
|
6
|
+
const serializer_1 = require("./serializer/serializer");
|
|
7
|
+
(async () => {
|
|
8
|
+
try {
|
|
9
|
+
const db = await new dbConnector_1.default()
|
|
10
|
+
.connectionString('postgresql://postgres@127.0.0.1/migrator')
|
|
11
|
+
.connect();
|
|
12
|
+
const usersTable = new usersTable_1.default(db);
|
|
13
|
+
db.useLogger(new consoleLogger_1.default());
|
|
14
|
+
const ser = new serializer_1.default();
|
|
15
|
+
const res = ser.generate([usersTable], []);
|
|
16
|
+
console.log(JSON.stringify(res, null, 2));
|
|
17
|
+
// const f = {
|
|
18
|
+
// id: count(usersTable.id),
|
|
19
|
+
// };
|
|
20
|
+
// type d = ExtractModel<typeof f>;
|
|
21
|
+
// const res = await usersTable.select({
|
|
22
|
+
// piska: count(),
|
|
23
|
+
// mongodibil: count(usersTable.phone),
|
|
24
|
+
// })
|
|
25
|
+
// .where({
|
|
26
|
+
// piska: eq(),
|
|
27
|
+
// mongodibil: eq(usersTable.phone),
|
|
28
|
+
// }).leftJoin(UsersTable, (table) => table.id, (table) => table.id)
|
|
29
|
+
// .leftJoin(UsersTable, UsersTable, (table) => table.id, (table) => table.id)
|
|
30
|
+
// .groupBy((table, join1, join2, join3) => [table.id, join1.id, join1.phone])
|
|
31
|
+
// .orderBy((table, join1, join2, join3) => [{table.id}, join1.id, join1.phone])
|
|
32
|
+
// .execute();
|
|
33
|
+
// const res = await usersTable.select()
|
|
34
|
+
// .groupBy((table, join1, join2, join3) => [table.id, join1.id, join1.phone])
|
|
35
|
+
// .leftJoin(UsersTable, (table) => table.id, (table) => table.id)
|
|
36
|
+
// .leftJoin(UsersTable, UsersTable, (table) => table.id, (table) => table.id)
|
|
37
|
+
// .leftJoin(UsersTable, UsersTable, (table) => table.id, (table) => table.id)
|
|
38
|
+
// // .groupBy({
|
|
39
|
+
// // usersTable: usersTable.id,
|
|
40
|
+
// // firstJoin: [usersTable.id],
|
|
41
|
+
// // secondJoin: usersTable.id,
|
|
42
|
+
// // thirdJoin: usersTable.id,
|
|
43
|
+
// // })
|
|
44
|
+
// .execute();
|
|
45
|
+
// console.log(res);
|
|
46
|
+
}
|
|
47
|
+
catch (e) {
|
|
48
|
+
console.log(e);
|
|
49
|
+
}
|
|
50
|
+
})();
|