@proteinjs/db-driver-knex 1.0.13 → 1.0.15

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.
@@ -7,9 +7,7 @@ import { getColumnFactory } from './getColumnFactory';
7
7
  export class KnexSchemaOperations implements SchemaOperations {
8
8
  private logger = new Logger(this.constructor.name);
9
9
 
10
- constructor(
11
- private knexDriver: KnexDriver
12
- ){}
10
+ constructor(private knexDriver: KnexDriver) {}
13
11
 
14
12
  async createTable(table: Table<any>) {
15
13
  let resolve: any;
@@ -18,113 +16,138 @@ export class KnexSchemaOperations implements SchemaOperations {
18
16
  resolve = rs;
19
17
  reject = rj;
20
18
  });
21
-
22
- await this.knexDriver.getKnex().schema.withSchema(this.knexDriver.getDbName()).createTable(table.name, (tableBuilder: knex.TableBuilder) => {
23
- for (const columnPropertyName in table.columns) {
24
- const column = table.columns[columnPropertyName];
25
- this.createColumn(column, table, tableBuilder);
26
- this.logger.info(`[${table.name}] Creating column: ${column.name}`);
27
- }
28
-
29
- tableBuilder.primary(['id']);
30
- this.logger.info(`[${table.name}] Creating primary key: id`);
31
-
32
- if (table.indexes) {
33
- for (const index of table.indexes) {
34
- const columnNames = index.columns.map((columnPropertyName) => table.columns[columnPropertyName as string].name)
35
- tableBuilder.index(columnNames, index.name);
36
- this.logger.info(`[${table.name}] Creating index: ${columnNames}`);
19
+
20
+ await this.knexDriver
21
+ .getKnex()
22
+ .schema.withSchema(this.knexDriver.getDbName())
23
+ .createTable(table.name, (tableBuilder: knex.TableBuilder) => {
24
+ for (const columnPropertyName in table.columns) {
25
+ const column = table.columns[columnPropertyName];
26
+ this.createColumn(column, table, tableBuilder);
27
+ this.logger.info(`[${table.name}] Creating column: ${column.name}`);
37
28
  }
38
- }
39
- }).catch((reason: any) => {
40
- reject(`Failed to create table: ${table.name}. reason: ${reason}`);
41
- }).then(() => {
42
- resolve();
43
- });
44
-
29
+
30
+ tableBuilder.primary(['id']);
31
+ this.logger.info(`[${table.name}] Creating primary key: id`);
32
+
33
+ if (table.indexes) {
34
+ for (const index of table.indexes) {
35
+ const columnNames = index.columns.map(
36
+ (columnPropertyName) => table.columns[columnPropertyName as string].name
37
+ );
38
+ tableBuilder.index(columnNames, index.name);
39
+ this.logger.info(`[${table.name}] Creating index: ${columnNames}`);
40
+ }
41
+ }
42
+ })
43
+ .catch((reason: any) => {
44
+ reject(`Failed to create table: ${table.name}. reason: ${reason}`);
45
+ })
46
+ .then(() => {
47
+ resolve();
48
+ });
49
+
45
50
  return p;
46
51
  }
47
52
 
48
53
  async alterTable(table: Table<any>, tableChanges: TableChanges) {
49
- let resolve: any;
50
- let reject: any;
51
- const p = new Promise<void>((rs, rj) => {
52
- resolve = rs;
53
- reject = rj;
54
- });
55
-
56
- await this.knexDriver.getKnex().schema.withSchema(this.knexDriver.getDbName()).table(table.name, (tableBuilder: knex.TableBuilder) => {
57
- for (const columnPropertyName of tableChanges.columnsToCreate) {
58
- const column = table.columns[columnPropertyName];
59
- this.logger.info(`[${table.name}] Creating column: ${column.name}`);
60
- this.createColumn(column, table, tableBuilder, tableChanges);
61
- }
62
-
63
- for (const column of tableChanges.columnsWithUniqueConstraintsToDrop) {
64
- tableBuilder.dropUnique([column]);
65
- this.logger.info(`[${table.name}.${column}] Dropping unique constraint`);
66
- }
67
-
68
- for (const column of tableChanges.columnsWithForeignKeysToDrop) {
69
- tableBuilder.dropForeign([column]);
70
- this.logger.info(`[${table.name}.${column}] Dropping foreign key`);
71
- }
72
-
73
- for (const index of tableChanges.indexesToDrop) {
74
- tableBuilder.dropIndex(index.columns);
75
- this.logger.info(`[${table.name}] Dropping index: ${JSON.stringify(index)}`);
76
- }
77
-
78
- for (const columnPropertyName of tableChanges.columnsToAlter) {
79
- const column = table.columns[columnPropertyName];
80
- this.logger.info(`[${table.name}.${column.name}] Altering column type to: ${column.constructor.name}`);
81
- this.createColumn(column, table, tableBuilder, tableChanges).alter();
82
- }
83
-
84
- for (const columnPropertyName of tableChanges.columnsToRename) {
85
- const column = table.columns[columnPropertyName];
86
- if (!column.oldName)
87
- continue;
88
-
89
- tableBuilder.renameColumn(column.oldName, column.name);
90
- this.logger.info(`[${table.name}] Renaming column: ${column.oldName} -> ${column.name}`);
91
- }
92
-
93
- for (const index of tableChanges.indexesToCreate) {
94
- tableBuilder.index(index.columns);
95
- this.logger.info(`[${table.name}] Creating index: ${JSON.stringify(index)}`);
96
- }
97
- }).catch((reason: any) => {
98
- reject(`Failed to alter table: ${table.name}. reason: ${reason}`);
99
- }).then(() => {
100
- resolve();
54
+ let resolve: any;
55
+ let reject: any;
56
+ const p = new Promise<void>((rs, rj) => {
57
+ resolve = rs;
58
+ reject = rj;
101
59
  });
102
-
103
- return p;
104
- }
105
60
 
106
- private createColumn(column: Column<any, any>, table: Table<any>, tableBuilder: knex.TableBuilder, tableChanges?: TableChanges) {
61
+ await this.knexDriver
62
+ .getKnex()
63
+ .schema.withSchema(this.knexDriver.getDbName())
64
+ .table(table.name, (tableBuilder: knex.TableBuilder) => {
65
+ for (const columnPropertyName of tableChanges.columnsToCreate) {
66
+ const column = table.columns[columnPropertyName];
67
+ this.logger.info(`[${table.name}] Creating column: ${column.name}`);
68
+ this.createColumn(column, table, tableBuilder, tableChanges);
69
+ }
70
+
71
+ for (const column of tableChanges.columnsWithUniqueConstraintsToDrop) {
72
+ tableBuilder.dropUnique([column]);
73
+ this.logger.info(`[${table.name}.${column}] Dropping unique constraint`);
74
+ }
75
+
76
+ for (const column of tableChanges.columnsWithForeignKeysToDrop) {
77
+ tableBuilder.dropForeign([column]);
78
+ this.logger.info(`[${table.name}.${column}] Dropping foreign key`);
79
+ }
80
+
81
+ for (const index of tableChanges.indexesToDrop) {
82
+ tableBuilder.dropIndex(index.columns);
83
+ this.logger.info(`[${table.name}] Dropping index: ${JSON.stringify(index)}`);
84
+ }
85
+
86
+ for (const columnPropertyName of tableChanges.columnsToAlter) {
87
+ const column = table.columns[columnPropertyName];
88
+ this.logger.info(`[${table.name}.${column.name}] Altering column type to: ${column.constructor.name}`);
89
+ this.createColumn(column, table, tableBuilder, tableChanges).alter();
90
+ }
91
+
92
+ for (const columnPropertyName of tableChanges.columnsToRename) {
93
+ const column = table.columns[columnPropertyName];
94
+ if (!column.oldName) {
95
+ continue;
96
+ }
97
+
98
+ tableBuilder.renameColumn(column.oldName, column.name);
99
+ this.logger.info(`[${table.name}] Renaming column: ${column.oldName} -> ${column.name}`);
100
+ }
101
+
102
+ for (const index of tableChanges.indexesToCreate) {
103
+ tableBuilder.index(index.columns);
104
+ this.logger.info(`[${table.name}] Creating index: ${JSON.stringify(index)}`);
105
+ }
106
+ })
107
+ .catch((reason: any) => {
108
+ reject(`Failed to alter table: ${table.name}. reason: ${reason}`);
109
+ })
110
+ .then(() => {
111
+ resolve();
112
+ });
113
+
114
+ return p;
115
+ }
116
+
117
+ private createColumn(
118
+ column: Column<any, any>,
119
+ table: Table<any>,
120
+ tableBuilder: knex.TableBuilder,
121
+ tableChanges?: TableChanges
122
+ ) {
107
123
  const columnFactory = getColumnFactory(column);
108
124
  const columnBuilder = columnFactory.create(column, tableBuilder);
109
- if (column.options?.unique?.unique && (!tableChanges || tableChanges.columnsWithUniqueConstraintsToCreate.includes(column.name))) {
125
+ if (
126
+ column.options?.unique?.unique &&
127
+ (!tableChanges || tableChanges.columnsWithUniqueConstraintsToCreate.includes(column.name))
128
+ ) {
110
129
  columnBuilder.unique(column.options.unique.indexName);
111
130
  this.logger.info(`[${table.name}.${column.name}] Adding unique constraint`);
112
131
  }
113
-
114
- if (column.options?.references && (!tableChanges || tableChanges.columnsWithForeignKeysToCreate.includes(column.name))) {
132
+
133
+ if (
134
+ column.options?.references &&
135
+ (!tableChanges || tableChanges.columnsWithForeignKeysToCreate.includes(column.name))
136
+ ) {
115
137
  columnBuilder.references('id').inTable(`${this.knexDriver.getDbName()}.${column.options.references.table}`);
116
138
  this.logger.info(`[${table.name}.${column.name}] Adding foreign key -> ${column.options.references.table}.id`);
117
139
  }
118
-
140
+
119
141
  if (typeof column.options?.nullable !== 'undefined') {
120
- if (column.options?.nullable)
142
+ if (column.options?.nullable) {
121
143
  columnBuilder.nullable();
122
- else
144
+ } else {
123
145
  columnBuilder.notNullable();
124
-
146
+ }
147
+
125
148
  this.logger.info(`[${table.name}.${column.name}] Adding constraint nullable: ${column.options?.nullable}`);
126
149
  }
127
-
150
+
128
151
  return columnBuilder;
129
152
  }
130
- }
153
+ }
@@ -1,87 +1,105 @@
1
1
  import knex from 'knex';
2
2
  import { isInstanceOf } from '@proteinjs/util';
3
- import { BinaryColumn, BooleanColumn, Column, DateColumn, DateTimeColumn, DecimalColumn, FloatColumn, IntegerColumn, StringColumn, UuidColumn } from '@proteinjs/db';
3
+ import {
4
+ BinaryColumn,
5
+ BooleanColumn,
6
+ Column,
7
+ DateColumn,
8
+ DateTimeColumn,
9
+ DecimalColumn,
10
+ FloatColumn,
11
+ IntegerColumn,
12
+ StringColumn,
13
+ UuidColumn,
14
+ } from '@proteinjs/db';
4
15
 
5
16
  export const getColumnFactory = (column: Column<any, any>): ColumnFactory => {
6
- if (isInstanceOf(column, IntegerColumn))
7
- return new IntegerColumnFactory();
8
- else if (isInstanceOf(column, UuidColumn))
9
- return new UuidColumnFactory();
10
- else if (isInstanceOf(column, StringColumn))
11
- return new StringColumnFactory();
12
- else if (isInstanceOf(column, FloatColumn))
13
- return new FloatColumnFactory();
14
- else if (isInstanceOf(column, DecimalColumn))
15
- return new DecimalColumnFactory();
16
- else if (isInstanceOf(column, BooleanColumn))
17
- return new BooleanColumnFactory();
18
- else if (isInstanceOf(column, DateColumn))
19
- return new DateColumnFactory();
20
- else if (isInstanceOf(column, DateTimeColumn))
21
- return new DateTimeColumnFactory();
22
- else if (isInstanceOf(column, BinaryColumn))
23
- return new BinaryColumnFactory();
17
+ if (isInstanceOf(column, IntegerColumn)) {
18
+ return new IntegerColumnFactory();
19
+ } else if (isInstanceOf(column, UuidColumn)) {
20
+ return new UuidColumnFactory();
21
+ } else if (isInstanceOf(column, StringColumn)) {
22
+ return new StringColumnFactory();
23
+ } else if (isInstanceOf(column, FloatColumn)) {
24
+ return new FloatColumnFactory();
25
+ } else if (isInstanceOf(column, DecimalColumn)) {
26
+ return new DecimalColumnFactory();
27
+ } else if (isInstanceOf(column, BooleanColumn)) {
28
+ return new BooleanColumnFactory();
29
+ } else if (isInstanceOf(column, DateColumn)) {
30
+ return new DateColumnFactory();
31
+ } else if (isInstanceOf(column, DateTimeColumn)) {
32
+ return new DateTimeColumnFactory();
33
+ } else if (isInstanceOf(column, BinaryColumn)) {
34
+ return new BinaryColumnFactory();
35
+ }
24
36
 
25
- throw new Error(`Invalid column type: ${column.constructor.name}, must extend a base column`);
26
- }
37
+ throw new Error(`Invalid column type: ${column.constructor.name}, must extend a base column`);
38
+ };
27
39
 
28
40
  export interface ColumnFactory {
29
41
  create(column: Column<any, any>, tableBuilder: knex.TableBuilder): knex.ColumnBuilder;
30
42
  }
31
43
 
32
44
  export class IntegerColumnFactory implements ColumnFactory {
33
- create(integerColumn: IntegerColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
34
- return integerColumn.large ? tableBuilder.bigInteger(integerColumn.name) : tableBuilder.integer(integerColumn.name);
35
- }
45
+ create(integerColumn: IntegerColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
46
+ return integerColumn.large ? tableBuilder.bigInteger(integerColumn.name) : tableBuilder.integer(integerColumn.name);
47
+ }
36
48
  }
37
49
 
38
50
  // max length of longtext is 4,294,967,295 bytes (~4 GiB)
39
51
  export class StringColumnFactory implements ColumnFactory {
40
- create(stringColumn: StringColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
41
- return stringColumn.maxLength === 'MAX' ? tableBuilder.text(stringColumn.name, 'longtext') : tableBuilder.string(stringColumn.name, stringColumn.maxLength);
42
- }
52
+ create(stringColumn: StringColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
53
+ return stringColumn.maxLength === 'MAX'
54
+ ? tableBuilder.text(stringColumn.name, 'longtext')
55
+ : tableBuilder.string(stringColumn.name, stringColumn.maxLength);
56
+ }
43
57
  }
44
58
 
45
59
  export class FloatColumnFactory implements ColumnFactory {
46
- create(floatColumn: FloatColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
47
- return tableBuilder.float(floatColumn.name);
48
- }
60
+ create(floatColumn: FloatColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
61
+ return tableBuilder.float(floatColumn.name);
62
+ }
49
63
  }
50
64
 
51
65
  export class DecimalColumnFactory implements ColumnFactory {
52
- create(decimalColumn: DecimalColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
53
- return decimalColumn.large ? tableBuilder.decimal(decimalColumn.name, 38, 20) : tableBuilder.decimal(decimalColumn.name);
54
- }
66
+ create(decimalColumn: DecimalColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
67
+ return decimalColumn.large
68
+ ? tableBuilder.decimal(decimalColumn.name, 38, 20)
69
+ : tableBuilder.decimal(decimalColumn.name);
70
+ }
55
71
  }
56
72
 
57
73
  export class BooleanColumnFactory implements ColumnFactory {
58
- create(booleanColumn: BooleanColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
59
- return tableBuilder.boolean(booleanColumn.name);
60
- }
74
+ create(booleanColumn: BooleanColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
75
+ return tableBuilder.boolean(booleanColumn.name);
76
+ }
61
77
  }
62
78
 
63
79
  export class DateColumnFactory implements ColumnFactory {
64
- create(dateColumn: DateColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
65
- return tableBuilder.date(dateColumn.name);
66
- }
80
+ create(dateColumn: DateColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
81
+ return tableBuilder.date(dateColumn.name);
82
+ }
67
83
  }
68
84
 
69
85
  export class DateTimeColumnFactory implements ColumnFactory {
70
- create(dateTimeColumn: DateTimeColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
71
- return tableBuilder.dateTime(dateTimeColumn.name);
72
- }
86
+ create(dateTimeColumn: DateTimeColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
87
+ return tableBuilder.dateTime(dateTimeColumn.name);
88
+ }
73
89
  }
74
90
 
75
91
  // max length of longblob is 4,294,967,295 bytes (~4 GiB)
76
92
  // max length when undefined (aka blob) is 65,535 bytes (~64 KiB)
77
93
  export class BinaryColumnFactory implements ColumnFactory {
78
- create(binaryColumn: BinaryColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
79
- return binaryColumn.maxLength == 'MAX' ? tableBuilder.specificType(binaryColumn.name, 'longblob') : tableBuilder.binary(binaryColumn.name, binaryColumn.maxLength);
80
- }
94
+ create(binaryColumn: BinaryColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
95
+ return binaryColumn.maxLength == 'MAX'
96
+ ? tableBuilder.specificType(binaryColumn.name, 'longblob')
97
+ : tableBuilder.binary(binaryColumn.name, binaryColumn.maxLength);
98
+ }
81
99
  }
82
100
 
83
101
  export class UuidColumnFactory implements ColumnFactory {
84
- create(uuidColumn: UuidColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
85
- return tableBuilder.uuid(uuidColumn.name);
86
- }
87
- }
102
+ create(uuidColumn: UuidColumn, tableBuilder: knex.TableBuilder): knex.ColumnBuilder {
103
+ return tableBuilder.uuid(uuidColumn.name);
104
+ }
105
+ }
package/test/Crud.test.ts CHANGED
@@ -1,21 +1,16 @@
1
- import { Table, crudTests } from '@proteinjs/db'
2
- import { KnexDriver } from '../src/KnexDriver'
1
+ import { Table, crudTests } from '@proteinjs/db';
2
+ import { KnexDriver } from '../src/KnexDriver';
3
3
 
4
4
  const knexDriver = new KnexDriver({
5
- host: 'localhost',
6
- user: 'root',
7
- password: '',
8
- dbName: 'test',
5
+ host: 'localhost',
6
+ user: 'root',
7
+ password: '',
8
+ dbName: 'test',
9
9
  });
10
10
  const dropTable = async (table: Table<any>) => {
11
- if (await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).hasTable(table.name))
12
- await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).dropTable(table.name);
13
- }
11
+ if (await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).hasTable(table.name)) {
12
+ await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).dropTable(table.name);
13
+ }
14
+ };
14
15
 
