knex 2.4.2 → 2.5.0

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.
Files changed (190) hide show
  1. package/CHANGELOG.md +54 -18
  2. package/CONTRIBUTING.md +194 -194
  3. package/LICENSE +22 -22
  4. package/README.md +147 -148
  5. package/UPGRADING.md +233 -233
  6. package/bin/cli.js +473 -473
  7. package/bin/utils/cli-config-utils.js +210 -210
  8. package/bin/utils/constants.js +7 -7
  9. package/bin/utils/migrationsLister.js +37 -37
  10. package/knex.js +23 -23
  11. package/knex.mjs +11 -0
  12. package/lib/builder-interface-augmenter.js +120 -120
  13. package/lib/client.js +495 -475
  14. package/lib/constants.js +61 -61
  15. package/lib/dialects/better-sqlite3/index.js +77 -72
  16. package/lib/dialects/cockroachdb/crdb-columncompiler.js +14 -14
  17. package/lib/dialects/cockroachdb/crdb-querybuilder.js +11 -11
  18. package/lib/dialects/cockroachdb/crdb-querycompiler.js +122 -122
  19. package/lib/dialects/cockroachdb/crdb-tablecompiler.js +37 -37
  20. package/lib/dialects/cockroachdb/crdb-viewcompiler.js +15 -15
  21. package/lib/dialects/cockroachdb/index.js +86 -86
  22. package/lib/dialects/index.js +33 -33
  23. package/lib/dialects/mssql/index.js +500 -495
  24. package/lib/dialects/mssql/mssql-formatter.js +34 -34
  25. package/lib/dialects/mssql/query/mssql-querycompiler.js +601 -600
  26. package/lib/dialects/mssql/schema/mssql-columncompiler.js +185 -185
  27. package/lib/dialects/mssql/schema/mssql-compiler.js +91 -91
  28. package/lib/dialects/mssql/schema/mssql-tablecompiler.js +378 -378
  29. package/lib/dialects/mssql/schema/mssql-viewcompiler.js +55 -55
  30. package/lib/dialects/mssql/transaction.js +176 -176
  31. package/lib/dialects/mysql/index.js +201 -201
  32. package/lib/dialects/mysql/query/mysql-querycompiler.js +274 -274
  33. package/lib/dialects/mysql/schema/mysql-columncompiler.js +193 -193
  34. package/lib/dialects/mysql/schema/mysql-compiler.js +60 -60
  35. package/lib/dialects/mysql/schema/mysql-tablecompiler.js +381 -381
  36. package/lib/dialects/mysql/schema/mysql-viewbuilder.js +21 -21
  37. package/lib/dialects/mysql/schema/mysql-viewcompiler.js +15 -15
  38. package/lib/dialects/mysql/transaction.js +46 -46
  39. package/lib/dialects/mysql2/index.js +53 -33
  40. package/lib/dialects/mysql2/transaction.js +44 -44
  41. package/lib/dialects/oracle/DEAD_CODE.md +5 -5
  42. package/lib/dialects/oracle/index.js +92 -92
  43. package/lib/dialects/oracle/query/oracle-querycompiler.js +343 -342
  44. package/lib/dialects/oracle/schema/internal/incrementUtils.js +20 -20
  45. package/lib/dialects/oracle/schema/internal/trigger.js +135 -135
  46. package/lib/dialects/oracle/schema/oracle-columnbuilder.js +17 -17
  47. package/lib/dialects/oracle/schema/oracle-columncompiler.js +126 -126
  48. package/lib/dialects/oracle/schema/oracle-compiler.js +122 -122
  49. package/lib/dialects/oracle/schema/oracle-tablecompiler.js +190 -190
  50. package/lib/dialects/oracle/utils.js +87 -87
  51. package/lib/dialects/oracledb/index.js +327 -327
  52. package/lib/dialects/oracledb/query/oracledb-querycompiler.js +481 -481
  53. package/lib/dialects/oracledb/schema/oracledb-columncompiler.js +61 -55
  54. package/lib/dialects/oracledb/schema/oracledb-tablecompiler.js +19 -19
  55. package/lib/dialects/oracledb/schema/oracledb-viewbuilder.js +13 -13
  56. package/lib/dialects/oracledb/schema/oracledb-viewcompiler.js +19 -19
  57. package/lib/dialects/oracledb/transaction.js +98 -98
  58. package/lib/dialects/oracledb/utils.js +208 -208
  59. package/lib/dialects/pgnative/index.js +60 -60
  60. package/lib/dialects/postgres/execution/pg-transaction.js +19 -12
  61. package/lib/dialects/postgres/index.js +358 -358
  62. package/lib/dialects/postgres/query/pg-querybuilder.js +43 -38
  63. package/lib/dialects/postgres/query/pg-querycompiler.js +400 -395
  64. package/lib/dialects/postgres/schema/pg-columncompiler.js +156 -156
  65. package/lib/dialects/postgres/schema/pg-compiler.js +138 -138
  66. package/lib/dialects/postgres/schema/pg-tablecompiler.js +304 -299
  67. package/lib/dialects/postgres/schema/pg-viewbuilder.js +21 -21
  68. package/lib/dialects/postgres/schema/pg-viewcompiler.js +35 -35
  69. package/lib/dialects/redshift/index.js +86 -86
  70. package/lib/dialects/redshift/query/redshift-querycompiler.js +163 -163
  71. package/lib/dialects/redshift/schema/redshift-columnbuilder.js +22 -22
  72. package/lib/dialects/redshift/schema/redshift-columncompiler.js +67 -67
  73. package/lib/dialects/redshift/schema/redshift-compiler.js +14 -14
  74. package/lib/dialects/redshift/schema/redshift-tablecompiler.js +122 -122
  75. package/lib/dialects/redshift/schema/redshift-viewcompiler.js +11 -11
  76. package/lib/dialects/redshift/transaction.js +32 -25
  77. package/lib/dialects/sqlite3/execution/sqlite-transaction.js +25 -18
  78. package/lib/dialects/sqlite3/index.js +250 -250
  79. package/lib/dialects/sqlite3/query/sqlite-querybuilder.js +33 -33
  80. package/lib/dialects/sqlite3/query/sqlite-querycompiler.js +334 -334
  81. package/lib/dialects/sqlite3/schema/ddl.js +400 -400
  82. package/lib/dialects/sqlite3/schema/internal/compiler.js +327 -327
  83. package/lib/dialects/sqlite3/schema/internal/parser-combinator.js +161 -161
  84. package/lib/dialects/sqlite3/schema/internal/parser.js +638 -638
  85. package/lib/dialects/sqlite3/schema/internal/sqlite-ddl-operations.js +41 -41
  86. package/lib/dialects/sqlite3/schema/internal/tokenizer.js +38 -38
  87. package/lib/dialects/sqlite3/schema/internal/utils.js +12 -12
  88. package/lib/dialects/sqlite3/schema/sqlite-columncompiler.js +50 -50
  89. package/lib/dialects/sqlite3/schema/sqlite-compiler.js +80 -80
  90. package/lib/dialects/sqlite3/schema/sqlite-tablecompiler.js +347 -347
  91. package/lib/dialects/sqlite3/schema/sqlite-viewcompiler.js +40 -40
  92. package/lib/execution/batch-insert.js +51 -51
  93. package/lib/execution/internal/delay.js +6 -6
  94. package/lib/execution/internal/ensure-connection-callback.js +41 -41
  95. package/lib/execution/internal/query-executioner.js +62 -62
  96. package/lib/execution/runner.js +325 -307
  97. package/lib/execution/transaction.js +409 -401
  98. package/lib/formatter/formatterUtils.js +42 -42
  99. package/lib/formatter/rawFormatter.js +84 -84
  100. package/lib/formatter/wrappingFormatter.js +250 -250
  101. package/lib/formatter.js +25 -25
  102. package/lib/index.js +3 -3
  103. package/lib/knex-builder/FunctionHelper.js +80 -54
  104. package/lib/knex-builder/Knex.js +59 -59
  105. package/lib/knex-builder/internal/config-resolver.js +57 -57
  106. package/lib/knex-builder/internal/parse-connection.js +87 -87
  107. package/lib/knex-builder/make-knex.js +345 -340
  108. package/lib/logger.js +76 -76
  109. package/lib/migrations/common/MigrationsLoader.js +36 -36
  110. package/lib/migrations/migrate/MigrationGenerator.js +84 -84
  111. package/lib/migrations/migrate/Migrator.js +598 -598
  112. package/lib/migrations/migrate/migrate-stub.js +17 -17
  113. package/lib/migrations/migrate/migration-list-resolver.js +33 -33
  114. package/lib/migrations/migrate/migrator-configuration-merger.js +58 -58
  115. package/lib/migrations/migrate/sources/fs-migrations.js +74 -74
  116. package/lib/migrations/migrate/stub/cjs.stub +15 -15
  117. package/lib/migrations/migrate/stub/coffee.stub +13 -13
  118. package/lib/migrations/migrate/stub/eg.stub +14 -14
  119. package/lib/migrations/migrate/stub/js-schema.stub +22 -22
  120. package/lib/migrations/migrate/stub/js.stub +22 -22
  121. package/lib/migrations/migrate/stub/knexfile-coffee.stub +34 -34
  122. package/lib/migrations/migrate/stub/knexfile-eg.stub +43 -43
  123. package/lib/migrations/migrate/stub/knexfile-js.stub +47 -47
  124. package/lib/migrations/migrate/stub/knexfile-ls.stub +35 -35
  125. package/lib/migrations/migrate/stub/knexfile-ts.stub +47 -47
  126. package/lib/migrations/migrate/stub/ls.stub +14 -14
  127. package/lib/migrations/migrate/stub/mjs.stub +23 -23
  128. package/lib/migrations/migrate/stub/ts-schema.stub +21 -21
  129. package/lib/migrations/migrate/stub/ts.stub +21 -21
  130. package/lib/migrations/migrate/table-creator.js +77 -77
  131. package/lib/migrations/migrate/table-resolver.js +27 -27
  132. package/lib/migrations/seed/Seeder.js +137 -137
  133. package/lib/migrations/seed/seed-stub.js +13 -13
  134. package/lib/migrations/seed/seeder-configuration-merger.js +60 -60
  135. package/lib/migrations/seed/sources/fs-seeds.js +65 -65
  136. package/lib/migrations/seed/stub/coffee.stub +9 -9
  137. package/lib/migrations/seed/stub/eg.stub +11 -11
  138. package/lib/migrations/seed/stub/js.stub +13 -13
  139. package/lib/migrations/seed/stub/ls.stub +11 -11
  140. package/lib/migrations/seed/stub/mjs.stub +12 -12
  141. package/lib/migrations/seed/stub/ts.stub +13 -13
  142. package/lib/migrations/util/fs.js +86 -86
  143. package/lib/migrations/util/import-file.js +12 -12
  144. package/lib/migrations/util/is-module-type.js +9 -9
  145. package/lib/migrations/util/template.js +52 -52
  146. package/lib/migrations/util/timestamp.js +14 -14
  147. package/lib/query/analytic.js +52 -52
  148. package/lib/query/constants.js +15 -15
  149. package/lib/query/joinclause.js +270 -270
  150. package/lib/query/method-constants.js +136 -135
  151. package/lib/query/querybuilder.js +1793 -1794
  152. package/lib/query/querycompiler.js +1591 -1580
  153. package/lib/raw.js +139 -139
  154. package/lib/ref.js +39 -39
  155. package/lib/schema/builder.js +115 -115
  156. package/lib/schema/columnbuilder.js +146 -146
  157. package/lib/schema/columncompiler.js +307 -307
  158. package/lib/schema/compiler.js +187 -187
  159. package/lib/schema/internal/helpers.js +55 -55
  160. package/lib/schema/tablebuilder.js +376 -376
  161. package/lib/schema/tablecompiler.js +433 -433
  162. package/lib/schema/viewbuilder.js +92 -92
  163. package/lib/schema/viewcompiler.js +138 -138
  164. package/lib/util/finally-mixin.js +13 -13
  165. package/lib/util/helpers.js +95 -95
  166. package/lib/util/is.js +32 -32
  167. package/lib/util/nanoid.js +40 -40
  168. package/lib/util/noop.js +1 -1
  169. package/lib/util/save-async-stack.js +14 -14
  170. package/lib/util/security.js +26 -0
  171. package/lib/util/string.js +190 -190
  172. package/lib/util/timeout.js +29 -29
  173. package/package.json +12 -10
  174. package/scripts/build.js +125 -125
  175. package/scripts/clean.js +31 -31
  176. package/scripts/docker-compose.yml +152 -152
  177. package/scripts/next-release-howto.md +24 -24
  178. package/scripts/oracledb-install-driver-libs.sh +82 -82
  179. package/scripts/release.sh +34 -34
  180. package/scripts/runkit-example.js +34 -34
  181. package/scripts/stress-test/README.txt +18 -18
  182. package/scripts/stress-test/docker-compose.yml +57 -57
  183. package/scripts/stress-test/knex-stress-test.js +208 -208
  184. package/scripts/stress-test/mysql2-random-hanging-every-now-and-then.js +145 -145
  185. package/scripts/stress-test/mysql2-sudden-exit-without-error.js +100 -100
  186. package/scripts/stress-test/reconnect-test-mysql-based-drivers.js +184 -184
  187. package/scripts/update_gitignore_for_tsc_output.js +90 -90
  188. package/types/index.d.ts +3273 -3233
  189. package/types/result.d.ts +27 -27
  190. package/types/tables.d.ts +4 -4
