drizzle-orm 0.9.13 → 0.9.17

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.
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PgBigSerial64 = void 0;
4
+ /* eslint-disable max-classes-per-file */
5
+ const columnType_1 = require("./columnType");
6
+ class PgBigSerial53 extends columnType_1.default {
7
+ constructor() {
8
+ super();
9
+ this.getDbName = () => this.dbName;
10
+ this.insertStrategy = (value) => `${value}`;
11
+ this.dbName = 'BIGSERIAL';
12
+ }
13
+ selectStrategy(value) {
14
+ return value ? parseInt(value, 10) : undefined;
15
+ }
16
+ }
17
+ exports.default = PgBigSerial53;
18
+ class PgBigSerial64 extends columnType_1.default {
19
+ constructor() {
20
+ super();
21
+ this.getDbName = () => this.dbName;
22
+ this.insertStrategy = (value) => `${value}`;
23
+ this.dbName = 'BIGSERIAL';
24
+ }
25
+ selectStrategy(value) {
26
+ return value ? BigInt(value) : undefined;
27
+ }
28
+ }
29
+ exports.PgBigSerial64 = PgBigSerial64;
@@ -0,0 +1,8 @@
1
+ import ColumnType from './columnType';
2
+ export default class PgSerial extends ColumnType<number> {
3
+ dbName: string;
4
+ constructor();
5
+ getDbName: () => string;
6
+ insertStrategy: (value: number) => string;
7
+ selectStrategy(value: string): number | undefined;
8
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const columnType_1 = require("./columnType");
4
+ class PgSerial extends columnType_1.default {
5
+ constructor() {
6
+ super();
7
+ this.getDbName = () => this.dbName;
8
+ this.insertStrategy = (value) => `${value}`;
9
+ this.dbName = 'SERIAL';
10
+ }
11
+ selectStrategy(value) {
12
+ return value ? parseInt(value, 10) : undefined;
13
+ }
14
+ }
15
+ exports.default = PgSerial;
@@ -0,0 +1,8 @@
1
+ import ColumnType from './columnType';
2
+ export default class PgTimestamptz extends ColumnType<Date> {
3
+ dbName: string;
4
+ constructor();
5
+ getDbName: () => string;
6
+ insertStrategy: (value: Date) => string;
7
+ selectStrategy(value: any): Date;
8
+ }
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const columnType_1 = require("./columnType");
4
+ class PgTimestamptz extends columnType_1.default {
5
+ constructor() {
6
+ super();
7
+ this.getDbName = () => this.dbName;
8
+ this.insertStrategy = (value) => `'${value.toISOString()}'`;
9
+ this.dbName = 'timestamp with time zone';
10
+ }
11
+ selectStrategy(value) {
12
+ return value;
13
+ }
14
+ }
15
+ exports.default = PgTimestamptz;
package/db/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { default as DB } from './db';
2
2
  export { default as DbConnector } from './dbConnector';
3
3
  export { default as DBStringConnector } from './dbStringConnector';
4
+ export { ISession } from './session';
package/db/index.js CHANGED
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DBStringConnector = exports.DbConnector = exports.DB = void 0;
3
+ exports.ISession = exports.DBStringConnector = exports.DbConnector = exports.DB = void 0;
4
4
  var db_1 = require("./db");
5
5
  Object.defineProperty(exports, "DB", { enumerable: true, get: function () { return db_1.default; } });
6
6
  var dbConnector_1 = require("./dbConnector");
7
7
  Object.defineProperty(exports, "DbConnector", { enumerable: true, get: function () { return dbConnector_1.default; } });
8
8
  var dbStringConnector_1 = require("./dbStringConnector");
9
9
  Object.defineProperty(exports, "DBStringConnector", { enumerable: true, get: function () { return dbStringConnector_1.default; } });
10
+ var session_1 = require("./session");
11
+ Object.defineProperty(exports, "ISession", { enumerable: true, get: function () { return session_1.ISession; } });
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ /* eslint-disable max-len */
3
4
  /* eslint-disable @typescript-eslint/no-unused-vars */
4
5
  const __1 = require("../..");
5
6
  const builders_1 = require("../../builders");
@@ -27,7 +27,7 @@ const usersTable_1 = require("../tables/usersTable");
27
27
  const greaterSelect = usersTable.select().where(static_1.greater(usersTable.bigIntField, 3)).all();
28
28
  const lessSelect = usersTable.select().where(static_1.less(usersTable.bigIntField, 3)).all();
29
29
  const greaterEqSelect = usersTable.select().where(static_1.greaterEq(usersTable.bigIntField, 3)).all();
30
- const lessEqSelect = usersTable.select().where(static_1.lessEq(usersTable.bigIntField, 3)).all();
30
+ const lessEqSelect = usersTable.select().where(static_1.lessEq(usersTable.bigIntField, 3));
31
31
  const isNullSelect = usersTable.select().where(static_1.isNull(usersTable.phone)).all();
32
32
  const notEqSelect = usersTable.select().where(static_1.notEq(usersTable.phone, 'hello')).all();
33
33
  // ordered select
@@ -4,7 +4,7 @@ interface CityMeta {
4
4
  connection: string;
5
5
  }
6
6
  export default class CitiesTable extends AbstractTable<CitiesTable> {
7
- id: import("../../columns/column").IndexedColumn<import("../..").PgInteger, true, true>;
7
+ id: import("../..").Column<import("../../columns/types/pgSerial").default, true, true>;
8
8
  foundationDate: import("../..").Column<import("../..").PgTimestamp, false, false>;
9
9
  location: import("../..").Column<import("../..").PgVarChar, true, false>;
10
10
  userId: import("../..").Column<import("../..").PgInteger, true, false>;
@@ -5,8 +5,8 @@ const usersTable_1 = require("./usersTable");
5
5
  class CitiesTable extends abstractTable_1.default {
6
6
  constructor() {
7
7
  super(...arguments);
8
- this.id = this.int('id').autoIncrement().primaryKey();
9
- this.foundationDate = this.timestamp('name', { notNull: true });
8
+ this.id = this.serial('id').primaryKey();
9
+ this.foundationDate = this.timestamp('name').notNull();
10
10
  this.location = this.varchar('page', { size: 256 });
11
11
  this.userId = this.int('user_id').foreignKey(usersTable_1.default, (table) => table.id, { onUpdate: 'CASCADE' });
12
12
  this.metadata = this.jsonb('metadata');
@@ -1,6 +1,6 @@
1
1
  import AbstractTable from '../../tables/abstractTable';
2
2
  export default class UserGroupsTable extends AbstractTable<UserGroupsTable> {
3
- id: import("../../columns/column").IndexedColumn<import("../..").PgInteger, true, true>;
3
+ id: import("../..").Column<import("../../columns/types/pgSerial").default, true, true>;
4
4
  name: import("../..").Column<import("../..").PgVarChar, true, false>;
5
5
  description: import("../..").Column<import("../..").PgVarChar, true, false>;
6
6
  tableName(): string;
@@ -4,7 +4,7 @@ const abstractTable_1 = require("../../tables/abstractTable");
4
4
  class UserGroupsTable extends abstractTable_1.default {
5
5
  constructor() {
6
6
  super(...arguments);
7
- this.id = this.int('id').autoIncrement().primaryKey();
7
+ this.id = this.serial('id').primaryKey();
8
8
  this.name = this.varchar('name');
9
9
  this.description = this.varchar('description');
10
10
  }
@@ -1,15 +1,16 @@
1
1
  import AbstractTable from '../../tables/abstractTable';
2
2
  export declare const rolesEnum: import("../../types/type").default<"user" | "guest" | "admin">;
3
3
  export default class UsersTable extends AbstractTable<UsersTable> {
4
- id: import("../../columns/column").IndexedColumn<import("../..").PgInteger, true, true>;
5
- fullName: import("../..").Column<import("../..").PgText, true, false>;
6
- phone: import("../..").Column<import("../..").PgVarChar, true, false>;
7
- media: import("../..").Column<import("../..").PgJsonb<string[]>, true, false>;
8
- decimalField: import("../..").Column<import("../..").PgBigDecimal, false, false>;
9
- bigIntField: import("../..").Column<import("../..").PgBigInt, true, false>;
10
- createdAt: import("../..").Column<import("../..").PgTimestamp, false, false>;
11
- updatedAt: import("../..").Column<import("../..").PgTimestamp, true, false>;
12
- isArchived: import("../..").Column<import("../..").PgBoolean, true, false>;
4
+ id: import("../../columns/column").Column<import("../../columns/types/pgSerial").default, true, true>;
5
+ fullName: import("../../columns/column").Column<import("../..").PgText, true, false>;
6
+ phone: import("../../columns/column").Column<import("../..").PgVarChar, true, false>;
7
+ media: import("../../columns/column").Column<import("../..").PgJsonb<string[]>, true, false>;
8
+ decimalField: import("../../columns/column").Column<import("../..").PgBigDecimal, false, false>;
9
+ bigIntField: import("../../columns/column").Column<import("../..").PgBigInt, true, true>;
10
+ createdAt: import("../../columns/column").Column<import("../..").PgTimestamp, false, false>;
11
+ createdAtWithTimezone: import("../../columns/column").Column<import("../../columns/types/pgTimestamptz").default, true, false>;
12
+ updatedAt: import("../../columns/column").Column<import("../..").PgTimestamp, true, false>;
13
+ isArchived: import("../../columns/column").Column<import("../..").PgBoolean, true, false>;
13
14
  phoneFullNameIndex: import("../../indexes/tableIndex").default;
14
15
  phoneIndex: import("../../indexes/tableIndex").default;
15
16
  tableName(): string;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.rolesEnum = void 0;
4
4
  /* eslint-disable max-classes-per-file */
5
+ const column_1 = require("../../columns/column");
5
6
  const abstractTable_1 = require("../../tables/abstractTable");
6
7
  const type_1 = require("../../types/type");
7
8
  // import { rolesEnum } from '../types/rolesType';
@@ -9,15 +10,16 @@ exports.rolesEnum = type_1.createEnum({ alias: 'test-enum', values: ['user', 'gu
9
10
  class UsersTable extends abstractTable_1.default {
10
11
  constructor() {
11
12
  super(...arguments);
12
- this.id = this.int('id').autoIncrement().primaryKey();
13
+ this.id = this.serial('id').primaryKey();
13
14
  this.fullName = this.text('full_name');
14
15
  this.phone = this.varchar('phone', { size: 256 });
15
16
  this.media = this.jsonb('media');
16
- this.decimalField = this.decimal('test', { notNull: true, precision: 100, scale: 2 });
17
- this.bigIntField = this.bigint('test1');
17
+ this.decimalField = this.decimal('test', { precision: 100, scale: 2 }).notNull();
18
+ this.bigIntField = this.bigint('test1', 'max_bytes_53');
18
19
  // public role = this.type(rolesEnum, 'name_in_table', { notNull: true });
19
- this.createdAt = this.timestamp('created_at', { notNull: true });
20
- this.updatedAt = this.timestamp('updated_at');
20
+ this.createdAt = this.timestamp('created_at').notNull();
21
+ this.createdAtWithTimezone = this.timestamptz('created_at_time_zone');
22
+ this.updatedAt = this.timestamp('updated_at').defaultValue(column_1.Defaults.CURRENT_TIMESTAMP);
21
23
  this.isArchived = this.bool('is_archived').defaultValue(false);
22
24
  this.phoneFullNameIndex = this.index([this.phone, this.fullName]);
23
25
  this.phoneIndex = this.uniqueIndex(this.phone);
package/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { ClientConfig } from 'pg';
2
2
  import { DB } from './db';
3
+ import Migrator from './migrator/migrator';
3
4
  export * from './db';
4
5
  export * from './builders';
5
6
  export * from './columns';
6
7
  export * from './tables';
7
8
  export declare const drizzle: {
8
9
  connect(config: ClientConfig): Promise<DB>;
10
+ migrator(db: DB): Migrator;
9
11
  };
package/index.js CHANGED
@@ -12,6 +12,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.drizzle = void 0;
14
14
  const db_1 = require("./db");
15
+ const migrator_1 = require("./migrator/migrator");
15
16
  __exportStar(require("./db"), exports);
16
17
  __exportStar(require("./builders"), exports);
17
18
  __exportStar(require("./columns"), exports);
@@ -21,4 +22,7 @@ exports.drizzle = {
21
22
  const dbConnector = new db_1.DbConnector().params(config);
22
23
  return dbConnector.connect();
23
24
  },
25
+ migrator(db) {
26
+ return new migrator_1.default(db);
27
+ },
24
28
  };
@@ -1,16 +1,11 @@
1
1
  import Db from '../db/db';
2
- export declare class MigrationSession {
3
- private finalQuery;
4
- execute: (query: string) => void;
5
- getQuery: () => string;
6
- }
2
+ export declare type InCodeConfig = {
3
+ migrationFolder: string;
4
+ };
7
5
  export default class Migrator {
8
- private _db;
9
- private migrationsPerVersion;
10
- private session;
6
+ private db;
11
7
  constructor(db: Db);
12
- chain: (tag: number, migration: (dbSession: MigrationSession) => void) => Migrator;
13
- getResultScript: () => string[];
14
- execute: () => Promise<boolean>;
8
+ migrate(configPath: string): Promise<void>;
9
+ migrate(config: InCodeConfig): Promise<void>;
15
10
  private generateHash;
16
11
  }
@@ -1,87 +1,76 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MigrationSession = void 0;
3
+ /* eslint-disable no-restricted-syntax */
4
4
  /* eslint-disable import/export */
5
5
  /* eslint-disable max-classes-per-file */
6
- const create_1 = require("../builders/lowLvlBuilders/create");
6
+ const fs = require("fs");
7
+ const builders_1 = require("../builders");
7
8
  const transaction_1 = require("../builders/transaction/transaction");
8
- const migrationsTable_1 = require("../tables/migrationsTable");
9
- class MigrationSession {
10
- constructor() {
11
- this.finalQuery = '';
12
- this.execute = (query) => {
13
- this.finalQuery += query;
14
- this.finalQuery += '\n';
15
- };
16
- this.getQuery = () => this.finalQuery;
17
- }
18
- }
19
- exports.MigrationSession = MigrationSession;
9
+ const tables_1 = require("../tables");
20
10
  class Migrator {
21
11
  constructor(db) {
22
- this.migrationsPerVersion = new Map();
23
- this.chain = (tag, migration) => {
24
- const migrationSession = new MigrationSession();
25
- migration(migrationSession);
26
- this.migrationsPerVersion.set(+tag, migrationSession.getQuery());
27
- return this;
28
- };
29
- this.getResultScript = () => {
30
- const values = [];
31
- // eslint-disable-next-line no-restricted-syntax
32
- for (const value of this.migrationsPerVersion.values()) {
33
- values.push(value);
34
- }
35
- return values;
36
- };
37
- this.execute = async () => {
38
- const migrationsTable = new migrationsTable_1.default(this._db);
39
- await this.session.execute(create_1.default.table(migrationsTable).build());
40
- const migrations = await migrationsTable.select().all();
41
- const transaction = new transaction_1.default(this.session);
42
- await transaction.begin();
12
+ this.db = db;
13
+ }
14
+ async migrate(configPath, config) {
15
+ let migrationFolderTo;
16
+ if (configPath) {
17
+ const configAsString = fs.readFileSync(configPath, 'utf8');
18
+ const splitted = configAsString.trim().split('\n');
43
19
  // eslint-disable-next-line no-restricted-syntax
44
- for await (const [key, value] of this.migrationsPerVersion) {
45
- const dbMigrationByTag = migrations.find((it) => it.version === key);
46
- if (dbMigrationByTag) {
47
- // const isHashSameAsInDb =
48
- // Buffer.from(dbMigrationByTag.hash, 'base64').toString('ascii') === value;
49
- // if (!isHashSameAsInDb) {
50
- // throw Error(`Migration script was changed for version ${key}`);
51
- // }
20
+ for (const split of splitted) {
21
+ const entry = split.trim().split(':');
22
+ const key = entry[0];
23
+ const value = entry[1].trim().replace(/['"]+/g, '');
24
+ if (key === 'migrationFolder') {
25
+ // proceed value
26
+ migrationFolderTo = value;
52
27
  }
53
- else {
54
- try {
55
- const logger = this._db.logger();
56
- if (logger) {
57
- logger.info(`Executing migration with tag ${key} with query:\n${value}`);
58
- }
59
- await this._db.session().execute(value);
60
- await migrationsTable
61
- .insert({
62
- version: key,
63
- createdAt: new Date(),
64
- hash: Buffer.from(value).toString('base64'),
65
- }).execute();
66
- }
67
- catch (e) {
68
- await transaction.rollback();
69
- throw new Error(`Migration chain ${key} was not migrated sucessfully.\nMessage: ${e.message}`);
70
- }
28
+ }
29
+ }
30
+ if (config) {
31
+ migrationFolderTo = config.migrationFolder;
32
+ }
33
+ if (!migrationFolderTo) {
34
+ throw Error('no migration folder defined');
35
+ }
36
+ const migrationTable = new tables_1.MigrationsTable(this.db);
37
+ await this.db.session().execute(builders_1.Create.table(migrationTable).build());
38
+ const dbMigrations = await migrationTable.select().all();
39
+ const lastDbMigration = dbMigrations.length > 0
40
+ ? dbMigrations[dbMigrations.length - 1]
41
+ : undefined;
42
+ const files = fs.readdirSync(migrationFolderTo);
43
+ const transaction = new transaction_1.default(this.db.session());
44
+ await transaction.begin();
45
+ try {
46
+ for await (const migrationFolder of files) {
47
+ const migrationFiles = fs.readdirSync(`${migrationFolderTo}/${migrationFolder}`);
48
+ const migrationFile = migrationFiles.filter((file) => file === 'migration.sql')[0];
49
+ const query = fs.readFileSync(`${migrationFolderTo}/${migrationFolder}/${migrationFile}`).toString();
50
+ const folderAsMillis = new Date(migrationFolder).getTime();
51
+ if (!lastDbMigration || lastDbMigration.createdAt < folderAsMillis) {
52
+ await this.db.session().execute(query);
53
+ await migrationTable.insert({
54
+ hash: this.generateHash(query),
55
+ createdAt: folderAsMillis,
56
+ }).execute();
71
57
  }
72
58
  }
73
59
  await transaction.commit();
74
- return true;
75
- };
76
- this._db = db;
77
- this.session = db.session();
60
+ }
61
+ catch (e) {
62
+ if (this.db.logger()) {
63
+ this.db.logger().error(e);
64
+ }
65
+ transaction.rollback();
66
+ }
78
67
  }
79
68
  generateHash(value) {
80
69
  let hash = 0;
81
70
  let i;
82
71
  let chr;
83
72
  if (value.length === 0)
84
- return hash;
73
+ return '';
85
74
  for (i = 0; i < value.length; i += 1) {
86
75
  chr = value.charCodeAt(i);
87
76
  // eslint-disable-next-line no-bitwise
@@ -89,7 +78,7 @@ class Migrator {
89
78
  // eslint-disable-next-line no-bitwise
90
79
  hash |= 0;
91
80
  }
92
- return hash;
81
+ return Buffer.from(value).toString('base64');
93
82
  }
94
83
  }
95
84
  exports.default = Migrator;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drizzle-orm",
3
- "version": "0.9.13",
3
+ "version": "0.9.17",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,5 +1,12 @@
1
+ import { DB } from '../db';
1
2
  import { AbstractTable } from '../tables';
2
3
  import Enum from '../types/type';
4
+ interface EnumsAsObject {
5
+ [name: string]: {
6
+ name: string;
7
+ values: string[];
8
+ };
9
+ }
3
10
  interface ColumnAsObject {
4
11
  [name: string]: {
5
12
  name?: string;
@@ -37,5 +44,10 @@ export default class MigrationSerializer {
37
44
  [key: string]: Enum<any>;
38
45
  };
39
46
  };
47
+ fromDatabase: (db: DB) => Promise<{
48
+ version: string;
49
+ tables: TableAsObject;
50
+ enums: EnumsAsObject;
51
+ }>;
40
52
  }
41
53
  export {};