15
- describe(
16
- 'CRUD Tests',
17
- crudTests(
18
- knexDriver,
19
- dropTable
20
- )
21
- );
16
+ describe('CRUD Tests', crudTests(knexDriver, dropTable));
@@ -1,23 +1,17 @@
1
- import { Table, tableManagerTests } from '@proteinjs/db'
2
- import { KnexDriver } from '../src/KnexDriver'
1
+ import { Table, tableManagerTests } from '@proteinjs/db';
2
+ import { KnexDriver } from '../src/KnexDriver';
3
3
  import { KnexColumnTypeFactory } from '../src/KnexColumnTypeFactory';
4
4
 
5
5
  const knexDriver = new KnexDriver({
6
- host: 'localhost',
7
- user: 'root',
8
- password: '',
9
- dbName: 'test',
6
+ host: 'localhost',
7
+ user: 'root',
8
+ password: '',
9
+ dbName: 'test',
10
10
  });
11
11
  const dropTable = async (table: Table<any>) => {
12
- if (await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).hasTable(table.name))
13
- await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).dropTable(table.name);
14
- }
12
+ if (await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).hasTable(table.name)) {
13
+ await knexDriver.getKnex().schema.withSchema(knexDriver.getDbName()).dropTable(table.name);
14
+ }
15
+ };
15
16
 
