-
Notifications
You must be signed in to change notification settings - Fork 0
/
plv8_type.cc
1338 lines (1170 loc) · 36.1 KB
/
plv8_type.cc
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
/*-------------------------------------------------------------------------
*
* plv8_type.cc : Postgres from/to v8 data converters.
*
* Copyright (c) 2009-2012, the PLV8JS Development Group.
*-------------------------------------------------------------------------
*/
#include "plv8.h"
extern "C" {
#if JSONB_DIRECT_CONVERSION
#include <time.h>
#endif
#if PG_VERSION_NUM >= 90300
#include "access/htup_details.h"
#endif
#include "catalog/pg_type.h"
#include "parser/parse_coerce.h"
#include "utils/array.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/builtins.h"
#if PG_VERSION_NUM >= 90400
#include "utils/jsonb.h"
#endif
#include "utils/lsyscache.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "nodes/memnodes.h"
#include "utils/memutils.h"
#include "fmgr.h"
} // extern "C"
using namespace v8;
static Datum ToScalarDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type);
static Datum ToArrayDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type);
static Datum ToRecordDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type);
static Local<v8::Value> ToScalarValue(Datum datum, bool isnull, plv8_type *type);
static Local<v8::Value> ToArrayValue(Datum datum, bool isnull, plv8_type *type);
static Local<v8::Value> ToRecordValue(Datum datum, bool isnull, plv8_type *type);
static double TimestampTzToEpoch(TimestampTz tm);
static Datum EpochToTimestampTz(double epoch);
static double DateToEpoch(DateADT date);
static Datum EpochToDate(double epoch);
void
plv8_fill_type(plv8_type *type, Oid typid, MemoryContext mcxt)
{
bool ispreferred;
if (!mcxt)
mcxt = CurrentMemoryContext;
type->typid = typid;
type->fn_input.fn_mcxt = type->fn_output.fn_mcxt = mcxt;
get_type_category_preferred(typid, &type->category, &ispreferred);
type->is_composite = (type->category == TYPCATEGORY_COMPOSITE);
get_typlenbyvalalign(typid, &type->len, &type->byval, &type->align);
if (get_typtype(typid) == TYPTYPE_DOMAIN)
{
HeapTuple tp;
Form_pg_type typtup;
#if PG_VERSION_NUM < 90100
tp = SearchSysCache(TYPEOID, ObjectIdGetDatum(typid), 0, 0, 0);
#else
tp = SearchSysCache1(TYPEOID, ObjectIdGetDatum(typid));
#endif
if (HeapTupleIsValid(tp))
{
/*
* Check if the type is the external array types.
*/
typtup = (Form_pg_type) GETSTRUCT(tp);
if (strcmp(NameStr(typtup->typname),
"plv8_int2array") == 0)
{
type->ext_array = kExternalShortArray;
}
else if (strcmp(NameStr(typtup->typname),
"plv8_int4array") == 0)
{
type->ext_array = kExternalIntArray;
}
else if (strcmp(NameStr(typtup->typname),
"plv8_float4array") == 0)
{
type->ext_array = kExternalFloatArray;
}
else if (strcmp(NameStr(typtup->typname),
"plv8_float8array") == 0)
{
type->ext_array = kExternalDoubleArray;
}
else if (strcmp(NameStr(typtup->typname),
"plv8_int8array") == 0)
{
type->ext_array = kExternalInt64Array;
}
ReleaseSysCache(tp);
}
else
elog(ERROR, "cache lookup failed for type %d", typid);
if (type->ext_array)
return;
/* If not, do as usual. */
}
if (type->category == TYPCATEGORY_ARRAY)
{
Oid elemid = get_element_type(typid);
if (elemid == InvalidOid)
ereport(ERROR,
(errmsg("cannot determine element type of array: %u", typid)));
type->typid = elemid;
type->is_composite = (TypeCategory(elemid) == TYPCATEGORY_COMPOSITE);
get_typlenbyvalalign(type->typid, &type->len, &type->byval, &type->align);
}
}
/*
* Return the database type inferred by the JS value type.
* If none looks appropriate, InvalidOid is returned (currently,
* objects and arrays are in this case).
*/
Oid
inferred_datum_type(Handle<v8::Value> value)
{
if (value->IsUndefined() || value->IsNull())
return TEXTOID;
if (value->IsBoolean())
return BOOLOID;
else if (value->IsInt32())
return INT4OID;
else if (value->IsUint32())
return INT8OID;
else if (value->IsBigInt())
return INT8OID;
else if (value->IsNumber())
return FLOAT8OID;
else if (value->IsString())
return TEXTOID;
else if (value->IsDate())
return TIMESTAMPOID;
/*
else if (value->IsObject())
else if (value->IsArray())
*/
return InvalidOid;
}
#if PG_VERSION_NUM >= 90400 && JSONB_DIRECT_CONVERSION
// jsonb types moved in pg10
#if PG_VERSION_NUM < 100000
#define jbvString JsonbValue::jbvString
#define jbvNumeric JsonbValue::jbvNumeric
#define jbvBool JsonbValue::jbvBool
#define jbvObject JsonbValue::jbvObject
#define jbvArray JsonbValue::jbvArray
#define jbvNull JsonbValue::jbvNull
#endif
static Local<v8::Value>
GetJsonbValue(JsonbValue *scalarVal) {
Isolate *isolate = Isolate::GetCurrent();
if (scalarVal->type == jbvNull) {
return Local<v8::Value>::New(isolate, Null(isolate));
} else if (scalarVal->type == jbvString) {
char t[ scalarVal->val.string.len + 1 ];
strncpy(t, scalarVal->val.string.val, scalarVal->val.string.len);
t[ scalarVal->val.string.len ] = '\0';
return Local<v8::Value>::New(isolate, String::NewFromUtf8(isolate, t).ToLocalChecked());
} else if (scalarVal->type == jbvNumeric) {
return Local<v8::Value>::New(isolate, Number::New(isolate, DatumGetFloat8(DirectFunctionCall1(numeric_float8, PointerGetDatum(scalarVal->val.numeric)))));
} else if (scalarVal->type == jbvBool) {
return Local<v8::Value>::New(isolate, Boolean::New(isolate, scalarVal->val.boolean));
} else {
elog(ERROR, "unknown jsonb scalar type");
return Local<v8::Value>::New(isolate, Null(isolate));
}
}
static Local<v8::Object>
JsonbIterate(JsonbIterator **it, Local<v8::Object> container) {
Isolate *isolate = Isolate::GetCurrent();
Local<Context> context = isolate->GetCurrentContext();
JsonbValue val;
Local<v8::Value> out;
int32 count = 0;
JsonbIteratorToken token;
Local<v8::Value> key;
Local<v8::Object> obj;
token = JsonbIteratorNext(it, &val, false);
while (token != WJB_DONE) {
switch (token) {
case WJB_BEGIN_OBJECT:
obj = v8::Object::New(isolate);
if (container->IsArray()) {
container->Set(context, count, JsonbIterate(it, obj)).Check();
count++;
} else {
container->Set(context, key, JsonbIterate(it, obj)).Check();
}
break;
case WJB_END_OBJECT:
return container;
break;
case WJB_BEGIN_ARRAY:
obj = v8::Array::New(isolate);
if (container->IsArray()) {
container->Set(context, count, JsonbIterate(it, obj)).Check();
count++;
} else {
container->Set(context, key, JsonbIterate(it, obj)).Check();
}
break;
case WJB_END_ARRAY:
return container;
break;
case WJB_KEY:
key = GetJsonbValue(&val);
break;
case WJB_VALUE:
// object value
container->Set(context, key, GetJsonbValue(&val)).Check();
break;
case WJB_ELEM:
// array element
container->Set(context, count, GetJsonbValue(&val)).Check();
count++;
break;
case WJB_DONE:
return container;
break;
default:
elog(ERROR, "unknown jsonb iterator value");
}
token = JsonbIteratorNext(it, &val, false);
}
return container;
}
static Local<Object>
ConvertJsonb(JsonbContainer *in) {
Isolate *isolate = Isolate::GetCurrent();
JsonbValue val;
JsonbIterator *it = JsonbIteratorInit(in);
JsonbIteratorToken token = JsonbIteratorNext(&it, &val, false);
Local<Object> container;
if (token == WJB_BEGIN_ARRAY) {
container = v8::Array::New(isolate);
} else {
container = v8::Object::New(isolate);
}
return JsonbIterate(&it, container);
}
static JsonbValue *
JsonbObjectFromObject(JsonbParseState **pstate, Local<v8::Object> object);
static JsonbValue *
JsonbArrayFromArray(JsonbParseState **pstate, Local<v8::Object> object);
static void LogType(Local<v8::Value> val, bool asError = true) {
if( val->IsUndefined() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Undefined");
if( val->IsNull() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Null");
if( val->IsTrue() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: True");
if( val->IsFalse() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: False");
if( val->IsName() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Name");
if( val->IsString() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: String");
if( val->IsSymbol() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Symbol");
if( val->IsFunction() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Function");
if( val->IsArray() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Array");
if( val->IsObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Object");
if( val->IsBoolean() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Boolean");
if( val->IsNumber() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Number");
if( val->IsExternal() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: External");
if( val->IsInt32() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Int32");
if( val->IsUint32() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Uint32");
if( val->IsDate() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Date");
if( val->IsArgumentsObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Arguments Object");
if( val->IsBooleanObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Boolean Object");
if( val->IsNumberObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Number Object");
if( val->IsStringObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: String Object");
if( val->IsSymbolObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Symbol Object");
if( val->IsNativeError() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Native Error");
if( val->IsRegExp() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: RegExp");
if( val->IsGeneratorFunction() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Generator Function");
if( val->IsGeneratorObject() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Generator Object");
if( val->IsPromise() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Promise");
if( val->IsMap() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Map");
if( val->IsSet() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Set");
if( val->IsMapIterator() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Map Iterator");
if( val->IsSetIterator() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Set Iterator");
if( val->IsWeakMap() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Weak Map");
if( val->IsWeakSet() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Weak Set");
if( val->IsArrayBuffer() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Array Buffer");
if( val->IsArrayBufferView() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Array Buffer View");
if( val->IsTypedArray() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Typed Array");
if( val->IsUint8Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Uint8 Array");
if( val->IsUint8ClampedArray() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Uint8 Clamped Array");
if( val->IsInt8Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Int8 Array");
if( val->IsUint16Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Uint16 Array");
if( val->IsInt16Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Int16 Array");
if( val->IsUint32Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Uint32 Array");
if( val->IsInt32Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Int32 Array");
if( val->IsFloat32Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Float32 Array");
if( val->IsFloat64Array() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Float64 Array");
if( val->IsDataView() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Data View");
if( val->IsSharedArrayBuffer() )
elog((asError ? ERROR : NOTICE), "Unaccounted for type: Shared Buffer Array");
}
static char *
TimeAs8601 (double millis) {
char tmp[100];
char *buf = (char *)palloc(25);
time_t t = (time_t) (millis / 1000);
strftime (tmp, 25, "%Y-%m-%dT%H:%M:%S", gmtime(&t));
double integral;
double fractional = modf(millis / 1000, &integral);
sprintf(buf, "%s.%03dZ", tmp, (int) (fractional * 1000));
return buf;
}
static JsonbValue *
JsonbFromValue(JsonbParseState **pstate, Local<v8::Value> value, JsonbIteratorToken type) {
Isolate *isolate = Isolate::GetCurrent();
Local<Context> context = isolate->GetCurrentContext();
JsonbValue val;
// if the token type is a key, the only valid value is jbvString
if (type == WJB_KEY) {
val.type = jbvString;
String::Utf8Value utf8(isolate, value->ToString(context).ToLocalChecked());
val.val.string.val = ToCStringCopy(utf8);
val.val.string.len = utf8.length();
} else {
if (value->IsBoolean()) {
val.type = jbvBool;
val.val.boolean = value->BooleanValue(isolate);
} else if (value->IsNull()) {
val.type = jbvNull;
} else if (value->IsUndefined()) {
return NULL;
} else if (value->IsString()) {
val.type = jbvString;
String::Utf8Value utf8(isolate, value->ToString(context).ToLocalChecked());
val.val.string.val = ToCStringCopy(utf8);
val.val.string.len = utf8.length();
} else if (value->IsNumber()) {
if (value->IsInt32()) {
int32 iv = value->Int32Value(context).ToChecked();
val.val.numeric = DatumGetNumeric(DirectFunctionCall1(int4_numeric, Int32GetDatum(iv)));
val.type = jbvNumeric;
} else if (value->IsUint32()) {
int64 iv = (int64) value->Uint32Value(context).ToChecked();
val.val.numeric = DatumGetNumeric(DirectFunctionCall1(int8_numeric, Int64GetDatum(iv)));
val.type = jbvNumeric;
} else {
float8 fv = (float8) value->NumberValue(context).ToChecked();
val.val.numeric = DatumGetNumeric(DirectFunctionCall1(float8_numeric, Float8GetDatum(fv)));
val.type = jbvNumeric;
}
} else if (value->IsDate()) {
double t = value->NumberValue(context).ToChecked();
if (isnan(t)) {
val.type = jbvNull;
} else {
val.val.string.val = TimeAs8601(t);
val.val.string.len = 24;
val.type = jbvString;
}
} else {
LogType(value, false);
val.type = jbvString;
String::Utf8Value utf8(isolate, value->ToString(context).ToLocalChecked());
val.val.string.val = ToCStringCopy(utf8);
val.val.string.len = utf8.length();
}
}
return pushJsonbValue(pstate, type, &val);
}
static JsonbValue *
JsonbArrayFromArray(JsonbParseState **pstate, Local<v8::Object> object) {
Isolate *isolate = Isolate::GetCurrent();
Local<Context> context = isolate->GetCurrentContext();
JsonbValue *val = pushJsonbValue(pstate, WJB_BEGIN_ARRAY, NULL);
Local<v8::Array> a = Local<v8::Array>::Cast(object);
for (size_t i = 0; i < a->Length(); i++) {
Local<v8::Value> o = a->Get(context, i).ToLocalChecked();
if (o->IsArray()) {
val = JsonbArrayFromArray(pstate, Local<v8::Array>::Cast(o));
} else if (o->IsObject()) {
val = JsonbObjectFromObject(pstate, Local<v8::Object>::Cast(o));
} else {
val = JsonbFromValue(pstate, o, WJB_ELEM);
}
}
val = pushJsonbValue(pstate, WJB_END_ARRAY, NULL);
return val;
}
static JsonbValue *
JsonbObjectFromObject(JsonbParseState **pstate, Local<v8::Object> object) {
Isolate *isolate = Isolate::GetCurrent();
Local<Context> context = isolate->GetCurrentContext();
JsonbValue *val = pushJsonbValue(pstate, WJB_BEGIN_OBJECT, NULL);
Local<Array> arr = object->GetOwnPropertyNames(context).ToLocalChecked();
for (size_t i = 0; i < arr->Length(); i++) {
Local<v8::Value> v = arr->Get(context, i).ToLocalChecked();
val = JsonbFromValue(pstate, v, WJB_KEY);
Local<v8::Value> o = object->Get(context, v).ToLocalChecked();
if (o->IsDate()) {
val = JsonbFromValue(pstate, o, WJB_VALUE);
} else if (o->IsArray()) {
val = JsonbArrayFromArray(pstate, Local<v8::Array>::Cast(o));
} else if (o->IsObject()) {
val = JsonbObjectFromObject(pstate, Local<v8::Object>::Cast(o));
} else {
val = JsonbFromValue(pstate, o, WJB_VALUE);
}
}
val = pushJsonbValue(pstate, WJB_END_OBJECT, NULL);
return val;
}
static Jsonb *
ConvertObject(Local<v8::Object> object) {
// create a new memory context for conversion
MemoryContext oldcontext = CurrentMemoryContext;
MemoryContext conversion_context;
#if PG_VERSION_NUM < 110000
conversion_context = AllocSetContextCreate(
CurrentMemoryContext,
"JSONB Conversion Context",
ALLOCSET_SMALL_MINSIZE,
ALLOCSET_SMALL_INITSIZE,
ALLOCSET_SMALL_MAXSIZE);
#else
conversion_context = AllocSetContextCreate(CurrentMemoryContext,
"JSONB Conversion Context",
ALLOCSET_SMALL_SIZES);
#endif
MemoryContextSwitchTo(conversion_context);
JsonbParseState *pstate = NULL;
JsonbValue *val;
if (object->IsArray()) {
val = JsonbArrayFromArray(&pstate, object);
} else if (object->IsObject()) {
val = JsonbObjectFromObject(&pstate, object);
} else {
val = pushJsonbValue(&pstate, WJB_BEGIN_ARRAY, NULL);
val = JsonbFromValue(&pstate, object, WJB_ELEM);
val = pushJsonbValue(&pstate, WJB_END_ARRAY, NULL);
}
MemoryContextSwitchTo(oldcontext);
Jsonb *ret = JsonbValueToJsonb(val);
MemoryContextDelete(conversion_context);
return ret;
}
#endif
static Local<Object>
CreateExternalArray(void *data, plv8_external_array_type array_type,
int byte_size, Datum datum)
{
Isolate* isolate = Isolate::GetCurrent();
Local<v8::ArrayBuffer> buffer;
Local<v8::TypedArray> array;
buffer = v8::ArrayBuffer::New(isolate, byte_size);
if (buffer.IsEmpty())
{
return {};
}
switch (array_type)
{
case kExternalByteArray:
array = v8::Int8Array::New(buffer, 0, byte_size);
break;
case kExternalUnsignedByteArray:
array = v8::Uint8Array::New(buffer, 0, byte_size);
break;
case kExternalShortArray:
array = v8::Int16Array::New(buffer, 0, byte_size / sizeof(int16));
break;
case kExternalUnsignedShortArray:
array = v8::Uint16Array::New(buffer, 0, byte_size / sizeof(int16));
break;
case kExternalIntArray:
array = v8::Int32Array::New(buffer, 0, byte_size / sizeof(int32));
break;
case kExternalUnsignedIntArray:
array = v8::Uint32Array::New(buffer, 0, byte_size / sizeof(int32));
break;
case kExternalFloatArray:
array = v8::Float32Array::New(buffer, 0, byte_size / sizeof(float4));
break;
case kExternalDoubleArray:
array = v8::Float64Array::New(buffer, 0, byte_size / sizeof(float8));
break;
case kExternalInt64Array:
array = v8::BigInt64Array::New(buffer, 0, byte_size / sizeof(int64));
default:
throw js_error("unexpected array type");
}
array->SetInternalField(0, External::New(isolate, DatumGetPointer(datum)));
// needs to be a copy, as the data could go away
memcpy(buffer->GetBackingStore()->Data(), data, byte_size);
return array;
}
static void *
ExtractExternalArrayDatum(Handle<v8::Value> value)
{
if (value->IsUndefined() || value->IsNull()) {
return NULL;
}
if (value->IsTypedArray())
{
Handle<Object> object = Handle<Object>::Cast(value);
return Handle<External>::Cast(object->GetInternalField(0))->Value();
}
return NULL;
}
Datum
ToDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type)
{
if (type->category == TYPCATEGORY_ARRAY)
return ToArrayDatum(value, isnull, type);
else
return ToScalarDatum(value, isnull, type);
}
static Datum
ToScalarDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type)
{
Isolate* isolate = Isolate::GetCurrent();
if (type->category == TYPCATEGORY_COMPOSITE)
return ToRecordDatum(value, isnull, type);
if (value->IsUndefined() || value->IsNull())
{
*isnull = true;
return (Datum) 0;
}
*isnull = false;
switch (type->typid)
{
case OIDOID:
if (value->IsNumber())
return ObjectIdGetDatum(value->Uint32Value(isolate->GetCurrentContext()).ToChecked());
break;
case BOOLOID:
if (value->IsBoolean())
return BoolGetDatum(value->BooleanValue(isolate));
break;
case INT2OID:
if (value->IsNumber())
#ifdef CHECK_INTEGER_OVERFLOW
return DirectFunctionCall1(int82,
Int64GetDatum(value->IntegerValue()));
#else
return Int16GetDatum((int16) value->Int32Value(isolate->GetCurrentContext()).ToChecked());
#endif
break;
case INT4OID:
if (value->IsNumber())
#ifdef CHECK_INTEGER_OVERFLOW
return DirectFunctionCall1(int84,
Int64GetDatum(value->IntegerValue()));
#else
return Int32GetDatum((int32) value->Int32Value(isolate->GetCurrentContext()).ToChecked());
#endif
break;
case INT8OID:
if (value->IsBigInt()) {
BigInt *b = BigInt::Cast(*value);
return Int64GetDatum((int64) b->Int64Value());
}
if (value->IsNumber())
return Int64GetDatum((int64) value->IntegerValue(isolate->GetCurrentContext()).ToChecked());
break;
case FLOAT4OID:
if (value->IsNumber())
return Float4GetDatum((float4) value->NumberValue(isolate->GetCurrentContext()).ToChecked());
break;
case FLOAT8OID:
if (value->IsNumber())
return Float8GetDatum((float8) value->NumberValue(isolate->GetCurrentContext()).ToChecked());
break;
case NUMERICOID:
if (value->IsBigInt()) {
String::Utf8Value utf8(isolate, value->ToString(isolate->GetCurrentContext()).ToLocalChecked());
return DirectFunctionCall3(numeric_in, (Datum) *utf8, ObjectIdGetDatum(InvalidOid), Int32GetDatum((int32) -1));
}
if (value->IsNumber())
return DirectFunctionCall1(float8_numeric,
Float8GetDatum((float8) value->NumberValue(isolate->GetCurrentContext()).ToChecked()));
break;
case DATEOID:
if (value->IsDate())
return EpochToDate(value->NumberValue(isolate->GetCurrentContext()).ToChecked());
break;
case TIMESTAMPOID:
case TIMESTAMPTZOID:
if (value->IsDate())
return EpochToTimestampTz(value->NumberValue(isolate->GetCurrentContext()).ToChecked());
break;
case BYTEAOID:
{
if (value->IsUint8Array() || value->IsInt8Array()) {
v8::Handle<v8::Uint8Array> array = v8::Handle<v8::Uint8Array>::Cast(value);
void *data = array->Buffer()->GetBackingStore()->Data();
int len = array->Length();
size_t size = len + VARHDRSZ;
void *result = (void *) palloc(size);
SET_VARSIZE(result, size);
memcpy(VARDATA(result), data, len);
return PointerGetDatum(result);
}
if (value->IsUint16Array() || value->IsInt16Array()) {
v8::Handle<v8::Uint16Array> array = v8::Handle<v8::Uint16Array>::Cast(value);
void *data = array->Buffer()->GetBackingStore()->Data();
int len = array->Length();
size_t size = (len * 2) + VARHDRSZ;
void *result = (void *) palloc(size);
SET_VARSIZE(result, size);
memcpy(VARDATA(result), data, len * 2);
return PointerGetDatum(result);
}
if (value->IsUint32Array() || value->IsInt32Array()) {
v8::Handle<v8::Uint32Array> array = v8::Handle<v8::Uint32Array>::Cast(value);
void *data = array->Buffer()->GetBackingStore()->Data();
int len = array->Length();
size_t size = (len * 4) + VARHDRSZ;
void *result = (void *) palloc(size);
SET_VARSIZE(result, size);
memcpy(VARDATA(result), data, len * 4);
return PointerGetDatum(result);
}
if (value->IsArrayBuffer()) {
v8::Handle<v8::ArrayBuffer> array = v8::Handle<v8::ArrayBuffer>::Cast(value);
void *data = array->GetBackingStore()->Data();
int len = array->ByteLength();
size_t size = len + VARHDRSZ;
void *result = (void *) palloc(size);
SET_VARSIZE(result, size);
memcpy(VARDATA(result), data, len);
return PointerGetDatum(result);
}
void *datum_p = ExtractExternalArrayDatum(value);
if (datum_p)
{
return PointerGetDatum(datum_p);
}
}
break;
#if PG_VERSION_NUM >= 90400
case JSONBOID:
#if JSONB_DIRECT_CONVERSION
{
Jsonb *obj = ConvertObject(Local<v8::Object>::Cast(value));
#if PG_VERSION_NUM < 110000
PG_RETURN_JSONB(DatumGetJsonb(obj));
#else
PG_RETURN_JSONB_P(DatumGetJsonbP(obj));
#endif // PG_VERSION_NUM < 110000
}
#else // JSONB_DIRECT_CONVERSION
if (value->IsObject() || value->IsArray())
{
JSONObject JSON;
Handle<v8::Value> result = JSON.Stringify(value);
CString str(result);
#if PG_VERSION_NUM < 110000
// lots of casting, but it ends up working - there is no CStringGetJsonb exposed
return (Datum) DatumGetJsonb(DirectFunctionCall1(jsonb_in, (Datum) (char *) str));
#else
return (Datum) DatumGetJsonbP(DirectFunctionCall1(jsonb_in, (Datum) (char *) str));
#endif
}
#endif // JSONB_DIRECT_CONVERSION
break;
#endif
#if PG_VERSION_NUM >= 90200
case JSONOID:
if (value->IsObject() || value->IsArray())
{
JSONObject JSON;
Handle<v8::Value> result = JSON.Stringify(value);
CString str(result);
return CStringGetTextDatum(str);
}
break;
#endif
}
/* Use lexical cast for non-numeric types. */
CString str(value);
Datum result;
PG_TRY();
{
if (type->fn_input.fn_addr == NULL)
{
Oid input_func;
getTypeInputInfo(type->typid, &input_func, &type->ioparam);
fmgr_info_cxt(input_func, &type->fn_input, type->fn_input.fn_mcxt);
}
result = InputFunctionCall(&type->fn_input, str, type->ioparam, -1);
}
PG_CATCH();
{
throw pg_error();
}
PG_END_TRY();
return result;
}
static Datum
ToArrayDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type)
{
int length;
Datum *values;
bool *nulls;
int ndims[1];
int lbs[] = {1};
ArrayType *result;
Isolate *isolate = Isolate::GetCurrent();
Local<Context> context = isolate->GetCurrentContext();
if (value->IsUndefined() || value->IsNull())
{
*isnull = true;
return (Datum) 0;
}
void *datum_p = ExtractExternalArrayDatum(value);
if (datum_p)
{
*isnull = false;
return PointerGetDatum(datum_p);
}
Handle<Array> array(Handle<Array>::Cast(value));
if (array.IsEmpty() || !array->IsArray())
throw js_error("value is not an Array");
length = array->Length();
values = (Datum *) palloc(sizeof(Datum) * length);
nulls = (bool *) palloc(sizeof(bool) * length);
ndims[0] = length;
for (int i = 0; i < length; i++) {
if (type->is_composite)
{
values[i] = ToRecordDatum(array->Get(context, i).ToLocalChecked(), &nulls[i], type);
} else {
values[i] = ToScalarDatum(array->Get(context, i).ToLocalChecked(), &nulls[i], type);
}
}
result = construct_md_array(values, nulls, 1, ndims, lbs,
type->typid, type->len, type->byval, type->align);
pfree(values);
pfree(nulls);
*isnull = false;
return PointerGetDatum(result);
}
static Datum
ToRecordDatum(Handle<v8::Value> value, bool *isnull, plv8_type *type)
{
Datum result;
TupleDesc tupdesc;
if (value->IsUndefined() || value->IsNull())
{
*isnull = true;
return (Datum) 0;
}
PG_TRY();
{
tupdesc = lookup_rowtype_tupdesc(type->typid, -1);
}
PG_CATCH();
{
throw pg_error();
}
PG_END_TRY();
Converter conv(tupdesc);
result = conv.ToDatum(value);
ReleaseTupleDesc(tupdesc);
*isnull = false;
return result;
}
Local<v8::Value>
ToValue(Datum datum, bool isnull, plv8_type *type)
{
Isolate* isolate = Isolate::GetCurrent();
if (isnull)
return Local<v8::Value>::New(isolate, Null(isolate));
else if (type->category == TYPCATEGORY_ARRAY || type->typid == RECORDARRAYOID)
return ToArrayValue(datum, isnull, type);
else if (type->category == TYPCATEGORY_COMPOSITE || type->typid == RECORDOID)
return ToRecordValue(datum, isnull, type);
else
return ToScalarValue(datum, isnull, type);
}
static Local<v8::Value>
ToScalarValue(Datum datum, bool isnull, plv8_type *type)
{
Isolate* isolate = Isolate::GetCurrent();
switch (type->typid)
{
case OIDOID:
return Uint32::New(isolate, DatumGetObjectId(datum));
case BOOLOID:
return Boolean::New(isolate, DatumGetBool(datum));
case INT2OID:
return Int32::New(isolate, DatumGetInt16(datum));
case INT4OID:
return Int32::New(isolate, DatumGetInt32(datum));
case INT8OID: {
#if BIGINT_GRACEFUL
int64 v = DatumGetInt64(datum);
if (v > INT32_MAX || v < INT32_MIN)
return BigInt::New(isolate, v);
return Number::New(isolate, v);
#else
return BigInt::New(isolate, DatumGetInt64(datum));
#endif
}
case FLOAT4OID:
return Number::New(isolate, DatumGetFloat4(datum));
case FLOAT8OID:
return Number::New(isolate, DatumGetFloat8(datum));
case NUMERICOID:
return Number::New(isolate, DatumGetFloat8(
DirectFunctionCall1(numeric_float8, datum)));
case DATEOID:
return Date::New(isolate->GetCurrentContext(), DateToEpoch(DatumGetDateADT(datum))).ToLocalChecked();
case TIMESTAMPOID:
case TIMESTAMPTZOID:
return Date::New(isolate->GetCurrentContext(), TimestampTzToEpoch(DatumGetTimestampTz(datum))).ToLocalChecked();
case TEXTOID:
case VARCHAROID:
case BPCHAROID:
case XMLOID:
{
void *p = PG_DETOAST_DATUM_PACKED(datum);
const char *str = VARDATA_ANY(p);
int len = VARSIZE_ANY_EXHDR(p);
Local<String> result = ToString(str, len);
if (p != DatumGetPointer(datum))
pfree(p); // free if detoasted
return result;
}
case BYTEAOID:
{
void *p = PG_DETOAST_DATUM_COPY(datum);
return CreateExternalArray(VARDATA_ANY(p),
kExternalUnsignedByteArray,
VARSIZE_ANY_EXHDR(p),
PointerGetDatum(p));
}
#if PG_VERSION_NUM >= 90200
case JSONOID:
{
void *p = PG_DETOAST_DATUM_PACKED(datum);
const char *str = VARDATA_ANY(p);
int len = VARSIZE_ANY_EXHDR(p);
Local<v8::Value> jsonString = ToString(str, len);