mythix-orm-postgresql 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Wyatt Greenway
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # mythix-orm-postgresql
2
+
3
+ PostgreSQL driver for Mythix ORM
4
+
5
+ Mythix ORM aims to replace Sequelize and the few other terrible solutions that the poor destitute Node community has to work with. Mythix ORM is not yet quite ready for prime time however, so please check back soon!
package/lib/index.js ADDED
@@ -0,0 +1,9 @@
1
+ 'use strict';
2
+
3
+ const PostgreSQLConnection = require('./postgresql-connection');
4
+ const PostgreSQLQueryGenerator = require('./postgresql-query-generator');
5
+
6
+ module.exports = {
7
+ PostgreSQLConnection,
8
+ PostgreSQLQueryGenerator,
9
+ };
@@ -0,0 +1,336 @@
1
+ /* eslint-disable no-magic-numbers */
2
+ /* eslint-disable camelcase */
3
+
4
+ 'use strict';
5
+
6
+ const Nife = require('nife');
7
+ const moment = require('mythix-orm/node_modules/moment');
8
+ const PG = require('pg');
9
+ const PGFormat = require('pg-format');
10
+ const { Literals } = require('mythix-orm');
11
+ const { SQLConnectionBase } = require('mythix-orm-sql-base');
12
+ const PostgreSQLQueryGenerator = require('./postgresql-query-generator');
13
+
14
+ class PostgreSQLConnection extends SQLConnectionBase {
15
+ static dialect = 'postgresql';
16
+
17
+ constructor(_options) {
18
+ super(_options);
19
+
20
+ this.setQueryGenerator(new PostgreSQLQueryGenerator(this));
21
+
22
+ Object.defineProperties(this, {
23
+ 'pool': {
24
+ writable: true,
25
+ enumberable: false,
26
+ configurable: true,
27
+ value: null,
28
+ },
29
+ });
30
+ }
31
+
32
+ isStarted() {
33
+ return !!this.pool;
34
+ }
35
+
36
+ async start() {
37
+ let options = this.getOptions();
38
+
39
+ if (options.foreignConstraints != null && options.logger)
40
+ options.logger.warn('"foreignConstraints" option is not supported by the PostgreSQL driver.');
41
+
42
+ let opts = Object.assign(
43
+ {
44
+ allowExitOnIdle: true,
45
+ },
46
+ options,
47
+ {
48
+ statement_timeout: options.statementTimeout,
49
+ query_timeout: options.queryTimeout,
50
+ connectionTimeoutMillis: options.connectionTimeout,
51
+ idle_in_transaction_session_timeout: options.idleTransactionTimeout,
52
+ idleTimeoutMillis: options.idleConnectionTimeout,
53
+ max: options.maxPoolConnections,
54
+ },
55
+ );
56
+
57
+ const PGScope = (opts.native === true && PG.native) ? PG.native : PG;
58
+
59
+ let pool = this.pool = new PGScope.Pool(opts);
60
+
61
+ pool.on('connect', (client) => {
62
+ this.emit('connect', client);
63
+ });
64
+
65
+ pool.on('acquire', (client) => {
66
+ this.emit('acquire', client);
67
+ });
68
+
69
+ pool.on('error', (error, client) => {
70
+ this.emit('error', error, client);
71
+ });
72
+
73
+ pool.on('remove', (client) => {
74
+ this.emit('disconnect', client);
75
+ });
76
+ }
77
+
78
+ async stop() {
79
+ if (!this.pool)
80
+ return;
81
+
82
+ await this.pool.end();
83
+ this.pool = null;
84
+
85
+ await super.stop();
86
+ }
87
+
88
+ _escape(value) {
89
+ return PGFormat.literal(value);
90
+ }
91
+
92
+ _escapeID(value) {
93
+ return PGFormat.ident(value);
94
+ }
95
+
96
+ getDefaultFieldValue(type) {
97
+ switch (type) {
98
+ case 'AUTO_INCREMENT':
99
+ // This will get discarded by createTable...
100
+ // but we need the value later to select the
101
+ // proper column data type
102
+ return new Literals.Literal('@@@AUTOINCREMENT@@@', { noDefaultStatementOnCreateTable: true, remote: true });
103
+ case 'DATETIME_NOW':
104
+ return new Literals.Literal('(NOW() AT TIME ZONE(\'UTC\'))', { escape: false, remote: true });
105
+ case 'DATE_NOW':
106
+ return new Literals.Literal('(NOW() AT TIME ZONE(\'UTC\'))', { escape: false, remote: true });
107
+ case 'DATETIME_NOW_LOCAL':
108
+ return moment().toDate();
109
+ case 'DATE_NOW_LOCAL':
110
+ return moment().startOf('day').toDate();
111
+ default:
112
+ return type;
113
+ }
114
+ }
115
+
116
+ // eslint-disable-next-line no-unused-vars
117
+ async enableForeignKeyConstraints(enable) {
118
+ // Not supported in PostgreSQL
119
+ return;
120
+ }
121
+
122
+ async exec(...args) {
123
+ return await this.query(...args);
124
+ }
125
+
126
+ async query(_sql, _options) {
127
+ let sql = _sql;
128
+ if (!sql)
129
+ return;
130
+
131
+ if (Nife.instanceOf(sql, 'string'))
132
+ sql = { text: sql, rowMode: 'array' };
133
+ else if (Nife.instanceOf(sql, 'object'))
134
+ sql = Object.assign({ text: sql, rowMode: 'array' }, sql);
135
+
136
+ let options = _options || {};
137
+ let logger = options.logger || (this.getOptions().logger);
138
+ let inTransaction = false;
139
+ let client;
140
+
141
+ try {
142
+ client = options.connection || this.inTransaction;
143
+ if (!client)
144
+ client = await this.pool.connect();
145
+ else
146
+ inTransaction = true;
147
+
148
+ if (logger && sql.text)
149
+ console.log('QUERY: ', sql.text);
150
+
151
+ let result;
152
+
153
+ if (Nife.isNotEmpty(options.parameters))
154
+ result = await client.query(sql, options.parameters);
155
+ else
156
+ result = await client.query(sql);
157
+
158
+ return this.formatResultsResponse(sql, result);
159
+ } catch (error) {
160
+ if (logger) {
161
+ logger.error(error);
162
+ logger.error('QUERY: ', sql);
163
+ }
164
+
165
+ error.query = sql;
166
+
167
+ throw error;
168
+ } finally {
169
+ if (client && !inTransaction)
170
+ await client.release();
171
+ }
172
+ }
173
+
174
+ async transaction(callback, _options) {
175
+ let options = _options || {};
176
+ let inheritedThis = Object.create(options.connection || this);
177
+ let savePointName;
178
+ let client;
179
+
180
+ if (!inheritedThis.inTransaction) {
181
+ client = options.connection;
182
+ if (!client)
183
+ client = await this.pool.connect();
184
+
185
+ inheritedThis.inTransaction = client;
186
+
187
+ try {
188
+ await inheritedThis.query(`BEGIN${(options.mode) ? ` ${options.mode}` : ''}`);
189
+ } catch (error) {
190
+ if (!options.connection)
191
+ await client.release();
192
+
193
+ throw error;
194
+ }
195
+ } else {
196
+ savePointName = this.generateSavePointName();
197
+ inheritedThis.savePointName = savePointName;
198
+ inheritedThis.isSavePoint = true;
199
+
200
+ await inheritedThis.query(`SAVEPOINT ${savePointName}`);
201
+ }
202
+
203
+ try {
204
+ let result = await callback.call(inheritedThis, inheritedThis);
205
+
206
+ if (savePointName)
207
+ await inheritedThis.query(`RELEASE SAVEPOINT ${savePointName}`);
208
+ else
209
+ await inheritedThis.query('COMMIT');
210
+
211
+ return result;
212
+ } catch (error) {
213
+ if (savePointName)
214
+ await inheritedThis.query(`ROLLBACK TO SAVEPOINT ${savePointName}`);
215
+ else if (inheritedThis.inTransaction)
216
+ await inheritedThis.query('ROLLBACK');
217
+
218
+ throw error;
219
+ } finally {
220
+ if (!savePointName && client)
221
+ await client.release();
222
+ }
223
+ }
224
+
225
+ formatResultsResponse(sqlStatement, result) {
226
+ if (!result.rows || !result.fields)
227
+ return result;
228
+
229
+ return {
230
+ rows: result.rows,
231
+ columns: result.fields.map((field) => field.name),
232
+ };
233
+ }
234
+
235
+ async truncate(Model, options) {
236
+ let queryGenerator = this.getQueryGenerator();
237
+ let sqlStatement = queryGenerator.generateTruncateTableStatement(Model, options);
238
+
239
+ return await this.query(sqlStatement);
240
+ }
241
+
242
+ _intTypeToSerial(type) {
243
+ let size = type.length;
244
+ if (size == null)
245
+ size = 4;
246
+
247
+ if (size <= 2)
248
+ return 'SMALLSERIAL';
249
+ else if (size <= 4)
250
+ return 'SERIAL';
251
+ else
252
+ return 'BIGSERIAL';
253
+ }
254
+
255
+ _bigintTypeToString(type, _options) {
256
+ let options = _options || {};
257
+
258
+ if (options.createTable && options.defaultValue === '@@@AUTOINCREMENT@@@')
259
+ return this._intTypeToSerial(type);
260
+
261
+ return 'BIGINT';
262
+ }
263
+
264
+ _integerTypeToString(type, _options) {
265
+ let options = _options || {};
266
+
267
+ if (options.createTable && options.defaultValue === '@@@AUTOINCREMENT@@@')
268
+ return this._intTypeToSerial(type);
269
+
270
+ return 'INTEGER';
271
+ }
272
+
273
+ _blobTypeToString(type) {
274
+ return 'BYTEA';
275
+ }
276
+
277
+ _datetimeTypeToString(type) {
278
+ return 'TIMESTAMP';
279
+ }
280
+
281
+ async average(_queryEngine, _field, options) {
282
+ let result = await super.average(_queryEngine, _field, options);
283
+
284
+ if (typeof result === 'string')
285
+ result = parseFloat(result);
286
+
287
+ return result;
288
+ }
289
+
290
+ async count(_queryEngine, _field, options) {
291
+ let result = await super.count(_queryEngine, _field, options);
292
+
293
+ if (typeof result === 'string')
294
+ result = parseInt(result, 10);
295
+
296
+ return result;
297
+ }
298
+
299
+ async min(_queryEngine, _field, options) {
300
+ let result = await super.min(_queryEngine, _field, options);
301
+
302
+ if (typeof result === 'string')
303
+ result = parseFloat(result);
304
+
305
+ return result;
306
+ }
307
+
308
+ async max(_queryEngine, _field, options) {
309
+ let result = await super.max(_queryEngine, _field, options);
310
+
311
+ if (typeof result === 'string')
312
+ result = parseFloat(result);
313
+
314
+ return result;
315
+ }
316
+
317
+ async sum(_queryEngine, _field, options) {
318
+ let result = await super.sum(_queryEngine, _field, options);
319
+
320
+ if (typeof result === 'string')
321
+ result = parseFloat(result);
322
+
323
+ return result;
324
+ }
325
+
326
+ convertDateToDBTime(value) {
327
+ if (value instanceof Date || (value && value.constructor && value.constructor.name === 'Date'))
328
+ return moment(value).utc(true).toDate();
329
+ else if (moment.isMoment(value))
330
+ return value.utc(true).toDate();
331
+
332
+ return value;
333
+ }
334
+ }
335
+
336
+ module.exports = PostgreSQLConnection;
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ const Nife = require('nife');
4
+ const { Literals } = require('mythix-orm');
5
+ const { SQLQueryGeneratorBase } = require('mythix-orm-sql-base');
6
+
7
+ const LiteralBase = Literals.LiteralBase;
8
+
9
+ class PostgreSQLQueryGenerator extends SQLQueryGeneratorBase {
10
+ // eslint-disable-next-line no-unused-vars
11
+ generateSQLJoinTypeFromQueryEngineJoinType(joinType, outer, options) {
12
+ if (!joinType || joinType === 'inner')
13
+ return 'INNER JOIN';
14
+ else if (joinType === 'left')
15
+ return 'LEFT JOIN';
16
+ else if (joinType === 'cross')
17
+ return 'CROSS JOIN';
18
+
19
+ return joinType;
20
+ }
21
+
22
+ generateForeignKeyConstraint(field, type) {
23
+ let options = type.getOptions();
24
+ let targetModel = type.getTargetModel();
25
+ let targetField = type.getTargetField();
26
+
27
+ let sqlParts = [
28
+ 'FOREIGN KEY(',
29
+ this.escapeID(field.columnName),
30
+ ') REFERENCES ',
31
+ this.escapeID(targetModel.getTableName(this.connection)),
32
+ '(',
33
+ this.escapeID(targetField.columnName),
34
+ ')',
35
+ ];
36
+
37
+ if (options.deferred === true) {
38
+ sqlParts.push(' ');
39
+ sqlParts.push('DEFERRABLE INITIALLY DEFERRED');
40
+ }
41
+
42
+ if (options.onDelete) {
43
+ sqlParts.push(' ');
44
+ sqlParts.push(`ON DELETE ${options.onDelete.toUpperCase()}`);
45
+ }
46
+
47
+ if (options.onUpdate) {
48
+ sqlParts.push(' ');
49
+ sqlParts.push(`ON UPDATE ${options.onUpdate.toUpperCase()}`);
50
+ }
51
+
52
+ return sqlParts.join('');
53
+ }
54
+
55
+ // eslint-disable-next-line no-unused-vars
56
+ generateCreateTableStatementInnerTail(Model, options) {
57
+ let fieldParts = [];
58
+
59
+ Model.iterateFields(({ field }) => {
60
+ if (field.type.isVirtual())
61
+ return;
62
+
63
+ if (field.type.isForeignKey()) {
64
+ let result = this.generateForeignKeyConstraint(field, field.type);
65
+ if (result)
66
+ fieldParts.push(result);
67
+
68
+ return;
69
+ }
70
+ });
71
+
72
+ return fieldParts;
73
+ }
74
+
75
+ generateInsertStatementTail(Model, model, options, context) {
76
+ return this._collectReturningFields(Model, model, options, context);
77
+ }
78
+
79
+ generateUpdateStatementTail(Model, model, options, context) {
80
+ return this._collectReturningFields(Model, model, options, context);
81
+ }
82
+
83
+ generateCreateTableStatement(Model, _options) {
84
+ let options = _options || {};
85
+ let fieldParts = [];
86
+
87
+ Model.iterateFields(({ field, fieldName }) => {
88
+ if (field.type.isVirtual())
89
+ return;
90
+
91
+ let columnName = field.columnName || fieldName;
92
+ let constraintParts = [];
93
+
94
+ let defaultValue = this.getFieldDefaultValue(field, fieldName, { remoteOnly: true });
95
+
96
+ if (field.primaryKey) {
97
+ if (field.primaryKey instanceof LiteralBase)
98
+ constraintParts.push(field.primaryKey.toString(this.connection));
99
+ else
100
+ constraintParts.push('PRIMARY KEY');
101
+
102
+ if (defaultValue !== '@@@AUTOINCREMENT@@@')
103
+ constraintParts.push('NOT NULL');
104
+ } else {
105
+ if (field.unique) {
106
+ if (field.unique instanceof LiteralBase)
107
+ constraintParts.push(field.unique.toString(this.connection));
108
+ else
109
+ constraintParts.push('UNIQUE');
110
+ }
111
+
112
+ if (field.allowNull === false)
113
+ constraintParts.push('NOT NULL');
114
+ }
115
+
116
+ if (defaultValue !== undefined && defaultValue !== '@@@AUTOINCREMENT@@@')
117
+ constraintParts.push(defaultValue);
118
+
119
+ constraintParts = constraintParts.join(' ');
120
+ if (Nife.isNotEmpty(constraintParts))
121
+ constraintParts = ` ${constraintParts}`;
122
+
123
+ fieldParts.push(` ${this.escapeID(columnName)} ${field.type.toConnectionType(this.connection, { createTable: true, defaultValue })}${constraintParts}`);
124
+ });
125
+
126
+ let ifNotExists = 'IF NOT EXISTS ';
127
+ if (options.ifNotExists === false)
128
+ ifNotExists = '';
129
+
130
+ let trailingParts = Nife.toArray(this.generateCreateTableStatementInnerTail(Model, options)).filter(Boolean);
131
+ if (Nife.isNotEmpty(trailingParts))
132
+ fieldParts = fieldParts.concat(trailingParts.map((part) => ` ${part.trim()}`));
133
+
134
+ let finalStatement = `CREATE TABLE ${ifNotExists}${this.escapeID(Model.getTableName(this.connection))} (${fieldParts.join(',\n')}\n);`;
135
+ return finalStatement;
136
+ }
137
+
138
+ generateTruncateTableStatement(Model, _options) {
139
+ let options = _options || {};
140
+ let escapedTableName = this.escapeID(Model.getTableName(this.connection));
141
+
142
+ return `TRUNCATE TABLE${(options.onlySpecifiedTable === true) ? ' ONLY' : ''} ${escapedTableName}${(options.continueIdentity === true) ? ' CONTINUE IDENTITY' : ' RESTART IDENTITY'}${(options.cascade === false) ? ' RESTRICT' : ' CASCADE'}`;
143
+ }
144
+ }
145
+
146
+ module.exports = PostgreSQLQueryGenerator;
package/package.json ADDED
@@ -0,0 +1,58 @@
1
+ {
2
+ "name": "mythix-orm-postgresql",
3
+ "version": "1.0.1",
4
+ "description": "PostgreSQL driver for Mythix ORM",
5
+ "main": "lib/index.js",
6
+ "type": "commonjs",
7
+ "scripts": {
8
+ "coverage": "clear ; node ./node_modules/.bin/nyc ./node_modules/.bin/jasmine",
9
+ "test": "node ./node_modules/.bin/jasmine",
10
+ "test-debug": "node --inspect-brk ./node_modules/.bin/jasmine",
11
+ "test-watch": "watch 'clear ; node ./node_modules/.bin/jasmine' . --wait=2 --interval=1"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/th317erd/mythix-orm-postgresql.git"
16
+ },
17
+ "keywords": [
18
+ "orm",
19
+ "mysql",
20
+ "postgres",
21
+ "postgresql",
22
+ "mssql",
23
+ "mongo",
24
+ "snowflake",
25
+ "database",
26
+ "sql",
27
+ "no-sql"
28
+ ],
29
+ "author": "Wyatt Greenway",
30
+ "license": "MIT",
31
+ "bugs": {
32
+ "url": "https://github.com/th317erd/mythix-orm-postgresql/issues"
33
+ },
34
+ "homepage": "https://github.com/th317erd/mythix-orm-postgresql#readme",
35
+ "dependencies": {
36
+ "nife": "^1.11.2",
37
+ "pg": "^8.7.3",
38
+ "pg-format": "^1.0.4",
39
+ "uuid": "^8.3.2"
40
+ },
41
+ "devDependencies": {
42
+ "@spothero/eslint-plugin-spothero": "github:spothero/eslint-plugin-spothero",
43
+ "eslint": "^8.13.0",
44
+ "jasmine": "^4.3.0",
45
+ "moment": "^2.29.4",
46
+ "nyc": "^15.1.0"
47
+ },
48
+ "nyc": {
49
+ "reporter": [
50
+ "text",
51
+ "html"
52
+ ],
53
+ "exclude": [
54
+ "spec/**",
55
+ "lib/proxy-class/proxy-class.js"
56
+ ]
57
+ }
58
+ }