16
- describe(
17
- 'Table Manager Tests',
18
- tableManagerTests(
19
- knexDriver,
20
- dropTable,
21
- new KnexColumnTypeFactory().getType
22
- )
23
- );
17
+ describe('Table Manager Tests', tableManagerTests(knexDriver, dropTable, new KnexColumnTypeFactory().getType));
package/tsconfig.json CHANGED
@@ -1,23 +1,19 @@
1
1
  {
2
- "compilerOptions": {
3
- "rootDir": "./",
4
- "target": "es5",
5
- "module": "commonjs",
6
- "declaration": true,
7
- "declarationMap": true,
8
- "sourceMap": true,
9
- "outDir": "./dist/",
10
- "strict": true,
11
- "noImplicitAny": true,
12
- "esModuleInterop": true,
13
- "skipLibCheck": true,
14
- "forceConsistentCasingInFileNames": true,
15
- "resolveJsonModule": true,
16
- "typeRoots": [
17
- "./node_modules/@types"
18
- ],
19
- "types": [
20
- "node", "jest"
21
- ]
22
- }
23
- }
2
+ "compilerOptions": {
3
+ "rootDir": "./",
4
+ "target": "es5",
5
+ "module": "commonjs",
6
+ "declaration": true,
7
+ "declarationMap": true,
8
+ "sourceMap": true,
9
+ "outDir": "./dist/",
10
+ "strict": true,
11
+ "noImplicitAny": true,
12
+ "esModuleInterop": true,
13
+ "skipLibCheck": true,
14
+ "forceConsistentCasingInFileNames": true,
15
+ "resolveJsonModule": true,
16
+ "typeRoots": ["./node_modules/@types"],
17
+ "types": ["node", "jest"]
18
+ }
19
+ }