-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathcodec.ts
1318 lines (1186 loc) · 33 KB
/
codec.ts
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 2017 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.
*/
import {GrpcService} from './common-grpc/service';
import {PreciseDate} from '@google-cloud/precise-date';
import arrify = require('arrify');
import {Big} from 'big.js';
import * as is from 'is';
import {common as p} from 'protobufjs';
import {google as spannerClient} from '../protos/protos';
import {GoogleError} from 'google-gax';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type Value = any;
export interface Field {
name: string;
value: Value;
}
export interface IProtoMessageParams {
// Supports proto message serialized binary data as a `Buffer` or pass a
// message object created using the functions generated by protobufjs-cli.
value: object;
// Fully qualified name of the proto representing the message definition
fullName: string;
/**
* Provide a First Class function that includes nested functions named
* "encode" for serialization and "decode" for deserialization of the proto
* message. The function should be sourced from the JS file generated by
* protobufjs-cli for the proto message.
*/
messageFunction?: Function;
}
export interface IProtoEnumParams {
// Supports proto enum integer constant or pass the enum string
// the functions generated by protobufjs-cli.
value: string | number;
// Fully qualified name of the proto representing the enum definition
fullName: string;
/**
* An object containing enum string to id mapping.
* @example: { POP: 0, JAZZ: 1, FOLK: 2, ROCK: 3 }
*
* The object should be sourced from the JS file generated by
* protobufjs-cli for the proto message. Additionally, please review the
* sample at {@link www.samples.com} for guidance.
*
* ToDo: Update the link
*/
enumObject?: object;
}
export interface Json {
[field: string]: Value;
}
export interface JSONOptions {
wrapNumbers?: boolean;
wrapStructs?: boolean;
includeNameless?: boolean;
}
// https://github.com/Microsoft/TypeScript/issues/27920
type DateFields = [number, number, number];
/**
* Date-like object used to represent Cloud Spanner Dates. DATE types represent
* a logical calendar date, independent of time zone. DATE values do not
* represent a specific 24-hour period. Rather, a given DATE value represents a
* different 24-hour period when interpreted in a different time zone. Because
* of this, all values passed to {@link Spanner.date} will be interpreted as
* local time.
*
* To represent an absolute point in time, use {@link Spanner.timestamp}.
*
* @see Spanner.date
* @see https://cloud.google.com/spanner/docs/data-types#date-type
*
* @class
* @extends Date
*
* @param {string|number} [date] String representing the date or number
* representing the year. If year is a number between 0 and 99, then year is
* assumed to be 1900 + year.
* @param {number} [month] Number representing the month (0 = January).
* @param {number} [date] Number representing the date.
*
* @example
* ```
* Spanner.date('3-3-1933');
* ```
*/
export class SpannerDate extends Date {
constructor(dateString?: string);
constructor(year: number, month: number, date: number);
constructor(...dateFields: Array<string | number | undefined>) {
const yearOrDateString = dateFields[0];
// yearOrDateString could be 0 (number).
if (yearOrDateString === null || yearOrDateString === undefined) {
dateFields[0] = new Date().toDateString();
}
// JavaScript Date objects will interpret ISO date strings as Zulu time,
// but by formatting it, we can infer local time.
if (/^\d{4}-\d{1,2}-\d{1,2}/.test(yearOrDateString as string)) {
const [year, month, date] = (yearOrDateString as string).split(/-|T/);
dateFields = [`${month}-${date}-${year}`];
}
super(...(dateFields.slice(0, 3) as DateFields));
}
/**
* Returns the date in ISO date format.
* `YYYY-MM-DD`
*
* @returns {string}
*/
toJSON(): string {
const year = this.getFullYear().toString();
const month = (this.getMonth() + 1).toString();
const date = this.getDate().toString();
return `${year.padStart(4, '0')}-${month.padStart(2, '0')}-${date.padStart(
2,
'0'
)}`;
}
}
/**
* Using an abstract class to simplify checking for wrapped numbers.
*
* @private
*/
abstract class WrappedNumber {
value!: string | number;
abstract valueOf(): number;
}
/**
* @typedef Float32
* @see Spanner.float32
*/
export class Float32 extends WrappedNumber {
value: number;
constructor(value: number) {
super();
this.value = value;
}
valueOf(): number {
return Number(this.value);
}
}
/**
* @typedef Float
* @see Spanner.float
*/
export class Float extends WrappedNumber {
value: number;
constructor(value: number) {
super();
this.value = value;
}
valueOf(): number {
return Number(this.value);
}
}
/**
* @typedef Int
* @see Spanner.int
*/
export class Int extends WrappedNumber {
value: string;
constructor(value: string) {
super();
this.value = value.toString();
}
valueOf(): number {
const num = Number(this.value);
if (num > Number.MAX_SAFE_INTEGER) {
throw new GoogleError(`Integer ${this.value} is out of bounds.`);
}
return num;
}
}
/**
* @typedef Struct
* @see Spanner.struct
*/
export class Struct extends Array<Field> {
/**
* Converts struct into a pojo (plain old JavaScript object).
*
* @param {JSONOptions} [options] JSON options.
* @returns {object}
*/
toJSON(options?: JSONOptions): Json {
return codec.convertFieldsToJson(this, options);
}
/**
* Converts an array of fields to a struct.
*
* @private
*
* @param {object[]} fields List of struct fields.
* @return {Struct}
*/
static fromArray(fields: Field[]): Struct {
return new Struct(...fields);
}
/**
* Converts a JSON object to a struct.
*
* @private
*
* @param {object} json Struct JSON.
* @return {Struct}
*/
static fromJSON(json: Json): Struct {
const fields = Object.keys(json || {}).map(name => {
const value = json[name];
return {name, value};
});
return Struct.fromArray(fields);
}
}
/**
* @typedef Numeric
* @see Spanner.numeric
*/
export class Numeric {
value: string;
constructor(value: string) {
this.value = value;
}
valueOf(): Big {
return new Big(this.value);
}
toJSON(): string {
return this.valueOf().toJSON();
}
}
/**
* @typedef PGNumeric
* @see Spanner.pgNumeric
*/
export class PGNumeric {
value: string;
constructor(pgValue: string | number) {
this.value = pgValue.toString();
}
valueOf(): Big {
if (this.value.toLowerCase() === 'nan') {
throw new Error(`${this.value} cannot be converted to a numeric value`);
}
return new Big(this.value);
}
toJSON(): string {
return this.valueOf().toJSON();
}
}
/**
* @typedef ProtoMessage
* @see Spanner.protoMessage
*/
export class ProtoMessage {
value: Buffer;
fullName: string;
messageFunction?: Function;
constructor(protoMessageParams: IProtoMessageParams) {
this.fullName = protoMessageParams.fullName;
this.messageFunction = protoMessageParams.messageFunction;
if (protoMessageParams.value instanceof Buffer) {
this.value = protoMessageParams.value;
} else if (protoMessageParams.messageFunction) {
this.value = protoMessageParams.messageFunction['encode'](
protoMessageParams.value
).finish();
} else {
throw new GoogleError(`protoMessageParams cannot be used to construct
the ProtoMessage. Pass the serialized buffer of the
proto message as the value or provide the message object along with the
corresponding messageFunction generated by protobufjs-cli.`);
}
}
toJSON(): string {
if (this.messageFunction) {
return this.messageFunction['toObject'](
this.messageFunction['decode'](this.value)
);
}
return this.value.toString();
}
}
/**
* @typedef ProtoEnum
* @see Spanner.protoEnum
*/
export class ProtoEnum {
value: string;
fullName: string;
enumObject?: object;
constructor(protoEnumParams: IProtoEnumParams) {
this.fullName = protoEnumParams.fullName;
this.enumObject = protoEnumParams.enumObject;
/**
* @code{IProtoEnumParams} can accept either a number or a string as a value so
* converting to string and checking whether it's numeric using regex.
*/
if (/^\d+$/.test(protoEnumParams.value.toString())) {
this.value = protoEnumParams.value.toString();
} else if (
protoEnumParams.enumObject &&
protoEnumParams.enumObject[protoEnumParams.value]
) {
this.value = protoEnumParams.enumObject[protoEnumParams.value];
} else {
throw new GoogleError(`protoEnumParams cannot be used for constructing the
ProtoEnum. Pass the number as the value or provide the enum string
constant as the value along with the corresponding enumObject generated
by protobufjs-cli.`);
}
}
toJSON(): string {
if (this.enumObject) {
return Object.getPrototypeOf(this.enumObject)[this.value];
}
return this.value.toString();
}
}
/**
* @typedef PGJsonb
* @see Spanner.pgJsonb
*/
export class PGJsonb {
value: object;
constructor(pgValue: object | string) {
if (typeof pgValue === 'string') {
pgValue = JSON.parse(pgValue) as object;
}
this.value = pgValue;
}
toString(): string {
return JSON.stringify(this.value);
}
}
/**
* @typedef PGOid
* @see Spanner.pgOid
*/
export class PGOid extends WrappedNumber {
value: string;
constructor(value: string) {
super();
this.value = value.toString();
}
valueOf(): number {
const num = Number(this.value);
if (num > Number.MAX_SAFE_INTEGER) {
throw new GoogleError(`PG.OID ${this.value} is out of bounds.`);
}
return num;
}
}
/**
* @typedef Interval
* @see Spanner.interval
*/
export class Interval {
private months: number;
private days: number;
private nanoseconds: bigint;
// Regex to parse ISO8601 duration format: P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S
// Only seconds can be fractional, and can have at most 9 digits after decimal point.
// Both '.' and ',' are considered valid decimal point.
private static readonly ISO8601_PATTERN: RegExp =
/^P(?!$)(-?\d+Y)?(-?\d+M)?(-?\d+D)?(T(?=-?[.,]?\d)(-?\d+H)?(-?\d+M)?(-?(((\d+)([.,]\d{1,9})?)|([.,]\d{1,9}))S)?)?$/;
static readonly MONTHS_PER_YEAR: number = 12;
static readonly DAYS_PER_MONTH: number = 30;
static readonly HOURS_PER_DAY: number = 24;
static readonly MINUTES_PER_HOUR: number = 60;
static readonly SECONDS_PER_MINUTE: number = 60;
static readonly SECONDS_PER_HOUR: number =
Interval.MINUTES_PER_HOUR * Interval.SECONDS_PER_MINUTE;
static readonly MILLISECONDS_PER_SECOND: number = 1000;
static readonly MICROSECONDS_PER_MILLISECOND: number = 1000;
static readonly NANOSECONDS_PER_MICROSECOND: number = 1000;
static readonly NANOSECONDS_PER_MILLISECOND: number =
Interval.MICROSECONDS_PER_MILLISECOND *
Interval.NANOSECONDS_PER_MICROSECOND;
static readonly NANOSECONDS_PER_SECOND: number =
Interval.MILLISECONDS_PER_SECOND *
Interval.MICROSECONDS_PER_MILLISECOND *
Interval.NANOSECONDS_PER_MICROSECOND;
static readonly NANOSECONDS_PER_DAY: bigint =
BigInt(Interval.HOURS_PER_DAY) *
BigInt(Interval.SECONDS_PER_HOUR) *
BigInt(Interval.NANOSECONDS_PER_SECOND);
static readonly NANOSECONDS_PER_MONTH: bigint =
BigInt(Interval.DAYS_PER_MONTH) * Interval.NANOSECONDS_PER_DAY;
static readonly ZERO: Interval = new Interval(0, 0, BigInt(0));
/**
* @param months months part of the `Interval`
* @param days days part of the `Interval`
* @param nanoseconds nanoseconds part of the `Interval`
*/
constructor(months: number, days: number, nanoseconds: bigint) {
if (!is.integer(months)) {
throw new GoogleError(
`Invalid months: ${months}, months should be an integral value`
);
}
if (!is.integer(days)) {
throw new GoogleError(
`Invalid days: ${days}, days should be an integral value`
);
}
if (is.null(nanoseconds) || is.undefined(nanoseconds)) {
throw new GoogleError(
`Invalid nanoseconds: ${nanoseconds}, nanoseconds should be a valid bigint value`
);
}
this.months = months;
this.days = days;
this.nanoseconds = nanoseconds;
}
/**
* @returns months part of the `Interval`.
*/
getMonths(): number {
return this.months;
}
/**
* @returns days part of the `Interval`.
*/
getDays(): number {
return this.days;
}
/**
* @returns nanoseconds part of the `Interval`.
*/
getNanoseconds(): bigint {
return this.nanoseconds;
}
/**
* Constructs an `Interval` with specified months.
*/
static fromMonths(months: number): Interval {
return new Interval(months, 0, BigInt(0));
}
/**
* Constructs an `Interval` with specified days.
*/
static fromDays(days: number): Interval {
return new Interval(0, days, BigInt(0));
}
/**
* Constructs an `Interval` with specified seconds.
*/
static fromSeconds(seconds: number): Interval {
if (!is.integer(seconds)) {
throw new GoogleError(
`Invalid seconds: ${seconds}, seconds should be an integral value`
);
}
return new Interval(
0,
0,
BigInt(Interval.NANOSECONDS_PER_SECOND) * BigInt(seconds)
);
}
/**
* Constructs an `Interval` with specified milliseconds.
*/
static fromMilliseconds(milliseconds: number): Interval {
if (!is.integer(milliseconds)) {
throw new GoogleError(
`Invalid milliseconds: ${milliseconds}, milliseconds should be an integral value`
);
}
return new Interval(
0,
0,
BigInt(Interval.NANOSECONDS_PER_MILLISECOND) * BigInt(milliseconds)
);
}
/**
* Constructs an `Interval` with specified microseconds.
*/
static fromMicroseconds(microseconds: number): Interval {
if (!is.integer(microseconds)) {
throw new GoogleError(
`Invalid microseconds: ${microseconds}, microseconds should be an integral value`
);
}
return new Interval(
0,
0,
BigInt(Interval.NANOSECONDS_PER_MICROSECOND) * BigInt(microseconds)
);
}
/**
* Constructs an `Interval` with specified nanoseconds.
*/
static fromNanoseconds(nanoseconds: bigint): Interval {
return new Interval(0, 0, nanoseconds);
}
/**
* Constructs an Interval from ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`.
* Only seconds can be fractional, and can have at most 9 digits after decimal point.
* Both '.' and ',' are considered valid decimal point.
*/
static fromISO8601(isoString: string): Interval {
const matcher = Interval.ISO8601_PATTERN.exec(isoString);
if (!matcher) {
throw new GoogleError(`Invalid ISO8601 duration string: ${isoString}`);
}
const getNullOrDefault = (groupIdx: number): string =>
matcher[groupIdx] === undefined ? '0' : matcher[groupIdx];
const years: number = parseInt(getNullOrDefault(1).replace('Y', ''));
const months: number = parseInt(getNullOrDefault(2).replace('M', ''));
const days: number = parseInt(getNullOrDefault(3).replace('D', ''));
const hours: number = parseInt(getNullOrDefault(5).replace('H', ''));
const minutes: number = parseInt(getNullOrDefault(6).replace('M', ''));
const seconds: Big = Big(
getNullOrDefault(7).replace('S', '').replace(',', '.')
);
const totalMonths: number = Big(years)
.mul(Big(Interval.MONTHS_PER_YEAR))
.add(Big(months))
.toNumber();
if (!Number.isSafeInteger(totalMonths)) {
throw new GoogleError(
'Total months is outside of the range of safe integer'
);
}
const totalNanoseconds = BigInt(
seconds
.add(
Big((BigInt(hours) * BigInt(Interval.SECONDS_PER_HOUR)).toString())
)
.add(
Big(
(BigInt(minutes) * BigInt(Interval.SECONDS_PER_MINUTE)).toString()
)
)
.mul(Big(this.NANOSECONDS_PER_SECOND))
.toString()
);
return new Interval(totalMonths, days, totalNanoseconds);
}
/**
* @returns string representation of Interval in ISO8601 duration format: `P[n]Y[n]M[n]DT[n]H[n]M[n][.fffffffff]S`
*/
toISO8601(): string {
if (this.equals(Interval.ZERO)) {
return 'P0Y';
}
// months part is normalized to years and months.
let result = 'P';
if (this.months !== 0) {
const years_part: number = Math.trunc(
this.months / Interval.MONTHS_PER_YEAR
);
const months_part: number =
this.months - years_part * Interval.MONTHS_PER_YEAR;
if (years_part !== 0) {
result += `${years_part}Y`;
}
if (months_part !== 0) {
result += `${months_part}M`;
}
}
if (this.days !== 0) {
result += `${this.days}D`;
}
// Nanoseconds part is normalized to hours, minutes and nanoseconds.
if (this.nanoseconds !== BigInt(0)) {
result += 'T';
let nanoseconds: bigint = this.nanoseconds;
const hours_part: bigint =
nanoseconds /
BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_HOUR);
nanoseconds =
nanoseconds -
hours_part *
BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_HOUR);
const minutes_part: bigint =
nanoseconds /
BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_MINUTE);
nanoseconds =
nanoseconds -
minutes_part *
BigInt(Interval.NANOSECONDS_PER_SECOND * Interval.SECONDS_PER_MINUTE);
const zero_bigint = BigInt(0);
if (hours_part !== zero_bigint) {
result += `${hours_part}H`;
}
if (minutes_part !== zero_bigint) {
result += `${minutes_part}M`;
}
let sign = '';
if (nanoseconds < zero_bigint) {
sign = '-';
nanoseconds = -nanoseconds;
}
// Nanoseconds are converted to seconds and fractional part.
const seconds_part: bigint =
nanoseconds / BigInt(Interval.NANOSECONDS_PER_SECOND);
nanoseconds =
nanoseconds - seconds_part * BigInt(Interval.NANOSECONDS_PER_SECOND);
if (seconds_part !== zero_bigint || nanoseconds !== zero_bigint) {
result += `${sign}${seconds_part}`;
if (nanoseconds !== zero_bigint) {
// Fractional part is kept in a group of 3
// For e.g.: PT0.5S will be normalized to PT0.500S
result += `.${nanoseconds
.toString()
.padStart(9, '0')
.replace(/(0{3})+$/, '')}`;
}
result += 'S';
}
}
return result;
}
equals(other: Interval): boolean {
if (!other) {
return false;
}
return (
this.months === other.months &&
this.days === other.days &&
this.nanoseconds === other.nanoseconds
);
}
valueOf(): Interval {
return this;
}
/**
* @returns JSON representation for Interval.
* Interval is represented in ISO8601 duration format string in JSON.
*/
toJSON(): string {
return this.toISO8601().toString();
}
}
/**
* @typedef JSONOptions
* @property {boolean} [wrapNumbers=false] Indicates if the numbers should be
* wrapped in Int/Float wrappers.
* @property {boolean} [wrapStructs=false] Indicates if the structs should be
* wrapped in Struct wrapper.
* @property {boolean} [includeNameless=false] Indicates if nameless columns
* should be included in the result. If true, nameless columns will be
* assigned the name '_{column_index}'.
*/
/**
* Wherever a row or struct object is returned, it is assigned a "toJSON"
* function. This function will generate the JSON for that row.
*
* @private
*
* @param {array} row The row to generate JSON for.
* @param {JSONOptions} [options] JSON options.
* @returns {object}
*/
function convertFieldsToJson(fields: Field[], options?: JSONOptions): Json {
const json: Json = {};
const defaultOptions = {
wrapNumbers: false,
wrapStructs: false,
includeNameless: false,
};
options = Object.assign(defaultOptions, options);
let index = 0;
for (const {name, value} of fields) {
if (!name && !options.includeNameless) {
continue;
}
const fieldName = name ? name : `_${index}`;
try {
json[fieldName] = convertValueToJson(value, options);
} catch (e) {
(e as Error).message = [
`Serializing column "${fieldName}" encountered an error: ${
(e as Error).message
}`,
'Call row.toJSON({ wrapNumbers: true }) to receive a custom type.',
].join(' ');
throw e;
}
index++;
}
return json;
}
/**
* Attempts to convert a wrapped or nested value into a native JavaScript type.
*
* @private
*
* @param {*} value The value to convert.
* @param {JSONOptions} options JSON options.
* @return {*}
*/
function convertValueToJson(value: Value, options: JSONOptions): Value {
if (!options.wrapNumbers && value instanceof WrappedNumber) {
return value.valueOf();
}
if (value instanceof Struct) {
if (!options.wrapStructs) {
return value.toJSON(options);
}
return value.map(({name, value}) => {
value = convertValueToJson(value, options);
return {name, value};
});
}
if (Array.isArray(value)) {
return value.map(child => convertValueToJson(child, options));
}
if (value instanceof ProtoMessage || value instanceof ProtoEnum) {
return value.toJSON();
}
return value;
}
/**
* Re-decode after the generic gRPC decoding step.
*
* @private
*
* @param {*} value Value to decode
* @param {object[]} type Value type object.
* @param columnMetadata Optional parameter to deserialize data
* @returns {*}
*/
function decode(
value: Value,
type: spannerClient.spanner.v1.Type,
columnMetadata?: object
): Value {
if (is.null(value)) {
return null;
}
let decoded = value;
let fields;
switch (type.code) {
case spannerClient.spanner.v1.TypeCode.BYTES:
case 'BYTES':
decoded = Buffer.from(decoded, 'base64');
break;
case spannerClient.spanner.v1.TypeCode.PROTO:
case 'PROTO':
decoded = Buffer.from(decoded, 'base64');
decoded = new ProtoMessage({
value: decoded,
fullName: type.protoTypeFqn,
messageFunction: columnMetadata as Function,
});
break;
case spannerClient.spanner.v1.TypeCode.ENUM:
case 'ENUM':
decoded = new ProtoEnum({
value: decoded,
fullName: type.protoTypeFqn,
enumObject: columnMetadata as object,
});
break;
case spannerClient.spanner.v1.TypeCode.FLOAT32:
case 'FLOAT32':
decoded = new Float32(decoded);
break;
case spannerClient.spanner.v1.TypeCode.FLOAT64:
case 'FLOAT64':
decoded = new Float(decoded);
break;
case spannerClient.spanner.v1.TypeCode.INT64:
case 'INT64':
if (
type.typeAnnotation ===
spannerClient.spanner.v1.TypeAnnotationCode.PG_OID ||
type.typeAnnotation === 'PG_OID'
) {
decoded = new PGOid(decoded);
break;
}
decoded = new Int(decoded);
break;
case spannerClient.spanner.v1.TypeCode.NUMERIC:
case 'NUMERIC':
if (
type.typeAnnotation ===
spannerClient.spanner.v1.TypeAnnotationCode.PG_NUMERIC ||
type.typeAnnotation === 'PG_NUMERIC'
) {
decoded = new PGNumeric(decoded);
break;
}
decoded = new Numeric(decoded);
break;
case spannerClient.spanner.v1.TypeCode.TIMESTAMP:
case 'TIMESTAMP':
decoded = new PreciseDate(decoded);
break;
case spannerClient.spanner.v1.TypeCode.DATE:
case 'DATE':
decoded = new SpannerDate(decoded);
break;
case spannerClient.spanner.v1.TypeCode.JSON:
case 'JSON':
if (
type.typeAnnotation ===
spannerClient.spanner.v1.TypeAnnotationCode.PG_JSONB ||
type.typeAnnotation === 'PG_JSONB'
) {
decoded = new PGJsonb(decoded);
break;
}
decoded = JSON.parse(decoded);
break;
case spannerClient.spanner.v1.TypeCode.INTERVAL:
case 'INTERVAL':
decoded = Interval.fromISO8601(decoded);
break;
case spannerClient.spanner.v1.TypeCode.ARRAY:
case 'ARRAY':
decoded = decoded.map(value => {
return decode(
value,
type.arrayElementType! as spannerClient.spanner.v1.Type,
columnMetadata
);
});
break;
case spannerClient.spanner.v1.TypeCode.STRUCT:
case 'STRUCT':
fields = type.structType!.fields!.map(({name, type}, index) => {
const value = decode(
(!Array.isArray(decoded) && decoded[name!]) || decoded[index],
type as spannerClient.spanner.v1.Type,
columnMetadata
);
return {name, value};
});
decoded = Struct.fromArray(fields as Field[]);
break;
default:
break;
}
return decoded;
}
/**
* Encode a value in the format the API expects.
*
* @private
*
* @param {*} value The value to be encoded.
* @returns {object} google.protobuf.Value
*/
function encode(value: Value): p.IValue {
return GrpcService.encodeValue_(encodeValue(value));
}
/**
* Formats values into expected format of google.protobuf.Value. The actual
* conversion to a google.protobuf.Value object happens via
* `Service.encodeValue_`
*
* @private
*
* @param {*} value The value to be encoded.
* @returns {*}
*/
function encodeValue(value: Value): Value {
if (is.number(value) && !is.decimal(value)) {
return value.toString();
}
if (is.date(value)) {
return value.toJSON();
}
if (value instanceof WrappedNumber) {
return value.value;
}
if (value instanceof Numeric) {
return value.value;
}
if (value instanceof PGNumeric) {
return value.value;
}
if (Buffer.isBuffer(value)) {
return value.toString('base64');
}
if (value instanceof ProtoMessage) {
return value.value.toString('base64');
}
if (value instanceof ProtoEnum) {
return value.value;
}
if (value instanceof Struct) {
return Array.from(value).map(field => encodeValue(field.value));
}
if (is.array(value)) {
return value.map(encodeValue);
}
if (value instanceof PGJsonb) {
return value.toString();
}