drizzle-orm 0.10.7 → 0.10.10

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.
@@ -40,7 +40,7 @@ class InsertTRB extends abstractRequestBuilder_1.default {
40
40
  throw new builderError_1.default(builderError_1.BuilderType.INSERT, this._table.tableName(), this._columns, e);
41
41
  }
42
42
  if (this._logger) {
43
- this._logger.info(`Inserting to ${this._table.tableName()} using query:\n ${query}`);
43
+ this._logger.info(`Inserting to ${this._table.tableName()} using query:\n ${query}\n${values}`);
44
44
  }
45
45
  const result = await this._session.execute(query, values);
46
46
  return responseMapper_1.default.map(this._mappedServiceToDb, result);
@@ -6,7 +6,7 @@ export default class UsersTable extends AbstractTable<UsersTable> {
6
6
  phone: import("../../columns/column").Column<import("../..").PgVarChar, true, false, this>;
7
7
  media: import("../../columns/column").Column<import("../..").PgJsonb<string[]>, true, false, this>;
8
8
  decimalField: import("../../columns/column").Column<import("../..").PgBigDecimal, false, false, this>;
9
- bigIntField: import("../../columns/column").Column<import("../..").PgBigInt, true, true, this>;
9
+ bigIntField: import("../../columns/column").Column<import("../..").PgBigInt, true, false, this>;
10
10
  role: import("../../columns/column").Column<import("../../columns/types/pgEnum").default<"foo" | "bar" | "baz">, false, false, this>;
11
11
  createdAt: import("../../columns/column").Column<import("../..").PgTimestamp, false, false, this>;
12
12
  updatedAt: import("../../columns/column").Column<import("../..").PgTimestamp, true, false, this>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drizzle-orm",
3
- "version": "0.10.7",
3
+ "version": "0.10.10",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -42,7 +42,7 @@ class MigrationSerializer {
42
42
  // default: value.getDefaultValue() === null ? undefined : value.getDefaultValue(),
43
43
  notNull: !value.isNullableFlag,
44
44
  };
45
- if (value.getDefaultValue !== undefined && value.getDefaultValue() !== null) {
45
+ if (value.getDefaultValue() !== undefined && value.getDefaultValue() !== null) {
46
46
  columnToReturn[value.getColumnName()].default = value.getDefaultValue();
47
47
  }
48
48
  if (value.uniqueKeyName) {
@@ -54,8 +54,8 @@ export default abstract class AbstractTable<TTable extends AbstractTable<TTable>
54
54
  protected bigSerial(name: string, maxBytes: 'max_bytes_64'): Column<PgBigSerial64, true, true, this>;
55
55
  protected timestamp(name: string): Column<PgTimestamp, true, false, this>;
56
56
  protected timestamptz(name: string): Column<PgTimestamptz, true, false, this>;
57
- protected bigint(name: string, maxBytes: 'max_bytes_53'): Column<PgBigInt53, true, true, this>;
58
- protected bigint(name: string, maxBytes: 'max_bytes_64'): Column<PgBigInt64, true, true, this>;
57
+ protected bigint(name: string, maxBytes: 'max_bytes_53'): Column<PgBigInt53, true, false, this>;
58
+ protected bigint(name: string, maxBytes: 'max_bytes_64'): Column<PgBigInt64, true, false, this>;
59
59
  protected type<ETtype extends string>(typeEnum: Enum<ETtype>, name: string): Column<PgEnum<ExtractEnumValues<Enum<ETtype>>>, true, false, this>;
60
60
  protected decimal(name: string, params?: {
61
61
  precision?: number;
@@ -2,6 +2,6 @@ import AbstractTable from './abstractTable';
2
2
  export default class MigrationsTable extends AbstractTable<MigrationsTable> {
3
3
  id: import("..").Column<import("../columns/types/pgSerial").default, true, true, this>;
4
4
  hash: import("..").Column<import("..").PgText, false, false, this>;
5
- createdAt: import("..").Column<import("..").PgBigInt, true, true, this>;
5
+ createdAt: import("..").Column<import("..").PgBigInt, true, false, this>;
6
6
  tableName(): string;
7
7
  }
package/README.md DELETED
@@ -1,439 +0,0 @@
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
- ```
@@ -1,14 +0,0 @@
1
- import AbstractTable from '../../tables/abstractTable';
2
- interface CityMeta {
3
- population: number;
4
- connection: string;
5
- }
6
- export default class CitiesTable extends AbstractTable<CitiesTable> {
7
- id: import("../..").Column<import("../../columns/types/pgSerial").default, true, true, this>;
8
- foundationDate: import("../..").Column<import("../..").PgTimestamp, false, false, this>;
9
- location: import("../..").Column<import("../..").PgVarChar, true, false, this>;
10
- userId: import("../..").Column<import("../..").PgInteger, true, false, this>;
11
- metadata: import("../..").Column<import("../..").PgJsonb<CityMeta>, true, false, this>;
12
- tableName(): string;
13
- }
14
- export {};
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const abstractTable_1 = require("../../tables/abstractTable");
4
- class CitiesTable extends abstractTable_1.default {
5
- constructor() {
6
- super(...arguments);
7
- this.id = this.serial('id').primaryKey();
8
- this.foundationDate = this.timestamp('name').notNull();
9
- this.location = this.varchar('page', { size: 256 });
10
- this.userId = this.int('user_id').foreignKey(CitiesTable, (table) => table.id, { onUpdate: 'CASCADE' });
11
- this.metadata = this.jsonb('metadata');
12
- }
13
- tableName() {
14
- return 'cities';
15
- }
16
- }
17
- exports.default = CitiesTable;
@@ -1,7 +0,0 @@
1
- import AbstractTable from '../../tables/abstractTable';
2
- export default class UserGroupsTable extends AbstractTable<UserGroupsTable> {
3
- id: import("../..").Column<import("../../columns/types/pgSerial").default, true, true, this>;
4
- name: import("../..").Column<import("../..").PgVarChar, true, false, this>;
5
- description: import("../..").Column<import("../..").PgVarChar, true, false, this>;
6
- tableName(): string;
7
- }
@@ -1,15 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const abstractTable_1 = require("../../tables/abstractTable");
4
- class UserGroupsTable extends abstractTable_1.default {
5
- constructor() {
6
- super(...arguments);
7
- this.id = this.serial('id').primaryKey();
8
- this.name = this.varchar('name');
9
- this.description = this.varchar('description');
10
- }
11
- tableName() {
12
- return 'user_groups';
13
- }
14
- }
15
- exports.default = UserGroupsTable;
@@ -1,16 +0,0 @@
1
- import AbstractTable from '../../tables/abstractTable';
2
- export declare const rolesEnum: import("../../types/type").default<"user" | "guest" | "admin">;
3
- export default class UsersTable extends AbstractTable<UsersTable> {
4
- id: import("../..").Column<import("../../columns/types/pgSerial").default, true, true, this>;
5
- fullName: import("../..").Column<import("../..").PgText, true, false, this>;
6
- phone: import("../..").Column<import("../..").PgVarChar, true, false, this>;
7
- media: import("../..").Column<import("../..").PgJsonb<string[]>, true, false, this>;
8
- decimalField: import("../..").Column<import("../..").PgBigDecimal, false, false, this>;
9
- bigIntField: import("../..").Column<import("../..").PgBigInt, true, true, this>;
10
- createdAt: import("../..").Column<import("../..").PgTimestamp, false, false, this>;
11
- createdAtWithTimezone: import("../..").Column<import("../../columns/types/pgTimestamptz").default, true, false, this>;
12
- isArchived: import("../..").Column<import("../..").PgBoolean, true, false, this>;
13
- phoneFullNameIndex: import("../../indexes/tableIndex").default;
14
- phoneIndex: import("../../indexes/tableIndex").default;
15
- tableName(): string;
16
- }
@@ -1,31 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.rolesEnum = void 0;
4
- /* eslint-disable max-classes-per-file */
5
- // import { Defaults } from '../../columns/column';
6
- const abstractTable_1 = require("../../tables/abstractTable");
7
- const type_1 = require("../../types/type");
8
- // import { rolesEnum } from '../types/rolesType';
9
- exports.rolesEnum = type_1.createEnum({ alias: 'test-enum', values: ['user', 'guest', 'admin'] });
10
- class UsersTable extends abstractTable_1.default {
11
- constructor() {
12
- super(...arguments);
13
- this.id = this.serial('id').primaryKey();
14
- this.fullName = this.text('full_name');
15
- this.phone = this.varchar('phone', { size: 256 });
16
- this.media = this.jsonb('media');
17
- this.decimalField = this.decimal('test', { precision: 100, scale: 2 }).notNull();
18
- this.bigIntField = this.bigint('test1', 'max_bytes_53');
19
- // public role = this.type(rolesEnum, 'name_in_table', { notNull: true });
20
- this.createdAt = this.timestamp('created_at').notNull();
21
- this.createdAtWithTimezone = this.timestamptz('created_at_time_zone');
22
- // public updatedAt = this.timestamp('updated_at').defaultValue(Defaults.CURRENT_TIMESTAMP);
23
- this.isArchived = this.bool('is_archived').defaultValue(false);
24
- this.phoneFullNameIndex = this.index([this.phone, this.fullName]);
25
- this.phoneIndex = this.uniqueIndex(this.phone);
26
- }
27
- tableName() {
28
- return 'users';
29
- }
30
- }
31
- exports.default = UsersTable;
@@ -1,7 +0,0 @@
1
- import AbstractTable from '../../tables/abstractTable';
2
- export default class UsersToUserGroupsTable extends AbstractTable<UsersToUserGroupsTable> {
3
- groupId: import("../..").Column<import("../..").PgInteger, true, false, this>;
4
- userId: import("../..").Column<import("../..").PgInteger, true, false, this>;
5
- manyToManyIndex: import("../../indexes/tableIndex").default;
6
- tableName(): string;
7
- }
@@ -1,17 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const abstractTable_1 = require("../../tables/abstractTable");
4
- const userGroupsTable_1 = require("./userGroupsTable");
5
- const usersTable_1 = require("./usersTable");
6
- class UsersToUserGroupsTable extends abstractTable_1.default {
7
- constructor() {
8
- super(...arguments);
9
- this.groupId = this.int('city_id').foreignKey(userGroupsTable_1.default, (table) => table.id, { onDelete: 'CASCADE' });
10
- this.userId = this.int('user_id').foreignKey(usersTable_1.default, (table) => table.id, { onDelete: 'CASCADE' });
11
- this.manyToManyIndex = this.index([this.groupId, this.userId]);
12
- }
13
- tableName() {
14
- return 'users_to_user_groups';
15
- }
16
- }
17
- exports.default = UsersToUserGroupsTable;
@@ -1 +0,0 @@
1
- export declare const rolesEnum: import("../../types/type").default<"foo" | "bar" | "baz">;
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.rolesEnum = void 0;
4
- const type_1 = require("../../types/type");
5
- // eslint-disable-next-line import/prefer-default-export
6
- exports.rolesEnum = type_1.createEnum({ alias: 'test-enum', values: ['foo', 'bar', 'baz'] });
package/test.d.ts DELETED
@@ -1 +0,0 @@
1
- export {};
package/test.js DELETED
@@ -1,261 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const _1 = require(".");
4
- const citiesTable_1 = require("./docs/tables/citiesTable");
5
- const usersTable_1 = require("./docs/tables/usersTable");
6
- const consoleLogger_1 = require("./logger/consoleLogger");
7
- // import { Pool } from 'pg';
8
- // import { DB } from '.';
9
- // import { DB, DbConnector } from '.';
10
- // import Enum from './types/type';
11
- const fromTypeFile = (filepath) => {
12
- // const db = new DB(new Pool());
13
- const importedEnum = require(filepath);
14
- const res = [];
15
- // eslint-disable-next-line no-restricted-syntax
16
- for (const type of Object.keys(importedEnum)) {
17
- res.push(importedEnum[type]);
18
- }
19
- return res;
20
- };
21
- (async () => {
22
- try {
23
- const db = await new _1.DbConnector()
24
- .connectionString('postgresql://postgres@127.0.0.1/drizzle-docs')
25
- .connect();
26
- db.useLogger(new consoleLogger_1.default());
27
- const table = new usersTable_1.default(db);
28
- const citiesTable = new citiesTable_1.default(db);
29
- // const res = await table.insert({
30
- // decimalField: 12.4,
31
- // createdAt: new Date(),
32
- // }).all();
33
- // console.log(res);
34
- const res1 = await citiesTable.select().leftJoin(usersTable_1.default, (cities) => cities.userId, (users) => users.id).execute();
35
- // const res: QueryResult<any> = await db.session().execute('SELECT * FROM users');
36
- // eslint-disable-next-line array-callback-return
37
- res1.map((city, user) => {
38
- console.log(city);
39
- console.log(user.decimalField);
40
- });
41
- // const res = await db.session().execute('SELECT * FROM users WHERE user.id = $1', [1]);
42
- // await table.update()
43
- // .where({
44
- // id: eq(1),
45
- // })
46
- // .set({
47
- // phone: 'hello'
48
- // })
49
- // .all();
50
- // await table.select()
51
- // .where({
52
- // and: {
53
- // id: {
54
- // eq: 1,
55
- // },
56
- // phone: {
57
- // notEq: 'hello',
58
- // },
59
- // },
60
- // })
61
- // .all();
62
- // await table.select()
63
- // .where({
64
- // and: {
65
- // id: eq(1),
66
- // phone: notEq('hello'),
67
- // },
68
- // })
69
- // .all();
70
- // await table.select()
71
- // .where(and([
72
- // eq(table.id, 1),
73
- // notEq(table.phone, 'hello'),
74
- // ]))
75
- // .all();
76
- // await table.insertMany([{
77
- // decimalField: 12.4,
78
- // createdAt: new Date(),
79
- // role: 'foo',
80
- // },
81
- // {
82
- // decimalField: 13.4,
83
- // createdAt: new Date(),
84
- // role: 'foo',
85
- // }]).all();
86
- // const d = await table.update().where(and([
87
- // or([
88
- // notEq(table.id, 1),
89
- // eq(table.bigIntField, 1)]),
90
- // or([notEq(table.id, 2),
91
- // eq(table.bigIntField, 1),
92
- // and([notEq(table.id, 1),
93
- // eq(table.isArchived, true),
94
- // ]),
95
- // ])])).set({
96
- // // phone: 'updated',
97
- // bigIntField: 1,
98
- // decimalField: 1.2,
99
- // }).all();
100
- // console.log(d);
101
- // await table.delete().where(eq(table.id, 4)).all();
102
- // const cities = new CitiesTable(db);
103
- // const d = new UsersToUserGroupsTable(db);
104
- // SELECT * FROM users WHERE id = $1 and name = $2
105
- // const res = notEq(table.id, 1).toQuery();
106
- // const res1 = and([notEq(table.id, 1), like(table.phone, 'phone')]).toQuery();
107
- // const res2 = and([
108
- // or([
109
- // notEq(table.id, 1),
110
- // like(table.phone, 'phone')]),
111
- // or([notEq(table.id, 2),
112
- // like(table.phone, 'phone2'),
113
- // and([notEq(table.id, 1),
114
- // eq(table.isArchived, true),
115
- // ]),
116
- // ]),
117
- // ]).toQuery();
118
- // const res3 = and([notEq(table.id, 2),
119
- // like(table.phone, 'phone2'),
120
- // or([
121
- // notEq(table.id, 1),
122
- // like(table.phone, 'phone')]),
123
- // ]).toQuery();
124
- // // console.log(res);
125
- // console.log(res2);
126
- // console.log(res3);
127
- // const serializer = new MigrationSerializer();
128
- // const res = serializer.generate([table], []);
129
- // console.log(JSON.stringify(res, null, 2));
130
- // fs.writeFileSync('introspected.json', JSON.stringify(res, null, 2), 'utf8');
131
- // const ser = new MigrationSerializer();
132
- // const d = db.create(UsersTable) as unknown as AbstractTable<any>;
133
- // const f = ser.generate([d], []);
134
- // console.log(JSON.stringify(f, null, 2));
135
- // await drizzle.migrator(db).smigrate('drizzle.config.yml');
136
- // await drizzle.migrator(db).migrate({ migrationFolder: 'drizzle' });
137
- // const typesFileNames = fs.readdirSync('/Users/andrewsherman/IdeaProjects/datalayer-orm/src/examples/types');
138
- // typesFileNames.forEach((filename) => {
139
- // const types = fromTypeFile(`./examples/types/${filename.split('.')[0]}`);
140
- // const typeValues = types[0].values;
141
- // console.log(typeValues);
142
- // // console.log(Object.values(typeValues));
143
- // });
144
- // const usersTable = new UsersTable(db);
145
- // const citiesTable = new CitiesTable(db);
146
- // await db.session().execute(Create.table(usersTable).build());
147
- // await db.session().execute(Create.table(citiesTable).build());
148
- // await usersTable.select().where(greater(usersTable.createdAtWithTimezone, new Date())).execute();
149
- // const db = await new DbConnector()
150
- // .connectionString('postgresql://postgres@127.0.0.1/drizzle')
151
- // .connect();
152
- // const db = await new DbConnector()
153
- // .connectionString('postgresql://postgres@127.0.0.1/migrator')
154
- // .connect();
155
- // const usersTable: UsersTable = new UsersTable(db);
156
- // const knexInstance = knex.knex({
157
- // client: 'pg',
158
- // connection: 'postgresql://postgres@127.0.0.1/migrator',
159
- // });
160
- // const userTableForKnex: UsersTable = new UsersTable(knexDb);
161
- // const users = await userTableForKnex.select().all();
162
- // console.log(users[0]);
163
- // const arr: AbstractColumn<ColumnType<any>, boolean, boolean>[] = [usersTable.id, usersTable.phone];
164
- // const objectRes: {[name: string]: AbstractColumn<ColumnType, boolean, boolean>} = arr.reduce(
165
- // (obj, item, index) => Object.assign(obj, { [Object.getOwnPropertyNames(item)[index]]: item }), {},
166
- // );
167
- // type f = ExtractModel<typeof objectRes1>;
168
- // type d1 = ExtractModel<UsersTable>;
169
- // const dff = usersTable.phone;
170
- // const f = usersTable.select()
171
- // .partial({
172
- // // usersCount: usersTable.id,
173
- // sumNumber: usersTable.phone,
174
- // });
175
- // const f = usersTable.select({
176
- // usersCount: usersTable.id,
177
- // sumNumber: usersTable.phone,
178
- // })
179
- // .limit(2)
180
- // .offset(2)
181
- // .all();
182
- // Done: provide partial interface + partial objects to each join inside and use in each execute mapper
183
- // Add possibility tp join on another table -> https://www.postgresqltutorial.com/postgresql-inner-join/
184
- // ________________________
185
- // const f1 = await usersTable.select({
186
- // usersCount: usersTable.id,
187
- // sumNumber: usersTable.phone,
188
- // }).leftJoin(CitiesTable,
189
- // (user) => user.id,
190
- // (city) => city.id)
191
- // .leftJoin(CitiesTable, CitiesTable,
192
- // (user) => user.id,
193
- // (city) => city.userId)
194
- // .leftJoin(CitiesTable, CitiesTable,
195
- // (user) => user.id,
196
- // (city) => city.userId)
197
- // .execute();
198
- // const res = f1.map((user, city, city1) => ({ user, city, city1 }));
199
- // console.log(res);
200
- // type d = ExtractModel<{
201
- // usersCount: Column<PgSerial, true, true, UsersTable>;
202
- // sumNumber: Column<PgVarChar, true, false, UsersTable>;
203
- // }>;
204
- // type f = Check<UserGroupsTable, UsersTable, CitiesTable>;
205
- // f1.map((user, city, city1, city2, city3, city4) => {
206
- // });
207
- // const f = usersTable.select().testTypes();
208
- // const rg = {
209
- // // usersCount: usersTable.id,
210
- // sumNumber: usersTable.phone,
211
- // };
212
- // const f = await usersTable.select({
213
- // usersCount: usersTable.id,
214
- // sumNumber: usersTable.phone,
215
- // }).all();
216
- // console.log(typeof f);
217
- // const objectRes1 = {
218
- // usersCount: usersTable.id,
219
- // sumNumber: usersTable.phone,
220
- // };
221
- // type fd = ExtractModel<typeof f>;
222
- // const g = await usersTable.select().execute();
223
- // type fd = ExtractModel<typeof g>;
224
- // if (res.isLeft()) {
225
- // console.log(res.value.reason);
226
- // } else {
227
- // console.log(res.value);
228
- // }
229
- // const userTable = new UsersTable(db);
230
- // const citiesTable = new CitiesTable(db);
231
- // const uni = new UniJoin(userTable).innerJoin(
232
- // UsersTable,
233
- // (table) => table.id,
234
- // (t) => t.id,
235
- // );
236
- // Inner.join1(
237
- // { table: CitiesTable, column: ((table) => table.id), on: ((table) => table.userId1) },
238
- // );
239
- // const res = await userTable.select().leftJoin(
240
- // UsersTable,
241
- // (table) => table.id,
242
- // (t) => t.id,
243
- // ).execute();
244
- // const d = await userTable
245
- // .insert({ phone: 'phone1', createdAt: new Date(), role: 'foo' }).all();
246
- // const all = await userTable.select().all();
247
- // console.log(all[1]?.role);
248
- // console.log(typeof d[0]?.role);
249
- // const users = await userTable.update()
250
- // .where(eq(userTable.id, 1))
251
- // .set({
252
- // phone: 'dsdf',
253
- // createdAt: new Date(),
254
- // })
255
- // .all();
256
- // console.log(users);
257
- }
258
- catch (e) {
259
- console.log(e);
260
- }
261
- })();