anote-server-libs 0.9.5 → 0.9.6

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.
@@ -23,34 +23,34 @@ class BaseModelRepository {
23
23
  this.Migration = new Migration_1.MigrationRepository(db, dbMssql, logger);
24
24
  this.ApiCall = new ApiCall_1.ApiCallRepository(db, dbMssql, logger);
25
25
  }
26
- migrate(migrationsPath, callback, onlyAboveOrEquals = 0) {
26
+ migrate(migrationsPath, callback, onlyAboveOrEquals = 0, onlyBelow) {
27
27
  (this.db ? Promise.all([
28
- this.db.query(`CREATE TABLE IF NOT EXISTS migration (
29
- id integer PRIMARY KEY,
30
- hash text NOT NULL,
31
- "sqlUp" text NOT NULL,
32
- "sqlDown" text NOT NULL,
33
- state integer NOT NULL,
34
- skip boolean NOT NULL
28
+ this.db.query(`CREATE TABLE IF NOT EXISTS migration (
29
+ id integer PRIMARY KEY,
30
+ hash text NOT NULL,
31
+ "sqlUp" text NOT NULL,
32
+ "sqlDown" text NOT NULL,
33
+ state integer NOT NULL,
34
+ skip boolean NOT NULL
35
35
  )`),
36
36
  this.db.query(`ALTER TABLE migration ADD COLUMN IF NOT EXISTS skip BOOLEAN NOT NULL DEFAULT FALSE`)
37
37
  ]) : Promise.all([
38
- this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
39
- id int PRIMARY KEY,
40
- hash text NOT NULL,
41
- "sqlUp" text NOT NULL,
42
- "sqlDown" text NOT NULL,
43
- state int NOT NULL,
44
- skip bit NOT NULL
38
+ this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
39
+ id int PRIMARY KEY,
40
+ hash text NOT NULL,
41
+ "sqlUp" text NOT NULL,
42
+ "sqlDown" text NOT NULL,
43
+ state int NOT NULL,
44
+ skip bit NOT NULL
45
45
  )`),
46
- this.dbMssql.query(`IF NOT EXISTS (
47
- SELECT *
48
- FROM INFORMATION_SCHEMA.COLUMNS
49
- WHERE TABLE_NAME = 'migration'
50
- AND COLUMN_NAME = 'skip'
51
- )
52
- BEGIN
53
- ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
46
+ this.dbMssql.query(`IF NOT EXISTS (
47
+ SELECT *
48
+ FROM INFORMATION_SCHEMA.COLUMNS
49
+ WHERE TABLE_NAME = 'migration'
50
+ AND COLUMN_NAME = 'skip'
51
+ )
52
+ BEGIN
53
+ ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
54
54
  END`)
55
55
  ])).then(() => {
56
56
  this.Migration.getAllBy('id').then((migrations) => {
@@ -70,16 +70,22 @@ END`)
70
70
  hash: crypto.createHash('sha256').update(content).digest('hex')
71
71
  };
72
72
  });
73
- if (migrationsAvailable.length === 0
74
- || migrationsAvailable.length
75
- !== migrationsAvailable[migrationsAvailable.length - 1].id)
73
+ migrations = migrations.filter(m => m.id >= onlyAboveOrEquals);
74
+ if (onlyBelow)
75
+ migrations = migrations.filter(m => m.id < onlyBelow);
76
+ if (migrationsAvailable.length === 0 && migrations.length === 0)
76
77
  process.exit(5);
77
- let highestCommon = onlyAboveOrEquals;
78
- while (highestCommon < migrations.length && highestCommon < migrationsAvailable.length
78
+ if (migrationsAvailable.length && migrationsAvailable.length !== (migrationsAvailable[migrationsAvailable.length - 1].id - migrationsAvailable[0].id + 1))
79
+ process.exit(5);
80
+ let highestCommon = 0;
81
+ while (highestCommon < migrations.length
82
+ && highestCommon < migrationsAvailable.length
83
+ && migrations[highestCommon]
84
+ && migrationsAvailable[highestCommon]
79
85
  && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
80
86
  highestCommon++;
81
- this.applyDownUntil(migrations, migrations.length, highestCommon).then(highestCommon => {
82
- this.applyUpUntil(migrationsAvailable, Math.min(highestCommon, migrations.length), migrationsAvailable.length).then(callback, process.exit);
87
+ this.applyDownUntil(migrations, migrations.length, highestCommon).then(appliedId => {
88
+ this.applyUpUntil(migrationsAvailable, Math.min(appliedId, migrations.length), migrationsAvailable.length).then(callback, process.exit);
83
89
  }, process.exit);
84
90
  });
85
91
  }, () => process.exit(3));
@@ -91,8 +97,10 @@ END`)
91
97
  return Promise.all(tables.map(t => client.request().query('SELECT id FROM ' + t.table + ' WITH (UPDLOCK)')));
92
98
  }
93
99
  applyUpUntil(migrations, current, until) {
94
- if (current < until)
100
+ if (current < until) {
101
+ console.log('Applying migration ' + migrations[current].id);
95
102
  return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
103
+ }
96
104
  return Promise.resolve();
97
105
  }
98
106
  applyUp(migration) {
@@ -126,6 +134,7 @@ END`)
126
134
  applyDownUntil(migrations, current, until) {
127
135
  if (current > until && !migrations[current - 1]?.skip) {
128
136
  current--;
137
+ console.log('Reverting migration ' + migrations[current].id);
129
138
  return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
130
139
  }
131
140
  return Promise.resolve(current);
@@ -1,168 +1,175 @@
1
- import * as crypto from 'crypto';
2
- import * as fs from 'fs';
3
- import * as Memcached from 'memcached';
4
- import {ConnectionPool, Transaction} from 'mssql';
5
- import {ClientBase, Pool} from 'pg';
6
- import {Logger} from 'winston';
7
- import { ApiCallRepository } from '../ApiCall';
8
- import { Migration, MigrationRepository } from '../Migration';
9
- import {ModelRepr} from './ModelDao';
10
-
11
- export class BaseModelRepository {
12
- Migration: MigrationRepository;
13
- ApiCall: ApiCallRepository;
14
-
15
- constructor(public db: Pool, public dbSpare: Pool, public dbMssql: ConnectionPool, public logger: Logger, public cache: Memcached) {
16
- if(db && dbSpare) {
17
- const dbQuery = db.query.bind(db);
18
- db.query = (function(text: any, values: any, cb: any) {
19
- if((this.idleCount + this.waitingCount) >= this.totalCount && this.totalCount === this.options.max)
20
- return dbSpare.query(text, values, cb);
21
- return dbQuery(text, values, cb);
22
- }).bind(db);
23
- }
24
- this.Migration = new MigrationRepository(db, dbMssql, logger);
25
- this.ApiCall = new ApiCallRepository(db, dbMssql, logger);
26
- }
27
-
28
- // TODO: alter table migration if exists without ok column
29
- migrate(migrationsPath: string, callback: (() => void), onlyAboveOrEquals = 0) {
30
- (this.db ? Promise.all([
31
- this.db.query(`CREATE TABLE IF NOT EXISTS migration (
32
- id integer PRIMARY KEY,
33
- hash text NOT NULL,
34
- "sqlUp" text NOT NULL,
35
- "sqlDown" text NOT NULL,
36
- state integer NOT NULL,
37
- skip boolean NOT NULL
38
- )`),
39
- this.db.query(`ALTER TABLE migration ADD COLUMN IF NOT EXISTS skip BOOLEAN NOT NULL DEFAULT FALSE`)]) : Promise.all([
40
- this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
41
- id int PRIMARY KEY,
42
- hash text NOT NULL,
43
- "sqlUp" text NOT NULL,
44
- "sqlDown" text NOT NULL,
45
- state int NOT NULL,
46
- skip bit NOT NULL
47
- )`),
48
- this.dbMssql.query(`IF NOT EXISTS (
49
- SELECT *
50
- FROM INFORMATION_SCHEMA.COLUMNS
51
- WHERE TABLE_NAME = 'migration'
52
- AND COLUMN_NAME = 'skip'
53
- )
54
- BEGIN
55
- ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
56
- END`)])).then(() => {
57
- this.Migration.getAllBy('id').then((migrations: Migration[]) => {
58
- if(migrations.find(migration => migration.state !== 0)) process.exit(4); // Have to fix manually
59
- // Read the new ones
60
- fs.readdir(migrationsPath, (_, files) => {
61
- const migrationsAvailable = files
62
- .filter(file => /[0-9]+\.sql/.test(file))
63
- .map(file => parseInt(file.split('.sql')[0], 10))
64
- .filter(file => file > 0)
65
- .sort((a, b) => a - b)
66
- .map(file => {
67
- const content = fs.readFileSync(migrationsPath + file + '.sql', 'utf-8');
68
- return {
69
- id: file,
70
- content: content,
71
- hash: crypto.createHash('sha256').update(content).digest('hex')
72
- };
73
- });
74
- if(migrationsAvailable.length === 0
75
- || migrationsAvailable.length
76
- !== migrationsAvailable[migrationsAvailable.length - 1].id) process.exit(5); // Did not use OK files
77
- let highestCommon = onlyAboveOrEquals;
78
- while(highestCommon < migrations.length && highestCommon < migrationsAvailable.length
79
- && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
80
- highestCommon++;
81
- this.applyDownUntil(migrations, migrations.length, highestCommon).then(highestCommon => {
82
- this.applyUpUntil(migrationsAvailable, Math.min(highestCommon, migrations.length), migrationsAvailable.length).then(callback, process.exit);
83
- }, process.exit);
84
- });
85
- }, () => process.exit(3));
86
- }, () => process.exit(2));
87
- }
88
-
89
- lockTables(tables: ModelRepr[], client: ClientBase | Transaction): Promise<any> {
90
- if(this.db)
91
- return Promise.all(tables.map(t => (<ClientBase>client).query('LOCK TABLE ' + t.table + ' IN EXCLUSIVE MODE')));
92
- return Promise.all(tables.map(t => (<Transaction>client).request().query('SELECT id FROM ' + t.table + ' WITH (UPDLOCK)')));
93
- }
94
-
95
- private applyUpUntil(migrations: {id: number, content: string, hash: string}[], current: number, until: number): Promise<void> {
96
- if(current < until)
97
- return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
98
- return Promise.resolve();
99
- }
100
-
101
- private applyUp(migration: {id: number, content: string, hash: string}): Promise<void> {
102
- return new Promise((resolve, reject) => {
103
- const sqlParts = migration.content.split(/-{4,}/);
104
- this.Migration.create({
105
- id: migration.id,
106
- hash: migration.hash,
107
- sqlUp: sqlParts[0],
108
- sqlDown: sqlParts[1],
109
- state: 2,
110
- skip: false
111
- }).then(() => {
112
- (<any>(this.db|| this.dbMssql)).query(sqlParts[0], (err: any) => {
113
- if(err) {
114
- console.error(err);
115
- reject(10);
116
- } else {
117
- (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=0 WHERE "id"=' + migration.id, (err2: any) => {
118
- if(err2) reject(11); // No cleanup
119
- else resolve();
120
- });
121
- }
122
- });
123
- }, () => process.exit(9));
124
- });
125
- }
126
-
127
- private applyDownUntil(migrations: Migration[], current: number, until: number): Promise<number> {
128
- if(current > until && !migrations[current - 1]?.skip) {
129
- current--;
130
- return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
131
- }
132
- return Promise.resolve(current);
133
- }
134
-
135
- private applyDown(migration: Migration): Promise<void> {
136
- return new Promise((resolve, reject) => {
137
- (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=1 WHERE "id"=' + migration.id, (err: any) => {
138
- if(err) reject(6); // No required change
139
- else (<any>(this.db|| this.dbMssql)).query(migration.sqlDown, (err2: any) => {
140
- if(err2) {
141
- console.error(err2);
142
- reject(7);
143
- } // No apply down
144
- else (<any>(this.db|| this.dbMssql)).query('DELETE FROM "migration" WHERE "id"=' + migration.id, (err3: any) => {
145
- if(err3 && migration.id !== 1) reject(8); // No cleanup for not base migration
146
- else {
147
- if(migration.id === 1) {
148
- (this.db ? this.db.query('CREATE TABLE IF NOT EXISTS migration (' +
149
- 'id integer PRIMARY KEY,' +
150
- 'hash text NOT NULL,' +
151
- '"sqlUp" text NOT NULL,' +
152
- '"sqlDown" text NOT NULL,' +
153
- 'state integer NOT NULL' +
154
- ')') : this.dbMssql.query('if not exists (select * from sysobjects where name=\'migration\' and xtype=\'U\') CREATE TABLE migration (' +
155
- 'id int PRIMARY KEY,' +
156
- 'hash text NOT NULL,' +
157
- '"sqlUp" text NOT NULL,' +
158
- '"sqlDown" text NOT NULL,' +
159
- 'state int NOT NULL' +
160
- ')')).then(() => resolve(), reject);
161
- } else resolve();
162
- }
163
- });
164
- });
165
- });
166
- });
167
- }
168
- }
1
+ import * as crypto from 'crypto';
2
+ import * as fs from 'fs';
3
+ import * as Memcached from 'memcached';
4
+ import {ConnectionPool, Transaction} from 'mssql';
5
+ import {ClientBase, Pool} from 'pg';
6
+ import {Logger} from 'winston';
7
+ import { ApiCallRepository } from '../ApiCall';
8
+ import { Migration, MigrationRepository } from '../Migration';
9
+ import {ModelRepr} from './ModelDao';
10
+
11
+ export class BaseModelRepository {
12
+ Migration: MigrationRepository;
13
+ ApiCall: ApiCallRepository;
14
+
15
+ constructor(public db: Pool, public dbSpare: Pool, public dbMssql: ConnectionPool, public logger: Logger, public cache: Memcached) {
16
+ if(db && dbSpare) {
17
+ const dbQuery = db.query.bind(db);
18
+ db.query = (function(text: any, values: any, cb: any) {
19
+ if((this.idleCount + this.waitingCount) >= this.totalCount && this.totalCount === this.options.max)
20
+ return dbSpare.query(text, values, cb);
21
+ return dbQuery(text, values, cb);
22
+ }).bind(db);
23
+ }
24
+ this.Migration = new MigrationRepository(db, dbMssql, logger);
25
+ this.ApiCall = new ApiCallRepository(db, dbMssql, logger);
26
+ }
27
+
28
+ // TODO: alter table migration if exists without ok column
29
+ migrate(migrationsPath: string, callback: (() => void), onlyAboveOrEquals = 0, onlyBelow?: number) {
30
+ (this.db ? Promise.all([
31
+ this.db.query(`CREATE TABLE IF NOT EXISTS migration (
32
+ id integer PRIMARY KEY,
33
+ hash text NOT NULL,
34
+ "sqlUp" text NOT NULL,
35
+ "sqlDown" text NOT NULL,
36
+ state integer NOT NULL,
37
+ skip boolean NOT NULL
38
+ )`),
39
+ this.db.query(`ALTER TABLE migration ADD COLUMN IF NOT EXISTS skip BOOLEAN NOT NULL DEFAULT FALSE`)]) : Promise.all([
40
+ this.dbMssql.query(`IF NOT EXISTS (SELECT * FROM sysobjects WHERE name=\'migration\' AND xtype=\'U\') CREATE TABLE migration (
41
+ id int PRIMARY KEY,
42
+ hash text NOT NULL,
43
+ "sqlUp" text NOT NULL,
44
+ "sqlDown" text NOT NULL,
45
+ state int NOT NULL,
46
+ skip bit NOT NULL
47
+ )`),
48
+ this.dbMssql.query(`IF NOT EXISTS (
49
+ SELECT *
50
+ FROM INFORMATION_SCHEMA.COLUMNS
51
+ WHERE TABLE_NAME = 'migration'
52
+ AND COLUMN_NAME = 'skip'
53
+ )
54
+ BEGIN
55
+ ALTER TABLE migration ADD skip BIT NOT NULL DEFAULT 0;
56
+ END`)])).then(() => {
57
+ this.Migration.getAllBy('id').then((migrations: Migration[]) => {
58
+ if(migrations.find(migration => migration.state !== 0)) process.exit(4); // Have to fix manually
59
+ // Read the new ones
60
+ fs.readdir(migrationsPath, (_, files) => {
61
+ const migrationsAvailable = files
62
+ .filter(file => /[0-9]+\.sql/.test(file))
63
+ .map(file => parseInt(file.split('.sql')[0], 10))
64
+ .filter(file => file > 0)
65
+ .sort((a, b) => a - b)
66
+ .map(file => {
67
+ const content = fs.readFileSync(migrationsPath + file + '.sql', 'utf-8');
68
+ return {
69
+ id: file,
70
+ content: content,
71
+ hash: crypto.createHash('sha256').update(content).digest('hex')
72
+ };
73
+ });
74
+ migrations = migrations.filter(m => m.id >= onlyAboveOrEquals);
75
+ if(onlyBelow) migrations = migrations.filter(m => m.id < onlyBelow);
76
+ if(migrationsAvailable.length === 0 && migrations.length === 0) process.exit(5);
77
+ if(migrationsAvailable.length && migrationsAvailable.length !== (migrationsAvailable[migrationsAvailable.length - 1].id - migrationsAvailable[0].id + 1)) process.exit(5);
78
+ let highestCommon = 0;
79
+ while(highestCommon < migrations.length
80
+ && highestCommon < migrationsAvailable.length
81
+ && migrations[highestCommon]
82
+ && migrationsAvailable[highestCommon]
83
+ && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
84
+ highestCommon++;
85
+ this.applyDownUntil(migrations, migrations.length, highestCommon).then(appliedId => {
86
+ this.applyUpUntil(migrationsAvailable, Math.min(appliedId, migrations.length), migrationsAvailable.length).then(callback, process.exit);
87
+ }, process.exit);
88
+ });
89
+ }, () => process.exit(3));
90
+ }, () => process.exit(2));
91
+ }
92
+
93
+ lockTables(tables: ModelRepr[], client: ClientBase | Transaction): Promise<any> {
94
+ if(this.db)
95
+ return Promise.all(tables.map(t => (<ClientBase>client).query('LOCK TABLE ' + t.table + ' IN EXCLUSIVE MODE')));
96
+ return Promise.all(tables.map(t => (<Transaction>client).request().query('SELECT id FROM ' + t.table + ' WITH (UPDLOCK)')));
97
+ }
98
+
99
+ private applyUpUntil(migrations: {id: number, content: string, hash: string}[], current: number, until: number): Promise<void> {
100
+ if(current < until) {
101
+ console.log('Applying migration ' + migrations[current].id);
102
+ return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
103
+ }
104
+ return Promise.resolve();
105
+ }
106
+
107
+ private applyUp(migration: {id: number, content: string, hash: string}): Promise<void> {
108
+ return new Promise((resolve, reject) => {
109
+ const sqlParts = migration.content.split(/-{4,}/);
110
+ this.Migration.create({
111
+ id: migration.id,
112
+ hash: migration.hash,
113
+ sqlUp: sqlParts[0],
114
+ sqlDown: sqlParts[1],
115
+ state: 2,
116
+ skip: false
117
+ }).then(() => {
118
+ (<any>(this.db|| this.dbMssql)).query(sqlParts[0], (err: any) => {
119
+ if(err) {
120
+ console.error(err);
121
+ reject(10);
122
+ } else {
123
+ (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=0 WHERE "id"=' + migration.id, (err2: any) => {
124
+ if(err2) reject(11); // No cleanup
125
+ else resolve();
126
+ });
127
+ }
128
+ });
129
+ }, () => process.exit(9));
130
+ });
131
+ }
132
+
133
+ private applyDownUntil(migrations: Migration[], current: number, until: number): Promise<number> {
134
+ if(current > until && !migrations[current - 1]?.skip) {
135
+ current--;
136
+ console.log('Reverting migration ' + migrations[current].id);
137
+ return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
138
+ }
139
+ return Promise.resolve(current);
140
+ }
141
+
142
+ private applyDown(migration: Migration): Promise<void> {
143
+ return new Promise((resolve, reject) => {
144
+ (<any>(this.db|| this.dbMssql)).query('UPDATE "migration" SET "state"=1 WHERE "id"=' + migration.id, (err: any) => {
145
+ if(err) reject(6); // No required change
146
+ else (<any>(this.db|| this.dbMssql)).query(migration.sqlDown, (err2: any) => {
147
+ if(err2) {
148
+ console.error(err2);
149
+ reject(7);
150
+ } // No apply down
151
+ else (<any>(this.db|| this.dbMssql)).query('DELETE FROM "migration" WHERE "id"=' + migration.id, (err3: any) => {
152
+ if(err3 && migration.id !== 1) reject(8); // No cleanup for not base migration
153
+ else {
154
+ if(migration.id === 1) {
155
+ (this.db ? this.db.query('CREATE TABLE IF NOT EXISTS migration (' +
156
+ 'id integer PRIMARY KEY,' +
157
+ 'hash text NOT NULL,' +
158
+ '"sqlUp" text NOT NULL,' +
159
+ '"sqlDown" text NOT NULL,' +
160
+ 'state integer NOT NULL' +
161
+ ')') : this.dbMssql.query('if not exists (select * from sysobjects where name=\'migration\' and xtype=\'U\') CREATE TABLE migration (' +
162
+ 'id int PRIMARY KEY,' +
163
+ 'hash text NOT NULL,' +
164
+ '"sqlUp" text NOT NULL,' +
165
+ '"sqlDown" text NOT NULL,' +
166
+ 'state int NOT NULL' +
167
+ ')')).then(() => resolve(), reject);
168
+ } else resolve();
169
+ }
170
+ });
171
+ });
172
+ });
173
+ });
174
+ }
175
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anote-server-libs",
3
- "version": "0.9.5",
3
+ "version": "0.9.6",
4
4
  "description": "Helpers for express-TS servers",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1",