/
database.js
1734 lines (1718 loc) · 53.5 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 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const arrify = require('arrify');
const {promisifyAll} = require('@google-cloud/promisify');
const {ServiceObject} = require('@google-cloud/common-grpc');
const extend = require('extend');
const is = require('is');
const retry = require('p-retry');
const streamEvents = require('stream-events');
const through = require('through2');
const BatchTransaction = require('./batch-transaction');
const codec = require('./codec');
const PartialResultStream = require('./partial-result-stream');
const Session = require('./session');
const SessionPool = require('./session-pool');
const Table = require('./table');
const Transaction = require('./transaction');
const TransactionRequest = require('./transaction-request');
/**
* Interface for implementing custom session pooling logic, it should extend the
* {@link https://nodejs.org/api/events.html|EventEmitter} class and emit any
* asynchronous errors via an error event.
*
* @interface SessionPoolCtor
* @extends external:{@link https://nodejs.org/api/events.html|EventEmitter}
*/
/**
* @constructs SessionPoolCtor
* @param {Database} database The database to create a pool for.
*/
/**
* Will be called by the Database object, should be used to start creating
* sessions/etc.
*
* @name SessionPoolCtor#open
*/
/**
* Will be called via {@link Database#close}. Indicates that the pool should
* perform any necessary teardown actions to its resources.
*
* @name SessionPoolCtor#close
* @param {BasicCallback} callback The callback function.
*/
/**
* @callback GetReadSessionCallback
* @param {?Error} error Request error, if any.
* @param {Session} session The read-only session.
*/
/**
* When called returns a read-only session.
*
* @name SessionPoolCtor#getReadSession
* @param {GetReadSessionCallback} callback The callback function.
*/
/**
* @callback GetWriteSessionCallback
* @param {?Error} error Request error, if any.
* @param {Session} session The read-write session.
* @param {Transaction} transaction The transaction object.
*/
/**
* When called returns a read-write session with prepared transaction.
*
* @name SessionPoolCtor#getWriteSession
* @param {GetWriteSessionCallback} callback The callback function.
*/
/**
* To be called when releasing a session back into the pool.
*
* @name SessionPoolCtor#release
* @param {Session} session The session to be released.
*/
/**
* Create a Database object to interact with a Cloud Spanner database.
*
* @class
*
* @param {string} name Name of the database.
* @param {SessionPoolOptions|SessionPoolCtor} options Session pool
* configuration options or custom pool interface.
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*/
class Database extends ServiceObject {
constructor(instance, name, poolOptions) {
const methods = {
/**
* Create a database.
*
* @method Database#create
* @param {CreateDatabaseRequest} [options] Configuration object.
* @param {CreateDatabaseCallback} [callback] Callback function.
* @returns {Promise<CreateDatabaseResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.create(function(err, database, operation, apiResponse) {
* if (err) {
* // Error handling omitted.
* }
*
* operation
* .on('error', function(err) {})
* .on('complete', function() {
* // Database created successfully.
* });
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.create()
* .then(function(data) {
* const operation = data[0];
* const apiResponse = data[1];
*
* return operation.promise();
* })
* .then(function() {
* // Database created successfully.
* });
*/
create: true,
};
const formattedName_ = Database.formatName_(instance.formattedName_, name);
super({
parent: instance,
id: name,
methods: methods,
createMethod: (_, options, callback) => {
return instance.createDatabase(formattedName_, options, callback);
},
});
this.formattedName_ = formattedName_;
this.request = instance.request;
this.requestStream = instance.requestStream;
let PoolCtor = SessionPool;
if (is.fn(poolOptions)) {
PoolCtor = poolOptions;
poolOptions = null;
}
this.pool_ = new PoolCtor(this, poolOptions);
this.pool_.on('error', this.emit.bind(this, 'error'));
this.pool_.open();
}
/**
* Get a reference to a {@link BatchTransaction} object.
*
* @see {@link BatchTransaction#identifier} to generate an identifier.
*
* @param {TransactionIdentifier} identifier The transaction identifier.
* @param {TransactionOptions} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds).
* @returns {BatchTransaction} A batch transaction object.
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* const transaction = database.batchTransaction({
* session: 'my-session',
* transaction: 'my-transaction',
* readTimestamp: 1518464696657
* });
*/
batchTransaction(identifier) {
let session = identifier.session;
const id = identifier.transaction;
if (is.string(session)) {
session = this.session(session);
}
const transaction = new BatchTransaction(session);
transaction.id = id;
transaction.readTimestamp = identifier.readTimestamp;
return transaction;
}
/**
* @callback CloseDatabaseCallback
* @param {?Error} err Request error, if any.
*/
/**
* Close the database connection and destroy all sessions associated with it.
*
* @param {CloseDatabaseCallback} [callback] Callback function.
* @returns {Promise}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.close(function(err) {
* if (err) {
* // Error handling omitted.
* }
* });
*
* //-
* // In the event of a session leak, the error object will contain a
* // `messages` field.
* //-
* database.close(function(err) {
* if (err && err.messages) {
* err.messages.forEach(function(message) {
* console.error(message);
* });
* }
* });
*/
close(callback) {
const key = this.id.split('/').pop();
this.parent.databases_.delete(key);
this.pool_.close(callback);
}
/**
* @typedef {array} CreateTransactionResponse
* @property {BatchTransaction} 0 The {@link BatchTransaction}.
* @property {object} 1 The full API response.
*/
/**
* @callback CreateTransactionCallback
* @param {?Error} err Request error, if any.
* @param {BatchTransaction} transaction The {@link BatchTransaction}.
* @param {object} apiResponse The full API response.
*/
/**
* Create a transaction that can be used for batch querying.
*
* @param {TransactionOptions} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds).
* @param {CreateTransactionCallback} [callback] Callback function.
* @returns {Promise<CreateTransactionResponse>}
*/
createBatchTransaction(options, callback) {
if (is.fn(options)) {
callback = options;
options = null;
}
this.createSession((err, session, resp) => {
if (err) {
callback(err, null, resp);
return;
}
const transaction = this.batchTransaction({session});
transaction.options = extend({}, options);
transaction.begin((err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
callback(null, transaction, resp);
});
});
}
/**
* @typedef {array} CreateSessionResponse
* @property {Session} 0 The newly created session.
* @property {object} 2 The full API response.
*/
/**
* @callback CreateSessionCallback
* @param {?Error} err Request error, if any.
* @param {Session} session The newly created session.
* @param {object} apiResponse The full API response.
*/
/**
* Create a new session, which can be used to perform transactions that read
* and/or modify data.
*
* Sessions can only execute one transaction at a time. To execute multiple
* concurrent read-write/write-only transactions, create multiple sessions.
* Note that standalone reads and queries use a transaction internally, and
* count toward the one transaction limit.
*
* **It is unlikely you will need to interact with sessions directly. By
* default, sessions are created and utilized for maximum performance
* automatically.**
*
* Wrapper around {@link v1.SpannerClient#createSession}.
*
* @see {@link v1.SpannerClient#createSession}
* @see [CreateSession API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.CreateSession)
*
* @param {object} [options] Configuration object.
* @param {CreateSessionCallback} [callback] Callback function.
* @returns {Promise<CreateSessionResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.createSession(function(err, session, apiResponse) {
* if (err) {
* // Error handling omitted.
* }
*
* // `session` is a Session object.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.createSession().then(function(data) {
* const session = data[0];
* const apiResponse = data[1];
* });
*/
createSession(options, callback) {
if (is.function(options)) {
callback = options;
options = {};
}
const gaxOpts = extend({}, options);
const reqOpts = {
database: this.formattedName_,
};
if (gaxOpts.labels) {
reqOpts.session = {labels: gaxOpts.labels};
delete gaxOpts.labels;
}
this.request(
{
client: 'SpannerClient',
method: 'createSession',
reqOpts: reqOpts,
gaxOpts: gaxOpts,
},
(err, resp) => {
if (err) {
callback(err, null, resp);
return;
}
const session = this.session(resp.name);
session.metadata = resp;
callback(null, session, resp);
}
);
}
/**
* @typedef {array} CreateTableResponse
* @property {Table} 0 The new {@link Table}.
* @property {Operation} 1 An {@link Operation} object that can be used to check
* the status of the request.
* @property {object} 2 The full API response.
*/
/**
* @callback CreateTableCallback
* @param {?Error} err Request error, if any.
* @param {Table} table The new {@link Table}.
* @param {Operation} operation An {@link Operation} object that can be used to
* check the status of the request.
* @param {object} apiResponse The full API response.
*/
/**
* Create a table.
*
* Wrapper around {@link Database#updateSchema}.
*
* @see {@link Database#updateSchema}
*
* @param {string} schema A DDL CREATE statement describing the table.
* @param {CreateTableCallback} [callback] Callback function.
* @returns {Promise<CreateTableResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* const schema =
* 'CREATE TABLE Singers (' +
* ' SingerId INT64 NOT NULL,' +
* ' FirstName STRING(1024),' +
* ' LastName STRING(1024),' +
* ' SingerInfo BYTES(MAX),' +
* ') PRIMARY KEY(SingerId)';
*
* database.createTable(schema, function(err, table, operation, apiResponse) {
* if (err) {
* // Error handling omitted.
* }
*
* operation
* .on('error', function(err) {})
* .on('complete', function() {
* // Table created successfully.
* });
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.createTable(schema)
* .then(function(data) {
* const table = data[0];
* const operation = data[1];
*
* return operation.promise();
* })
* .then(function() {
* // Table created successfully.
* });
*/
createTable(schema, callback) {
this.updateSchema(schema, (err, operation, resp) => {
if (err) {
callback(err, null, null, resp);
return;
}
const tableName = schema.match(/CREATE TABLE `*([^\s`(]+)/)[1];
const table = this.table(tableName);
callback(null, table, operation, resp);
});
}
/**
* Decorates transaction so that when end() is called it will return the session
* back into the pool.
*
* @private
*
* @param {Transaction} transaction The transaction to decorate.
* @param {Session} session The session to release.
* @returns {Transaction}
*/
decorateTransaction_(transaction, session) {
const self = this;
const end = transaction.end.bind(transaction);
transaction.end = function(callback) {
self.pool_.release(session);
return end(callback);
};
return transaction;
}
/**
* Delete the database.
*
* Wrapper around {@link v1.DatabaseAdminClient#dropDatabase}.
*
* @see {@link v1.DatabaseAdminClient#dropDatabase}
* @see [DropDatabase API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase)
* @param {BasicCallback} [callback] Callback function.
* @returns {Promise<BasicResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.delete(function(err, apiResponse) {
* if (err) {
* // Error handling omitted.
* }
*
* // Database was deleted successfully.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.delete().then(function(data) {
* const apiResponse = data[0];
* });
*/
delete(callback) {
const reqOpts = {
database: this.formattedName_,
};
this.close(() => {
this.request(
{
client: 'DatabaseAdminClient',
method: 'dropDatabase',
reqOpts: reqOpts,
},
callback
);
});
}
/**
* @typedef {array} DatabaseExistsResponse
* @property {boolean} 0 Whether the {@link Database} exists.
*/
/**
* @callback DatabaseExistsCallback
* @param {?Error} err Request error, if any.
* @param {boolean} exists Whether the {@link Database} exists.
*/
/**
* Check if a database exists.
*
* @method Database#exists
* @param {DatabaseExistsCallback} [callback] Callback function.
* @returns {Promise<DatabaseExistsResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.exists(function(err, exists) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.exists().then(function(data) {
* const exists = data[0];
* });
*/
exists(callback) {
const NOT_FOUND = 5;
this.getMetadata(err => {
if (err && err.code !== NOT_FOUND) {
callback(err, null);
return;
}
const exists = !err || err.code !== NOT_FOUND;
callback(null, exists);
});
}
/**
* @typedef {array} GetDatabaseResponse
* @property {Database} 0 The {@link Database}.
* @property {object} 1 The full API response.
*/
/**
* @callback GetDatabaseCallback
* @param {?Error} err Request error, if any.
* @param {Database} database The {@link Database}.
* @param {object} apiResponse The full API response.
*/
/**
* Get a database if it exists.
*
* You may optionally use this to "get or create" an object by providing an
* object with `autoCreate` set to `true`. Any extra configuration that is
* normally required for the `create` method must be contained within this
* object as well.
*
* @param {options} [options] Configuration object.
* @param {boolean} [options.autoCreate=false] Automatically create the
* object if it does not exist.
* @param {GetDatabaseCallback} [callback] Callback function.
* @returns {Promise<GetDatabaseResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.get(function(err, database, apiResponse) {
* // `database.metadata` has been populated.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.get().then(function(data) {
* const database = data[0];
* const apiResponse = data[0];
* });
*/
get(options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
this.getMetadata((err, metadata) => {
if (err) {
if (options.autoCreate && err.code === 5) {
this.create(options, (err, database, operation) => {
if (err) {
callback(err);
return;
}
operation.on('error', callback).on('complete', metadata => {
this.metadata = metadata;
callback(null, this, metadata);
});
});
return;
}
callback(err);
return;
}
callback(null, this, metadata);
});
}
/**
* @typedef {array} GetDatabaseMetadataResponse
* @property {object} 0 The {@link Database} metadata.
* @property {object} 1 The full API response.
*/
/**
* @callback GetDatabaseMetadataCallback
* @param {?Error} err Request error, if any.
* @param {object} metadata The {@link Database} metadata.
* @param {object} apiResponse The full API response.
*/
/**
* Get the database's metadata.
*
* Wrapper around {@link v1.DatabaseAdminClient#getDatabase}.
*
* @see {@link v1.DatabaseAdminClient#getDatabase}
* @see [GetDatabase API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabase)
*
* @param {GetDatabaseMetadataCallback} [callback] Callback function.
* @returns {Promise<GetDatabaseMetadataResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.getMetadata(function(err, metadata, apiResponse) {
* if (err) {
* // Error handling omitted.
* }
*
* // Database was deleted successfully.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.getMetadata().then(function(data) {
* const metadata = data[0];
* const apiResponse = data[1];
* });
*/
getMetadata(callback) {
const reqOpts = {
name: this.formattedName_,
};
return this.request(
{
client: 'DatabaseAdminClient',
method: 'getDatabase',
reqOpts: reqOpts,
},
callback
);
}
/**
* @typedef {array} GetSchemaResponse
* @property {string[]} 0 An array of database DDL statements.
* @property {object} 1 The full API response.
*/
/**
* @callback GetSchemaCallback
* @param {?Error} err Request error, if any.
* @param {string[]} statements An array of database DDL statements.
* @param {object} apiResponse The full API response.
*/
/**
* Get this database's schema as a list of formatted DDL statements.
*
* Wrapper around {@link v1.DatabaseAdminClient#getDatabaseDdl}.
*
* @see {@link v1.DatabaseAdminClient#getDatabaseDdl}
* @see [Data Definition Language (DDL)](https://cloud.google.com/spanner/docs/data-definition-language)
* @see [GetDatabaseDdl API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl)
*
* @param {GetSchemaCallback} [callback] Callback function.
* @returns {Promise<GetSchemaResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.getSchema(function(err, statements, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.getSchema().then(function(data) {
* const statements = data[0];
* const apiResponse = data[1];
* });
*/
getSchema(callback) {
const reqOpts = {
database: this.formattedName_,
};
this.request(
{
client: 'DatabaseAdminClient',
method: 'getDatabaseDdl',
reqOpts: reqOpts,
},
function(err, statements) {
if (statements) {
arguments[1] = statements.statements;
}
callback.apply(null, arguments);
}
);
}
/**
* Options object for listing sessions.
*
* @typedef {object} GetSessionsRequest
* @property {boolean} [autoPaginate=true] Have pagination handled
* automatically.
* @property {string} [filter] An expression for filtering the results of the
* request. Filter rules are case insensitive. The fields eligible for
* filtering are:
* - **`name`**
* - **`display_name`**
* - **`labels.key`** where key is the name of a label
*
* Some examples of using filters are:
* - **`name:*`** The instance has a name.
* - **`name:Howl`** The instance's name is howl.
* - **`labels.env:*`** The instance has the label env.
* - **`labels.env:dev`** The instance's label env has the value dev.
* - **`name:howl labels.env:dev`** The instance's name is howl and it has
* the label env with value dev.
* @property {number} [maxApiCalls] Maximum number of API calls to make.
* @property {number} [maxResults] Maximum number of items to return.
* @property {number} [pageSize] Maximum number of results per page.
* @property {string} [pageToken] A previously-returned page token
* representing part of the larger set of results to view.
*/
/**
* @typedef {array} GetSessionsResponse
* @property {Session[]} 0 Array of {@link Session} instances.
* @property {object} 1 The full API response.
*/
/**
* @callback GetSessionsCallback
* @param {?Error} err Request error, if any.
* @param {Session[]} instances Array of {@link Session} instances.
* @param {object} apiResponse The full API response.
*/
/**
* Gets a list of sessions.
*
* Wrapper around {@link v1.SpannerClient#listSessions}
*
* @see {@link v1.SpannerClient#listSessions}
* @see [ListSessions API Documentation](https://cloud.google.com/spanner/docs/reference/rpc/google.spanner.v1#google.spanner.v1.Spanner.ListSessions)
*
* @param {GetSessionsRequest} [options] Options object for listing sessions.
* @param {GetSessionsCallback} [callback] Callback function.
* @returns {Promise<GetSessionsResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.getSessions(function(err, sessions) {
* // `sessions` is an array of `Session` objects.
* });
*
* //-
* // To control how many API requests are made and page through the results
* // manually, set `autoPaginate` to `false`.
* //-
* function callback(err, sessions, nextQuery, apiResponse) {
* if (nextQuery) {
* // More results exist.
* database.getSessions(nextQuery, callback);
* }
* }
*
* database.getInstances({
* autoPaginate: false
* }, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.getInstances().then(function(data) {
* const sessions = data[0];
* });
*/
getSessions(options, callback) {
const self = this;
if (is.fn(options)) {
callback = options;
options = {};
}
const gaxOpts = options.gaxOptions;
const reqOpts = extend({}, options, {database: this.formattedName_});
delete reqOpts.gaxOptions;
this.request(
{
client: 'SpannerClient',
method: 'listSessions',
reqOpts,
gaxOpts,
},
function(err, sessions) {
if (sessions) {
arguments[1] = sessions.map(metadata => {
const session = self.session(metadata.name);
session.metadata = metadata;
return session;
});
}
callback.apply(null, arguments);
}
);
}
/**
* @typedef {array} GetTransactionResponse
* @property {Transaction} 0 The transaction object.
*/
/**
* @callback GetTransactionCallback
* @param {?Error} err Request error, if any.
* @param {Transaction} transaction The transaction object.
*/
/**
* Get a read/write ready Transaction object.
*
* Wrapper around {@link v1.SpannerClient#beginTransaction}.
*
* @see {@link v1.SpannerClient#beginTransaction}
*
* @param {TransactionOptions} [options] [Transaction options](https://cloud.google.com/spanner/docs/timestamp-bounds).
* @param {GetTransactionCallback} [callback] Callback function.
* @returns {Promise<GetTransactionResponse>}
*
* @example
* const {Spanner} = require('@google-cloud/spanner');
* const spanner = new Spanner();
*
* const instance = spanner.instance('my-instance');
* const database = instance.database('my-database');
*
* database.getTransaction(function(err, transaction) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* database.getTransaction().then(function(data) {
* const transaction = data[0];
* });
*/
getTransaction(options, callback) {
if (is.fn(options)) {
callback = options;
options = null;
}
const isReadWrite = !options || (!options.readOnly && !options.partitioned);
if (isReadWrite) {
this.pool_.getWriteSession((err, session, transaction) => {
if (!err) {
transaction = this.decorateTransaction_(transaction, session);
}
callback(err, transaction);
});
return;
}
this.pool_.getReadSession((err, session) => {
if (err) {
callback(err, null);
return;
}
session.beginTransaction(options, (err, transaction) => {
if (err) {
this.pool_.release(session);
callback(err, null);
return;
}
transaction = this.decorateTransaction_(transaction, session);
callback(null, transaction);
});
});
}
/**
* Make an API request, first assuring an active session is used.
*
* @private
*
* @param {object} config Request config
* @param {function} callback Callback function
*/
makePooledRequest_(config, callback) {
const pool = this.pool_;
pool.getReadSession((err, session) => {
if (err) {
callback(err, null);
return;
}
config.reqOpts.session = session.formattedName_;
this.request(config, function() {
pool.release(session);
callback.apply(null, arguments);
});
});
}
/**
/**
* Make an API request as a stream, first assuring an active session is used.
*
* @private
*
* @param {object} config Request config
* @returns {Stream}
*/
makePooledStreamingRequest_(config) {
const self = this;
const pool = this.pool_;
let requestStream;
let session;
const waitForSessionStream = streamEvents(through.obj());
waitForSessionStream.abort = function() {
releaseSession();
if (requestStream) {
requestStream.cancel();
}
};
function destroyStream(err) {
waitForSessionStream.destroy(err);
}
function releaseSession() {
if (session) {
pool.release(session);
session = null;
}
}
waitForSessionStream.on('reading', () => {
pool.getReadSession((err, session_) => {
if (err) {
destroyStream(err);
return;
}
session = session_;
config.reqOpts.session = session.formattedName_;
requestStream = self.requestStream(config);
requestStream
.on('error', releaseSession)
.on('error', destroyStream)
.on('end', releaseSession)
.pipe(waitForSessionStream);
});
});
return waitForSessionStream;
}
/**