@@ -1,401 +1,409 @@
1
- // Transaction
2
- // -------
3
- const { EventEmitter } = require('events');
4
- const Debug = require('debug');
5
- const uniqueId = require('lodash/uniqueId');
6
- const { callbackify } = require('util');
7
-
8
- const makeKnex = require('../knex-builder/make-knex');
9
- const { timeout, KnexTimeoutError } = require('../util/timeout');
10
- const finallyMixin = require('../util/finally-mixin');
11
-
12
- const debug = Debug('knex:tx');
13
-
14
- // FYI: This is defined as a function instead of a constant so that
15
- // each Transactor can have its own copy of the default config.
16
- // This will minimize the impact of bugs that might be introduced
17
- // if a Transactor ever mutates its config.
18
- function DEFAULT_CONFIG() {
19
- return {
20
- userParams: {},
21
- doNotRejectOnRollback: true,
22
- };
23
- }
24
- // These aren't supported in sqlite3 which is serialized already so it's as
25
- // safe as reasonable, except for a special read_uncommitted pragma
26
- const validIsolationLevels = [
27
- // Doesn't really work in postgres, it treats it as read committed
28
- 'read uncommitted',
29
- 'read committed',
30
- 'snapshot',
31
- // snapshot and repeatable read are basically the same, most "repeatable
32
- // read" implementations are actually "snapshot" also known as Multi Version
33
- // Concurrency Control (MVCC). Mssql's repeatable read doesn't stop
34
- // repeated reads for inserts as it uses a pessimistic locking system so
35
- // you should probably use 'snapshot' to stop read skew.
36
- 'repeatable read',
37
- // mysql pretends to have serializable, but it is not
38
- 'serializable',
39
- ];
40
-
41
- // Acts as a facade for a Promise, keeping the internal state
42
- // and managing any child transactions.
43
- class Transaction extends EventEmitter {
44
- constructor(client, container, config = DEFAULT_CONFIG(), outerTx = null) {
45
- super();
46
- this.userParams = config.userParams;
47
- this.doNotRejectOnRollback = config.doNotRejectOnRollback;
48
-
49
- const txid = (this.txid = uniqueId('trx'));
50
-
51
- this.client = client;
52
- this.logger = client.logger;
53
- this.outerTx = outerTx;
54
- this.trxClient = undefined;
55
- this._completed = false;
56
- this._debug = client.config && client.config.debug;
57
-
58
- if (config.isolationLevel) {
59
- this.setIsolationLevel(config.isolationLevel);
60
- }
61
-
62
- debug(
63
- '%s: Starting %s transaction',
64
- txid,
65
- outerTx ? 'nested' : 'top level'
66
- );
67
-
68
- // `this` can potentially serve as an `outerTx` for another
69
- // Transaction. So, go ahead and establish `_lastChild` now.
70
- this._lastChild = Promise.resolve();
71
-
72
- const _previousSibling = outerTx ? outerTx._lastChild : Promise.resolve();
73
-
74
- // FYI: As you will see in a moment, this Promise will be used to construct
75
- // 2 separate Promise Chains. This ensures that each Promise Chain
76
- // can establish its error-handling semantics without interfering
77
- // with the other Promise Chain.
78
- const basePromise = _previousSibling.then(() =>
79
- this._evaluateContainer(config, container)
80
- );
81
-
82
- // FYI: This is the Promise Chain for EXTERNAL use. It ensures that the
83
- // caller must handle any exceptions that result from `basePromise`.
84
- this._promise = basePromise.then((x) => x);
85
-
86
- if (outerTx) {
87
- // FYI: This is the Promise Chain for INTERNAL use. It serves as a signal
88
- // for when the next sibling should begin its execution. Therefore,
89
- // exceptions are caught and ignored.
90
- outerTx._lastChild = basePromise.catch(() => {});
91
- }
92
- }
93
-
94
- isCompleted() {
95
- return (
96
- this._completed || (this.outerTx && this.outerTx.isCompleted()) || false
97
- );
98
- }
99
-
100
- begin(conn) {
101
- const runIsolationLevelQuery = this.isolationLevel
102
- ? this.query(
103
- conn,
104
- `SET TRANSACTION ISOLATION LEVEL ${this.isolationLevel};`
105
- )
106
- : Promise.resolve();
107
- return runIsolationLevelQuery.then(() => this.query(conn, 'BEGIN;'));
108
- }
109
-
110
- savepoint(conn) {
111
- return this.query(conn, `SAVEPOINT ${this.txid};`);
112
- }
113
-
114
- commit(conn, value) {
115
- return this.query(conn, 'COMMIT;', 1, value);
116
- }
117
-
118
- release(conn, value) {
119
- return this.query(conn, `RELEASE SAVEPOINT ${this.txid};`, 1, value);
120
- }
121
-
122
- setIsolationLevel(isolationLevel) {
123
- if (!validIsolationLevels.includes(isolationLevel)) {
124
- throw new Error(
125
- `Invalid isolationLevel, supported isolation levels are: ${JSON.stringify(
126
- validIsolationLevels
127
- )}`
128
- );
129
- }
130
- this.isolationLevel = isolationLevel;
131
- return this;
132
- }
133
-
134
- rollback(conn, error) {
135
- return timeout(this.query(conn, 'ROLLBACK', 2, error), 5000).catch(
136
- (err) => {
137
- if (!(err instanceof KnexTimeoutError)) {
138
- return Promise.reject(err);
139
- }
140
- this._rejecter(error);
141
- }
142
- );
143
- }
144
-
145
- rollbackTo(conn, error) {
146
- return timeout(
147
- this.query(conn, `ROLLBACK TO SAVEPOINT ${this.txid}`, 2, error),
148
- 5000
149
- ).catch((err) => {
150
- if (!(err instanceof KnexTimeoutError)) {
151
- return Promise.reject(err);
152
- }
153
- this._rejecter(error);
154
- });
155
- }
156
-
157
- query(conn, sql, status, value) {
158
- const q = this.trxClient
159
- .query(conn, sql)
160
- .catch((err) => {
161
- status = 2;
162
- value = err;
163
- this._completed = true;
164
- debug('%s error running transaction query', this.txid);
165
- })
166
- .then((res) => {
167
- if (status === 1) {
168
- this._resolver(value);
169
- }
170
- if (status === 2) {
171
- if (value === undefined) {
172
- if (this.doNotRejectOnRollback && /^ROLLBACK\b/i.test(sql)) {
173
- this._resolver();
174
- return;
175
- }
176
-
177
- value = new Error(`Transaction rejected with non-error: ${value}`);
178
- }
179
- this._rejecter(value);
180
- }
181
- return res;
182
- });
183
- if (status === 1 || status === 2) {
184
- this._completed = true;
185
- }
186
- return q;
187
- }
188
-
189
- debug(enabled) {
190
- this._debug = arguments.length ? enabled : true;
191
- return this;
192
- }
193
-
194
- async _evaluateContainer(config, container) {
195
- return this.acquireConnection(config, (connection) => {
196
- const trxClient = (this.trxClient = makeTxClient(
197
- this,
198
- this.client,
199
- connection
200
- ));
201
- const init = this.client.transacting
202
- ? this.savepoint(connection)
203
- : this.begin(connection);
204
- const executionPromise = new Promise((resolver, rejecter) => {
205
- this._resolver = resolver;
206
- this._rejecter = rejecter;
207
- });
208
-
209
- init
210
- .then(() => {
211
- return makeTransactor(this, connection, trxClient);
212
- })
213
- .then((transactor) => {
214
- transactor.executionPromise = executionPromise;
215
-
216
- // If we've returned a "thenable" from the transaction container, assume
217
- // the rollback and commit are chained to this object's success / failure.
218
- // Directly thrown errors are treated as automatic rollbacks.
219
- let result;
220
- try {
221
- result = container(transactor);
222
- } catch (err) {
223
- result = Promise.reject(err);
224
- }
225
- if (result && result.then && typeof result.then === 'function') {
226
- result
227
- .then((val) => {
228
- return transactor.commit(val);
229
- })
230
- .catch((err) => {
231
- return transactor.rollback(err);
232
- });
233
- }
234
- return null;
235
- })
236
- .catch((e) => {
237
- return this._rejecter(e);
238
- });
239
-
240
- return executionPromise;
241
- });
242
- }
243
-
244
- // Acquire a connection and create a disposer - either using the one passed
245
- // via config or getting one off the client. The disposer will be called once
246
- // the original promise is marked completed.
247
- async acquireConnection(config, cb) {
248
- const configConnection = config && config.connection;
249
- const connection =
250
- configConnection || (await this.client.acquireConnection());
251
-
252
- try {
253
- connection.__knexTxId = this.txid;
254
- return await cb(connection);
255
- } finally {
256
- if (!configConnection) {
257
- debug('%s: releasing connection', this.txid);
258
- this.client.releaseConnection(connection);
259
- } else {
260
- debug('%s: not releasing external connection', this.txid);
261
- }
262
- }
263
- }
264
-
265
- then(onResolve, onReject) {
266
- return this._promise.then(onResolve, onReject);
267
- }
268
-
269
- catch(...args) {
270
- return this._promise.catch(...args);
271
- }
272
-
273
- asCallback(cb) {
274
- callbackify(() => this._promise)(cb);
275
- return this._promise;
276
- }
277
- }
278
- finallyMixin(Transaction.prototype);
279
-
280
- // The transactor is a full featured knex object, with a "commit", a "rollback"
281
- // and a "savepoint" function. The "savepoint" is just sugar for creating a new
282
- // transaction. If the rollback is run inside a savepoint, it rolls back to the
283
- // last savepoint - otherwise it rolls back the transaction.
284
- function makeTransactor(trx, connection, trxClient) {
285
- const transactor = makeKnex(trxClient);
286
-
287
- transactor.context.withUserParams = () => {
288
- throw new Error(
289
- 'Cannot set user params on a transaction - it can only inherit params from main knex instance'
290
- );
291
- };
292
-
293
- transactor.isTransaction = true;
294
- transactor.userParams = trx.userParams || {};
295
-
296
- transactor.context.transaction = function (container, options) {
297
- if (!options) {
298
- options = { doNotRejectOnRollback: true };
299
- } else if (options.doNotRejectOnRollback === undefined) {
300
- options.doNotRejectOnRollback = true;
301
- }
302
-
303
- return this._transaction(container, options, trx);
304
- };
305
-
306
- transactor.savepoint = function (container, options) {
307
- return transactor.transaction(container, options);
308
- };
309
-
310
- if (trx.client.transacting) {
311
- transactor.commit = (value) => trx.release(connection, value);
312
- transactor.rollback = (error) => trx.rollbackTo(connection, error);
313
- } else {
314
- transactor.commit = (value) => trx.commit(connection, value);
315
- transactor.rollback = (error) => trx.rollback(connection, error);
316
- }
317
-
318
- transactor.isCompleted = () => trx.isCompleted();
319
-
320
- return transactor;
321
- }
322
-
323
- // We need to make a client object which always acquires the same
324
- // connection and does not release back into the pool.
325
- function makeTxClient(trx, client, connection) {
326
- const trxClient = Object.create(client.constructor.prototype);
327
- trxClient.version = client.version;
328
- trxClient.config = client.config;
329
- trxClient.driver = client.driver;
330
- trxClient.connectionSettings = client.connectionSettings;
331
- trxClient.transacting = true;
332
- trxClient.valueForUndefined = client.valueForUndefined;
333
- trxClient.logger = client.logger;
334
-
335
- trxClient.on('start', function (arg) {
336
- trx.emit('start', arg);
337
- client.emit('start', arg);
338
- });
339
-
340
- trxClient.on('query', function (arg) {
341
- trx.emit('query', arg);
342
- client.emit('query', arg);
343
- });
344
-
345
- trxClient.on('query-error', function (err, obj) {
346
- trx.emit('query-error', err, obj);
347
- client.emit('query-error', err, obj);
348
- });
349
-
350
- trxClient.on('query-response', function (response, obj, builder) {
351
- trx.emit('query-response', response, obj, builder);
352
- client.emit('query-response', response, obj, builder);
353
- });
354
-
355
- const _query = trxClient.query;
356
- trxClient.query = function (conn, obj) {
357
- const completed = trx.isCompleted();
358
- return new Promise(function (resolve, reject) {
359
- try {
360
- if (conn !== connection)
361
- throw new Error('Invalid connection for transaction query.');
362
- if (completed) completedError(trx, obj);
363
- resolve(_query.call(trxClient, conn, obj));
364
- } catch (e) {
365
- reject(e);
366
- }
367
- });
368
- };
369
- const _stream = trxClient.stream;
370
- trxClient.stream = function (conn, obj, stream, options) {
371
- const completed = trx.isCompleted();
372
- return new Promise(function (resolve, reject) {
373
- try {
374
- if (conn !== connection)
375
- throw new Error('Invalid connection for transaction query.');
376
- if (completed) completedError(trx, obj);
377
- resolve(_stream.call(trxClient, conn, obj, stream, options));
378
- } catch (e) {
379
- reject(e);
380
- }
381
- });
382
- };
383
- trxClient.acquireConnection = function () {
384
- return Promise.resolve(connection);
385
- };
386
- trxClient.releaseConnection = function () {
387
- return Promise.resolve();
388
- };
389
-
390
- return trxClient;
391
- }
392
-
393
- function completedError(trx, obj) {
394
- const sql = typeof obj === 'string' ? obj : obj && obj.sql;
395
- debug('%s: Transaction completed: %s', trx.txid, sql);
396
- throw new Error(
397
- 'Transaction query already complete, run with DEBUG=knex:tx for more info'
398
- );
399
- }
400
-
401
- module.exports = Transaction;
1
+ // Transaction
2
+ // -------
3
+ const { EventEmitter } = require('events');
4
+ const Debug = require('debug');
5
+ const uniqueId = require('lodash/uniqueId');
6
+ const { callbackify } = require('util');
7
+
8
+ const makeKnex = require('../knex-builder/make-knex');
9
+ const { timeout, KnexTimeoutError } = require('../util/timeout');
10
+ const finallyMixin = require('../util/finally-mixin');
11
+
12
+ const debug = Debug('knex:tx');
13
+
14
+ // FYI: This is defined as a function instead of a constant so that
15
+ // each Transactor can have its own copy of the default config.
16
+ // This will minimize the impact of bugs that might be introduced
17
+ // if a Transactor ever mutates its config.
18
+ function DEFAULT_CONFIG() {
19
+ return {
20
+ userParams: {},
21
+ doNotRejectOnRollback: true,
22
+ };
23
+ }
24
+ // These aren't supported in sqlite3 which is serialized already so it's as
25
+ // safe as reasonable, except for a special read_uncommitted pragma
26
+ const validIsolationLevels = [
27
+ // Doesn't really work in postgres, it treats it as read committed
28
+ 'read uncommitted',
29
+ 'read committed',
30
+ 'snapshot',
31
+ // snapshot and repeatable read are basically the same, most "repeatable
32
+ // read" implementations are actually "snapshot" also known as Multi Version
33
+ // Concurrency Control (MVCC). Mssql's repeatable read doesn't stop
34
+ // repeated reads for inserts as it uses a pessimistic locking system so
35
+ // you should probably use 'snapshot' to stop read skew.
36
+ 'repeatable read',
37
+ // mysql pretends to have serializable, but it is not
38
+ 'serializable',
39
+ ];
40
+
41
+ // Acts as a facade for a Promise, keeping the internal state
42
+ // and managing any child transactions.
43
+ class Transaction extends EventEmitter {
44
+ constructor(client, container, config = DEFAULT_CONFIG(), outerTx = null) {
45
+ super();
46
+ this.userParams = config.userParams;
47
+ this.doNotRejectOnRollback = config.doNotRejectOnRollback;
48
+
49
+ const txid = (this.txid = uniqueId('trx'));
50
+
51
+ this.client = client;
52
+ this.logger = client.logger;
53
+ this.outerTx = outerTx;
54
+ this.trxClient = undefined;
55
+ this._completed = false;
56
+ this._debug = client.config && client.config.debug;
57
+
58
+ this.readOnly = config.readOnly;
59
+ if (config.isolationLevel) {
60
+ this.setIsolationLevel(config.isolationLevel);
61
+ }
62
+
63
+ debug(
64
+ '%s: Starting %s transaction',
65
+ txid,
66
+ outerTx ? 'nested' : 'top level'
67
+ );
68
+
69
+ // `this` can potentially serve as an `outerTx` for another
70
+ // Transaction. So, go ahead and establish `_lastChild` now.
71
+ this._lastChild = Promise.resolve();
72
+
73
+ const _previousSibling = outerTx ? outerTx._lastChild : Promise.resolve();
74
+
75
+ // FYI: As you will see in a moment, this Promise will be used to construct
76
+ // 2 separate Promise Chains. This ensures that each Promise Chain
77
+ // can establish its error-handling semantics without interfering
78
+ // with the other Promise Chain.
79
+ const basePromise = _previousSibling.then(() =>
80
+ this._evaluateContainer(config, container)
81
+ );
82
+
83
+ // FYI: This is the Promise Chain for EXTERNAL use. It ensures that the
84
+ // caller must handle any exceptions that result from `basePromise`.
85
+ this._promise = basePromise.then((x) => x);
86
+
87
+ if (outerTx) {
88
+ // FYI: This is the Promise Chain for INTERNAL use. It serves as a signal
89
+ // for when the next sibling should begin its execution. Therefore,
90
+ // exceptions are caught and ignored.
91
+ outerTx._lastChild = basePromise.catch(() => {});
92
+ }
93
+ }
94
+
95
+ isCompleted() {
96
+ return (
97
+ this._completed || (this.outerTx && this.outerTx.isCompleted()) || false
98
+ );
99
+ }
100
+
101
+ begin(conn) {
102
+ const trxMode = [
103
+ this.isolationLevel ? `ISOLATION LEVEL ${this.isolationLevel}` : '',
104
+ this.readOnly ? 'READ ONLY' : '',
105
+ ]
106
+ .join(' ')
107
+ .trim();
108
+
109
+ if (trxMode.length === 0) {
110
+ return this.query(conn, 'BEGIN;');
111
+ }
112
+
113
+ return this.query(conn, `SET TRANSACTION ${trxMode};`).then(() =>
114
+ this.query(conn, 'BEGIN;')
115
+ );
116
+ }
117
+
118
+ savepoint(conn) {
119
+ return this.query(conn, `SAVEPOINT ${this.txid};`);
120
+ }
121
+
122
+ commit(conn, value) {
123
+ return this.query(conn, 'COMMIT;', 1, value);
124
+ }
125
+
126
+ release(conn, value) {
127
+ return this.query(conn, `RELEASE SAVEPOINT ${this.txid};`, 1, value);
128
+ }
129
+
130
+ setIsolationLevel(isolationLevel) {
131
+ if (!validIsolationLevels.includes(isolationLevel)) {
132
+ throw new Error(
133
+ `Invalid isolationLevel, supported isolation levels are: ${JSON.stringify(
134
+ validIsolationLevels
135
+ )}`
136
+ );
137
+ }
138
+ this.isolationLevel = isolationLevel;
139
+ return this;
140
+ }
141
+
142
+ rollback(conn, error) {
143
+ return timeout(this.query(conn, 'ROLLBACK', 2, error), 5000).catch(
144
+ (err) => {
145
+ if (!(err instanceof KnexTimeoutError)) {
146
+ return Promise.reject(err);
147
+ }
148
+ this._rejecter(error);
149
+ }
150
+ );
151
+ }
152
+
153
+ rollbackTo(conn, error) {
154
+ return timeout(
155
+ this.query(conn, `ROLLBACK TO SAVEPOINT ${this.txid}`, 2, error),
156
+ 5000
157
+ ).catch((err) => {
158
+ if (!(err instanceof KnexTimeoutError)) {
159
+ return Promise.reject(err);
160
+ }
161
+ this._rejecter(error);
162
+ });
163
+ }
164
+
165
+ query(conn, sql, status, value) {
166
+ const q = this.trxClient
167
+ .query(conn, sql)
168
+ .catch((err) => {
169
+ status = 2;
170
+ value = err;
171
+ this._completed = true;
172
+ debug('%s error running transaction query', this.txid);
173
+ })
174
+ .then((res) => {
175
+ if (status === 1) {
176
+ this._resolver(value);
177
+ }
178
+ if (status === 2) {
179
+ if (value === undefined) {
180
+ if (this.doNotRejectOnRollback && /^ROLLBACK\b/i.test(sql)) {
181
+ this._resolver();
182
+ return;
183
+ }
184
+
185
+ value = new Error(`Transaction rejected with non-error: ${value}`);
186
+ }
187
+ this._rejecter(value);
188
+ }
189
+ return res;
190
+ });
191
+ if (status === 1 || status === 2) {
192
+ this._completed = true;
193
+ }
194
+ return q;
195
+ }
196
+
197
+ debug(enabled) {
198
+ this._debug = arguments.length ? enabled : true;
199
+ return this;
200
+ }
201
+
202
+ async _evaluateContainer(config, container) {
203
+ return this.acquireConnection(config, (connection) => {
204
+ const trxClient = (this.trxClient = makeTxClient(
205
+ this,
206
+ this.client,
207
+ connection
208
+ ));
209
+ const init = this.client.transacting
210
+ ? this.savepoint(connection)
211
+ : this.begin(connection);
212
+ const executionPromise = new Promise((resolver, rejecter) => {
213
+ this._resolver = resolver;
214
+ this._rejecter = rejecter;
215
+ });
216
+
217
+ init
218
+ .then(() => {
219
+ return makeTransactor(this, connection, trxClient);
220
+ })
221
+ .then((transactor) => {
222
+ transactor.executionPromise = executionPromise;
223
+
224
+ // If we've returned a "thenable" from the transaction container, assume
225
+ // the rollback and commit are chained to this object's success / failure.
226
+ // Directly thrown errors are treated as automatic rollbacks.
227
+ let result;
228
+ try {
229
+ result = container(transactor);
230
+ } catch (err) {
231
+ result = Promise.reject(err);
232
+ }
233
+ if (result && result.then && typeof result.then === 'function') {
234
+ result
235
+ .then((val) => {
236
+ return transactor.commit(val);
237
+ })
238
+ .catch((err) => {
239
+ return transactor.rollback(err);
240
+ });
241
+ }
242
+ return null;
243
+ })
244
+ .catch((e) => {
245
+ return this._rejecter(e);
246
+ });
247
+
248
+ return executionPromise;
249
+ });
250
+ }
251
+
252
+ // Acquire a connection and create a disposer - either using the one passed
253
+ // via config or getting one off the client. The disposer will be called once
254
+ // the original promise is marked completed.
255
+ async acquireConnection(config, cb) {
256
+ const configConnection = config && config.connection;
257
+ const connection =
258
+ configConnection || (await this.client.acquireConnection());
259
+
260
+ try {
261
+ connection.__knexTxId = this.txid;
262
+ return await cb(connection);
263
+ } finally {
264
+ if (!configConnection) {
265
+ debug('%s: releasing connection', this.txid);
266
+ this.client.releaseConnection(connection);
267
+ } else {
268
+ debug('%s: not releasing external connection', this.txid);
269
+ }
270
+ }
271
+ }
272
+
273
+ then(onResolve, onReject) {
274
+ return this._promise.then(onResolve, onReject);
275
+ }
276
+
277
+ catch(...args) {
278
+ return this._promise.catch(...args);
279
+ }
280
+
281
+ asCallback(cb) {
282
+ callbackify(() => this._promise)(cb);
283
+ return this._promise;
284
+ }
285
+ }
286
+ finallyMixin(Transaction.prototype);
287
+
288
+ // The transactor is a full featured knex object, with a "commit", a "rollback"
289
+ // and a "savepoint" function. The "savepoint" is just sugar for creating a new
290
+ // transaction. If the rollback is run inside a savepoint, it rolls back to the
291
+ // last savepoint - otherwise it rolls back the transaction.
292
+ function makeTransactor(trx, connection, trxClient) {
293
+ const transactor = makeKnex(trxClient);
294
+
295
+ transactor.context.withUserParams = () => {
296
+ throw new Error(
297
+ 'Cannot set user params on a transaction - it can only inherit params from main knex instance'
298
+ );
299
+ };
300
+
301
+ transactor.isTransaction = true;
302
+ transactor.userParams = trx.userParams || {};
303
+
304
+ transactor.context.transaction = function (container, options) {
305
+ if (!options) {
306
+ options = { doNotRejectOnRollback: true };
307
+ } else if (options.doNotRejectOnRollback === undefined) {
308
+ options.doNotRejectOnRollback = true;
309
+ }
310
+
311
+ return this._transaction(container, options, trx);
312
+ };
313
+
314
+ transactor.savepoint = function (container, options) {
315
+ return transactor.transaction(container, options);
316
+ };
317
+
318
+ if (trx.client.transacting) {
319
+ transactor.commit = (value) => trx.release(connection, value);
320
+ transactor.rollback = (error) => trx.rollbackTo(connection, error);
321
+ } else {
322
+ transactor.commit = (value) => trx.commit(connection, value);
323
+ transactor.rollback = (error) => trx.rollback(connection, error);
324
+ }
325
+
326
+ transactor.isCompleted = () => trx.isCompleted();
327
+
328
+ return transactor;
329
+ }
330
+
331
+ // We need to make a client object which always acquires the same
332
+ // connection and does not release back into the pool.
333
+ function makeTxClient(trx, client, connection) {
334
+ const trxClient = Object.create(client.constructor.prototype);
335
+ trxClient.version = client.version;
336
+ trxClient.config = client.config;
337
+ trxClient.driver = client.driver;
338
+ trxClient.connectionSettings = client.connectionSettings;
339
+ trxClient.transacting = true;
340
+ trxClient.valueForUndefined = client.valueForUndefined;
341
+ trxClient.logger = client.logger;
342
+
343
+ trxClient.on('start', function (arg) {
344
+ trx.emit('start', arg);
345
+ client.emit('start', arg);
346
+ });
347
+
348
+ trxClient.on('query', function (arg) {
349
+ trx.emit('query', arg);
350
+ client.emit('query', arg);
351
+ });
352
+
353
+ trxClient.on('query-error', function (err, obj) {
354
+ trx.emit('query-error', err, obj);
355
+ client.emit('query-error', err, obj);
356
+ });
357
+
358
+ trxClient.on('query-response', function (response, obj, builder) {
359
+ trx.emit('query-response', response, obj, builder);
360
+ client.emit('query-response', response, obj, builder);
361
+ });
362
+
363
+ const _query = trxClient.query;
364
+ trxClient.query = function (conn, obj) {
365
+ const completed = trx.isCompleted();
366
+ return new Promise(function (resolve, reject) {
367
+ try {
368
+ if (conn !== connection)
369
+ throw new Error('Invalid connection for transaction query.');
370
+ if (completed) completedError(trx, obj);
371
+ resolve(_query.call(trxClient, conn, obj));
372
+ } catch (e) {
373
+ reject(e);
374
+ }
375
+ });
376
+ };
377
+ const _stream = trxClient.stream;
378
+ trxClient.stream = function (conn, obj, stream, options) {
379
+ const completed = trx.isCompleted();
380
+ return new Promise(function (resolve, reject) {
381
+ try {
382
+ if (conn !== connection)
383
+ throw new Error('Invalid connection for transaction query.');
384
+ if (completed) completedError(trx, obj);
385
+ resolve(_stream.call(trxClient, conn, obj, stream, options));
386
+ } catch (e) {
387
+ reject(e);
388
+ }
389
+ });
390
+ };
391
+ trxClient.acquireConnection = function () {
392
+ return Promise.resolve(connection);
393
+ };
394
+ trxClient.releaseConnection = function () {
395
+ return Promise.resolve();
396
+ };
397
+
398
+ return trxClient;
399
+ }
400
+
401
+ function completedError(trx, obj) {
402
+ const sql = typeof obj === 'string' ? obj : obj && obj.sql;
403
+ debug('%s: Transaction completed: %s', trx.txid, sql);
404
+ throw new Error(
405
+ 'Transaction query already complete, run with DEBUG=knex:tx for more info'
406
+ );
407
+ }
408
+
409
+ module.exports = Transaction;