-
Notifications
You must be signed in to change notification settings - Fork 217
/
Copy pathdatabase.js
1675 lines (1620 loc) · 71.4 KB
/
database.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2015-present, Vitaly Tomilov
*
* See the LICENSE file at the top-level directory of this distribution
* for licensing information.
*
* Removal or modification of this copyright notice is prohibited.
*/
'use strict';
const npm = {
assertOptions: require('assert-options'),
result: require('./result'),
special: require('./special'),
Context: require('./cnContext'),
events: require('./events'),
utils: require('./utils'),
pubUtils: require('./utils/public'),
connect: require('./connect'),
dbPool: require('./dbPool'),
query: require('./query'),
task: require('./task'),
text: require('./text')
};
/**
* @class Database
* @description
*
* Represents the database protocol, extensible via event {@link event:extend extend}.
* This type is not available directly, it can only be created via the library's base call.
*
* **IMPORTANT:**
*
* For any given connection, you should only create a single {@link Database} object in a separate module,
* to be shared in your application (see the code example below). If instead you keep creating the {@link Database}
* object dynamically, your application will suffer from loss in performance, and will be getting a warning in a
* development environment (when `NODE_ENV` = `development`):
*
* `WARNING: Creating a duplicate database object for the same connection.`
*
* If you ever see this warning, rectify your {@link Database} object initialization, so there is only one object
* per connection details. See the example provided below.
*
* See also: property `noWarnings` in {@link module:pg-promise Initialization Options}.
*
* Note however, that in special cases you may need to re-create the database object, if its connection pool has been
* shut-down externally. And in this case the library won't be showing any warning.
*
* @param {string|object} cn
* Database connection details, which can be:
*
* - a configuration object
* - a connection string
*
* For details see {@link https://github.com/vitaly-t/pg-promise/wiki/Connection-Syntax Connection Syntax}.
*
* The value can be accessed from the database object via property {@link Database.$cn $cn}.
*
* @param {*} [dc]
* Database Context.
*
* Any object or value to be propagated through the protocol, to allow implementations and event handling
* that depend on the database context.
*
* This is mainly to facilitate the use of multiple databases which may need separate protocol extensions,
* or different implementations within a single task / transaction callback, depending on the database context.
*
* This parameter also adds uniqueness to the connection context that's used in combination with the connection
* parameters, i.e. use of unique database context will prevent getting the warning about creating a duplicate
* Database object.
*
* The value can be accessed from the database object via property {@link Database#$dc $dc}.
*
* @returns {Database}
*
* @see
*
* {@link Database#query query},
* {@link Database#none none},
* {@link Database#one one},
* {@link Database#oneOrNone oneOrNone},
* {@link Database#many many},
* {@link Database#manyOrNone manyOrNone},
* {@link Database#any any},
* {@link Database#func func},
* {@link Database#proc proc},
* {@link Database#result result},
* {@link Database#multiResult multiResult},
* {@link Database#multi multi},
* {@link Database#map map},
* {@link Database#each each},
* {@link Database#stream stream},
* {@link Database#task task},
* {@link Database#taskIf taskIf},
* {@link Database#tx tx},
* {@link Database#txIf txIf},
* {@link Database#connect connect},
* {@link Database#$config $config},
* {@link Database#$cn $cn},
* {@link Database#$dc $dc},
* {@link Database#$pool $pool},
* {@link event:extend extend}
*
* @example
* // Proper way to initialize and share the Database object
*
* // Loading and initializing the library:
* const pgp = require('pg-promise')({
* // Initialization Options
* });
*
* // Preparing the connection details:
* const cn = 'postgres://username:password@host:port/database';
*
* // Creating a new database instance from the connection details:
* const db = pgp(cn);
*
* // Exporting the database object for shared use:
* module.exports = db;
*/
function Database(cn, dc, config) {
const dbThis = this,
$p = config.promise,
poolConnection = typeof cn === 'string' ? {connectionString: cn} : cn,
pool = new config.pgp.pg.Pool(poolConnection),
endMethod = pool.end;
let destroyed;
pool.end = cb => {
const res = endMethod.call(pool, cb);
dbThis.$destroy();
return res;
};
pool.on('error', onError);
/**
* @method Database#connect
*
* @description
* Acquires a new or existing connection, depending on the current state of the connection pool, and parameter `direct`.
*
* This method creates a shared connection for executing a chain of queries against it. The connection must be released
* in the end of the chain by calling method `done()` on the connection object.
*
* It should not be used just for chaining queries on the same connection, methods {@link Database#task task} and
* {@link Database#tx tx} (for transactions) are to be used for that. This method is primarily for special cases, like
* `LISTEN` notifications.
*
* **NOTE:** Even though this method exposes a {@link external:Client Client} object via property `client`,
* you cannot call `client.end()` directly, or it will print an error into the console:
* `Abnormal client.end() call, due to invalid code or failed server connection.`
* You should only call method `done()` to release the connection.
*
* @param {object} [options]
* Connection Options.
*
* @param {boolean} [options.direct=false]
* Creates a new connection directly, as a stand-alone {@link external:Client Client} object, bypassing the connection pool.
*
* By default, all connections are acquired from the connection pool. But if you set this option, the library will instead
* create a new {@link external:Client Client} object directly (separately from the pool), and then call its `connect` method.
*
* **WARNING:**
*
* Do not use this option for regular query execution, because it exclusively occupies one physical channel, and it cannot scale.
* This option is only suitable for global connection usage, such as event listeners.
*
* @param {function} [options.onLost]
* Notification callback of the lost/broken connection, called with the following parameters:
* - `err` - the original connectivity error
* - `e` - error context object, which contains:
* - `cn` - safe connection string/config (with the password hashed);
* - `dc` - Database Context, as was used during {@link Database} construction;
* - `start` - Date/Time (`Date` type) when the connection was established;
* - `client` - {@link external:Client Client} object that has lost the connection.
*
* The notification is mostly valuable with `direct: true`, to be able to re-connect direct/permanent connections by calling
* method {@link Database#connect connect} again.
*
* You do not need to call `done` on lost connections, as it happens automatically. However, if you had event listeners
* set up on the connection's `client` object, you should remove them to avoid leaks:
*
* ```js
* function onLostConnection(err, e) {
* e.client.removeListener('my-event', myHandler);
* }
* ```
*
* For a complete example see $[Robust Listeners].
*
* @returns {external:Promise}
* A promise object that represents the connection result:
* - resolves with the complete {@link Database} protocol, extended with:
* - property `client` of type {@link external:Client Client} that represents the open connection
* - method `done()` that must be called in the end, in order to release the connection
* - methods `batch`, `page` and `sequence`, same as inside a {@link Task}
* - rejects with a connection-related error when it fails to connect.
*
* @see
* {@link Database#task Database.task},
* {@link Database#taskIf Database.taskIf},
* {@link Database#tx Database.tx},
* {@link Database#txIf Database.txIf}
*
* @example
*
* let sco; // shared connection object;
*
* db.connect()
* .then(obj => {
* // obj.client = new connected Client object;
*
* sco = obj; // save the connection object;
*
* // execute all the queries you need:
* return sco.any('SELECT * FROM Users');
* })
* .then(data => {
* // success
* })
* .catch(error => {
* // error
* })
* .finally(() => {
* // release the connection, if it was successful:
* if (sco) {
* sco.done();
* }
* });
*
*/
this.connect = function (options) {
options = options || {};
const ctx = createContext();
ctx.cnOptions = options;
const self = {
// Generic query method:
query(query, values, qrm) {
if (!ctx.db) {
return $p.reject(new Error(npm.text.queryDisconnected));
}
return config.$npm.query.call(this, ctx, query, values, qrm);
},
// Connection release method:
done() {
if (!ctx.db) {
throw new Error(npm.text.looseQuery);
}
ctx.disconnect();
},
batch(values, opt) {
return config.$npm.spex.batch.call(this, values, opt);
},
page(source, opt) {
return config.$npm.spex.page.call(this, source, opt);
},
sequence(source, opt) {
return config.$npm.spex.sequence.call(this, source, opt);
}
};
const connection = options.direct ? config.$npm.connect.direct(ctx) : config.$npm.connect.pool(ctx, dbThis);
return connection
.then(db => {
ctx.connect(db);
self.client = db.client;
extend(ctx, self);
return self;
});
};
/**
* @method Database#query
*
* @description
* Base query method that executes a generic query, expecting the return data according to parameter `qrm`.
*
* It performs the following steps:
*
* 1. Validates and formats the query via {@link formatting.format as.format}, according to the `query` and `values` passed in;
* 2. For a root-level query (against the {@link Database} object), it requests a new connection from the pool;
* 3. Executes the query;
* 4. For a root-level query (against the {@link Database} object), it releases the connection back to the pool;
* 5. Resolves/rejects, according to the data returned from the query and the value of `qrm`.
*
* Direct use of this method is not suitable for chaining queries, for performance reasons. It should be done
* through either task or transaction context, see $[Chaining Queries].
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @param {queryResult} [qrm=queryResult.any]
* {@link queryResult Query Result Mask}
*
* @returns {external:Promise}
* A promise object that represents the query result according to `qrm`.
*/
this.query = function (query, values, qrm) {
const self = this, ctx = createContext();
return config.$npm.connect.pool(ctx, dbThis)
.then(db => {
ctx.connect(db);
return config.$npm.query.call(self, ctx, query, values, qrm);
})
.then(data => {
ctx.disconnect();
return data;
})
.catch(error => {
ctx.disconnect();
return $p.reject(error);
});
};
/**
* @member {object} Database#$config
* @readonly
* @description
* This is a hidden property, to help integrating type {@link Database} directly with third-party libraries.
*
* Properties available in the object:
* - `pgp` - instance of the entire library after initialization
* - `options` - the library's {@link module:pg-promise Initialization Options} object
* - `promiseLib` - instance of the promise library that's used
* - `promise` - generic promise interface that uses `promiseLib` via 4 basic methods:
* - `promise((resolve, reject) => {})` - to create a new promise
* - `promise.resolve(value)` - to resolve with a value
* - `promise.reject(reason)` - to reject with a reason
* - `promise.all(iterable)` - to resolve an iterable list of promises
* - `version` - this library's version
* - `$npm` _(hidden property)_ - internal module cache
*
* @example
*
* // Using the promise protocol as configured by pg-promise:
*
* const $p = db.$config.promise;
*
* const resolvedPromise = $p.resolve('some data');
* const rejectedPromise = $p.reject('some reason');
*
* const newPromise = $p((resolve, reject) => {
* // call either resolve(data) or reject(reason) here
* });
*/
npm.utils.addReadProp(this, '$config', config, true);
/**
* @member {string|object} Database#$cn
* @readonly
* @description
* Database connection, as was passed in during the object's construction.
*
* This is a hidden property, to help integrating type {@link Database} directly with third-party libraries.
*
* @see Database
*/
npm.utils.addReadProp(this, '$cn', cn, true);
/**
* @member {*} Database#$dc
* @readonly
* @description
* Database Context, as was passed in during the object's construction.
*
* This is a hidden property, to help integrating type {@link Database} directly with third-party libraries.
*
* @see Database
*/
npm.utils.addReadProp(this, '$dc', dc, true);
/**
* @member {external:pg-pool} Database#$pool
* @readonly
* @description
* A $[pg-pool] object associated with the database object, as each {@link Database} creates its own $[pg-pool] instance.
*
* This is a hidden property, primarily for integrating type {@link Database} with third-party libraries that support
* $[pg-pool] directly. Note however, that if you pass the pool object into a library that calls `pool.end()`, you will no longer be able
* to use this {@link Database} object, and each query method will be rejecting with {@link external:Error Error} =
* `Connection pool of the database object has been destroyed.`
*
* You can also use this object to shut down the pool, by calling `$pool.end()`.
*
* For more details see $[Library de-initialization].
*
* @see
* {@link Database}
* {@link module:pg-promise~end pgp.end}
*
* @example
*
* // Shutting down the connection pool of this database object,
* // after all queries have finished in a run-though process:
*
* .then(() => {}) // processing the data
* .catch() => {}) // handling the error
* .finally(db.$pool.end); // shutting down the pool
*
*/
npm.utils.addReadProp(this, '$pool', pool, true);
/**
* @member {function} Database.$destroy
* @readonly
* @private
* @description
* Permanently shuts down the database object.
*/
npm.utils.addReadProp(this, '$destroy', () => {
if (!destroyed) {
if (!pool.ending) {
endMethod.call(pool);
}
npm.dbPool.unregister(dbThis);
pool.removeListener('error', onError);
destroyed = true;
}
}, true);
npm.dbPool.register(this);
extend(createContext(), this); // extending root protocol;
function createContext() {
return new npm.Context({cn, dc, options: config.options});
}
function transform(value, cb, thisArg) {
if (typeof cb === 'function') {
value = value.then(data => {
return cb.call(thisArg, data);
});
}
return value;
}
////////////////////////////////////////////////////
// Injects additional methods into an access object,
// extending the protocol's base method 'query'.
function extend(ctx, obj) {
/**
* @method Database#none
* @description
* Executes a query that expects no data to be returned. If the query returns any kind of data,
* the method rejects.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @returns {external:Promise<null>}
* A promise object that represents the query result:
* - When no records are returned, it resolves with `null`.
* - When any data is returned, it rejects with {@link errors.QueryResultError QueryResultError}:
* - `.message` = `No return data was expected.`
* - `.code` = {@link errors.queryResultErrorCode.notEmpty queryResultErrorCode.notEmpty}
*/
obj.none = function (query, values) {
return obj.query.call(this, query, values, npm.result.none);
};
/**
* @method Database#one
* @description
* Executes a query that expects exactly one row of data. When 0 or more than 1 rows are returned,
* the method rejects.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @param {function} [cb]
* Value transformation callback, to allow in-line value change.
* When specified, the return value replaces the original resolved value.
*
* The function takes only one parameter - value resolved from the query.
*
* @param {*} [thisArg]
* Value to use as `this` when executing the transformation callback.
*
* @returns {external:Promise}
* A promise object that represents the query result:
* - When 1 row is returned, it resolves with that row as a single object.
* - When no rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
* - `.message` = `No data returned from the query.`
* - `.code` = {@link errors.queryResultErrorCode.noData queryResultErrorCode.noData}
* - When multiple rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
* - `.message` = `Multiple rows were not expected.`
* - `.code` = {@link errors.queryResultErrorCode.multiple queryResultErrorCode.multiple}
* - Resolves with the new value, if transformation callback `cb` was specified.
*
* @see
* {@link Database#oneOrNone oneOrNone}
*
* @example
*
* // a query with in-line value transformation:
* db.one('INSERT INTO Events VALUES($1) RETURNING id', [123], event => event.id)
* .then(data => {
* // data = a new event id, rather than an object with it
* });
*
* @example
*
* // a query with in-line value transformation + conversion:
* db.one('SELECT count(*) FROM Users', [], c => +c.count)
* .then(count => {
* // count = a proper integer value, rather than an object with a string
* });
*
*/
obj.one = function (query, values, cb, thisArg) {
const v = obj.query.call(this, query, values, npm.result.one);
return transform(v, cb, thisArg);
};
/**
* @method Database#many
* @description
* Executes a query that expects one or more rows. When the query returns no rows, the method rejects.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @returns {external:Promise}
* A promise object that represents the query result:
* - When 1 or more rows are returned, it resolves with the array of rows.
* - When no rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
* - `.message` = `No data returned from the query.`
* - `.code` = {@link errors.queryResultErrorCode.noData queryResultErrorCode.noData}
*/
obj.many = function (query, values) {
return obj.query.call(this, query, values, npm.result.many);
};
/**
* @method Database#oneOrNone
* @description
* Executes a query that expects 0 or 1 rows, to resolve with the row-object when 1 row is returned,
* and with `null` when nothing is returned. When the query returns more than 1 row, the method rejects.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @param {function} [cb]
* Value transformation callback, to allow in-line value change.
* When specified, the return value replaces the original resolved value.
*
* The function takes only one parameter - value resolved from the query.
*
* @param {*} [thisArg]
* Value to use as `this` when executing the transformation callback.
*
* @returns {external:Promise}
* A promise object that represents the query result:
* - When no rows are returned, it resolves with `null`.
* - When 1 row is returned, it resolves with that row as a single object.
* - When multiple rows are returned, it rejects with {@link errors.QueryResultError QueryResultError}:
* - `.message` = `Multiple rows were not expected.`
* - `.code` = {@link errors.queryResultErrorCode.multiple queryResultErrorCode.multiple}
* - Resolves with the new value, if transformation callback `cb` was specified.
*
* @see
* {@link Database#one one},
* {@link Database#none none},
* {@link Database#manyOrNone manyOrNone}
*
* @example
*
* // a query with in-line value transformation:
* db.oneOrNone('SELECT id FROM Events WHERE type = $1', ['entry'], e => e && e.id)
* .then(data => {
* // data = the event id or null (rather than object or null)
* });
*
*/
obj.oneOrNone = function (query, values, cb, thisArg) {
const v = obj.query.call(this, query, values, npm.result.one | npm.result.none);
return transform(v, cb, thisArg);
};
/**
* @method Database#manyOrNone
* @description
* Executes a query that expects any number of rows.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @returns {external:Promise<Array>}
* A promise object that represents the query result:
* - When no rows are returned, it resolves with an empty array.
* - When 1 or more rows are returned, it resolves with the array of rows.
*
* @see
* {@link Database#any any},
* {@link Database#many many},
* {@link Database#none none}
*
*/
obj.manyOrNone = function (query, values) {
return obj.query.call(this, query, values, npm.result.many | npm.result.none);
};
/**
* @method Database#any
* @description
* Executes a query that expects any number of rows.
* This is simply a shorter alias for method {@link Database#manyOrNone manyOrNone}.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @returns {external:Promise<Array>}
* A promise object that represents the query result:
* - When no rows are returned, it resolves with an empty array.
* - When 1 or more rows are returned, it resolves with the array of rows.
*
* @see
* {@link Database#manyOrNone manyOrNone},
* {@link Database#map map},
* {@link Database#each each}
*
*/
obj.any = function (query, values) {
return obj.query.call(this, query, values, npm.result.any);
};
/**
* @method Database#result
* @description
* Executes a query without any expectation for the return data, to resolve with the
* original $[Result] object when successful.
*
* When receiving a multi-query result, only the last result is processed, ignoring the rest.
*
* @param {string|function|object} query
* Query to be executed, which can be any of the following types:
* - A non-empty query string
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @param {function} [cb]
* Value transformation callback, to allow in-line value change.
* When specified, the return value replaces the original resolved value.
*
* The function takes only one parameter - value resolved from the query.
*
* @param {*} [thisArg]
* Value to use as `this` when executing the transformation callback.
*
* @returns {external:Promise}
* A promise object that represents the query result:
* - resolves with the original $[Result] object (by default);
* - resolves with the new value, if transformation callback `cb` was specified.
*
* @example
*
* // use of value transformation:
* // deleting rows and returning the number of rows deleted
* db.result('DELETE FROM Events WHERE id = $1', [123], r => r.rowCount)
* .then(data => {
* // data = number of rows that were deleted
* });
*
* @example
*
* // use of value transformation:
* // getting only column details from a table
* db.result('SELECT * FROM Users LIMIT 0', null, r => r.fields)
* .then(data => {
* // data = array of column descriptors
* });
*
*/
obj.result = function (query, values, cb, thisArg) {
const v = obj.query.call(this, query, values, npm.special.cache.resultQuery);
return transform(v, cb, thisArg);
};
/**
* @method Database#multiResult
* @description
* Executes a multi-query string, without any expectation for the return data, to resolve with an array
* of the original $[Result] objects when successful.
*
* The operation is atomic, i.e. all queries are executed in a single transaction, unless there are explicit
* `BEGIN/COMMIT` commands included in the query string to divide it into multiple transactions.
*
* @param {string|function|object} query
* Multi-query string to be executed, which can be any of the following types:
* - A non-empty string that can contain any number of queries
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @returns {external:Promise<external:Result[]>}
*
* @see {@link Database#multi multi}
*
*/
obj.multiResult = function (query, values) {
return obj.query.call(this, query, values, npm.special.cache.multiResultQuery);
};
/**
* @method Database#multi
* @description
* Executes a multi-query string without any expectation for the return data, to resolve with an array
* of arrays of rows when successful.
*
* The operation is atomic, i.e. all queries are executed in a single transaction, unless there are explicit
* `BEGIN/COMMIT` commands included in the query string to divide it into multiple transactions.
*
* @param {string|function|object} query
* Multi-query string to be executed, which can be any of the following types:
* - A non-empty string that can contain any number of queries
* - A function that returns a query string or another function, i.e. recursive resolution
* is supported, passing in `values` as `this`, and as the first parameter.
* - Prepared Statement `{name, text, values, ...}` or {@link PreparedStatement} object
* - Parameterized Query `{text, values, ...}` or {@link ParameterizedQuery} object
* - {@link QueryFile} object
*
* @param {array|value} [values]
* Query formatting parameters.
*
* When `query` is of type `string` or a {@link QueryFile} object, the `values` can be:
* - a single value - to replace all `$1` occurrences
* - an array of values - to replace all `$1`, `$2`, ... variables
* - an object - to apply $[Named Parameters] formatting
*
* When `query` is a Prepared Statement or a Parameterized Query (or their class types),
* and `values` is not `null` or `undefined`, it is automatically set within such object,
* as an override for its internal `values`.
*
* @returns {external:Promise<Array<Array>>}
*
* @see {@link Database#multiResult multiResult}
*
* @example
*
* db.multi('SELECT * FROM users;SELECT * FROM products')
* .then(([users, products]) => {
* // we get data from all queries at once
* })
* .catch(error => {
* // error
* });
*/
obj.multi = function (query, values) {
return obj.query.call(this, query, values, npm.special.cache.multiResultQuery)
.then(data => data.map(a => a.rows));
};
/**
* @method Database#stream
* @description
* Custom data streaming, with the help of $[pg-query-stream].
*
* This method doesn't work with the $[Native Bindings], and if option `pgNative`
* is set, it will reject with `Streaming doesn't work with Native Bindings.`
*
* @param {QueryStream} qs
* Stream object of type $[QueryStream].
*
* @param {Database.streamInitCB} initCB
* Stream initialization callback.
*
* It is invoked with the same `this` context as the calling method.
*
* @returns {external:Promise}
* Result of the streaming operation.
*
* Once the streaming has finished successfully, the method resolves with
* `{processed, duration}`:
* - `processed` - total number of rows processed;
* - `duration` - streaming duration, in milliseconds.
*
* Possible rejections messages:
* - `Invalid or missing stream object.`
* - `Invalid stream state.`
* - `Invalid or missing stream initialization callback.`
*/
obj.stream = function (qs, init) {
return obj.query.call(this, qs, init, npm.special.cache.streamQuery);
};
/**
* @method Database#func
* @description
* Executes a query against a database function by its name: `SELECT * FROM funcName(values)`.
*
* @param {string} funcName
* Name of the function to be executed.
*
* @param {array|value} [values]
* Parameters for the function - one value or an array of values.
*
* @param {queryResult} [qrm=queryResult.any] - {@link queryResult Query Result Mask}.
*
* @returns {external:Promise}
*
* A promise object as returned from method {@link Database#query query}, according to parameter `qrm`.
*
* @see
* {@link Database#query query},
* {@link Database#proc proc}
*/
obj.func = function (funcName, values, qrm) {
return obj.query.call(this, {funcName}, values, qrm);
};
/**
* @method Database#proc
* @description
* Executes a query against a stored procedure via its name: `SELECT * FROM procName(values)`,
* expecting back 0 or 1 rows. It resolves either with the resulting row-object, or with
* `null` when none returned.
*
* The method simply forwards into {@link Database#func func}`(procName, values, queryResult.one|queryResult.none)`.
*
* @param {string} procName
* Name of the stored procedure to be executed.
*
* @param {array|value} [values]
* Parameters for the procedure - one value or an array of values.