-
Notifications
You must be signed in to change notification settings - Fork 4
/
jsonknife.c
890 lines (714 loc) · 22.1 KB
/
jsonknife.c
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
#include "postgres.h"
#include "miscadmin.h"
#include "fmgr.h"
#include "lib/stringinfo.h"
#include "utils/builtins.h"
#include "utils/formatting.h"
#include "utils/timestamp.h"
#include "utils/datetime.h"
#include "utils/json.h"
#include "catalog/pg_type.h"
#include "catalog/pg_collation.h"
#include "utils/jsonb.h"
#include "utils/varlena.h"
#ifndef PG_GETARG_JSONB
#define PG_GETARG_JSONB(x) DatumGetJsonbP(PG_GETARG_DATUM(x))
#endif
typedef struct LocalNullableDatum {
Datum value;
bool isnull;
} LocalNullableDatum;
typedef void (*reduce_fn)(void *acc, JsonbValue *val);
typedef enum MinMax {min, max} MinMax;
static MinMax minmax_from_string(char *s);
typedef enum JValueType {JVObject, JVArray, JVString, JVNumeric, JVBoolean, JVNull} JValueType;
static LocalNullableDatum date_bound(char *date_str, long str_len, MinMax minmax);
static text *jsonbv_to_text(StringInfoData *out, JsonbValue *v);
static void initJsonbValue(JsonbValue *jbv, Jsonb *jb);
static bool knife_match(JsonbValue *value, JsonbValue *pattern);
typedef struct BasicAccumulator {
} BasicAccumulator;
typedef struct NumericAccumulator {
MinMax minmax;
Numeric acc;
} NumericAccumulator;
typedef struct ArrayAccumulator {
ArrayBuildState *acc;
bool case_insensitive;
} ArrayAccumulator;
typedef struct DateAccumulator {
LocalNullableDatum acc;
MinMax minmax;
} DateAccumulator;
typedef struct TextAccumulator {
text *acc;
} TextAccumulator;
typedef struct BoolAccumulator {
bool acc;
} BoolAccumulator;
static void update_numeric(NumericAccumulator *nacc, Numeric num);
/* static char * numeric_to_cstring(Numeric n); */
MinMax
minmax_from_string(char *s){
if(strcmp(s, "min") == 0){
return min;
} else if (strcmp(s, "max") == 0) {
return max;
} else {
elog(ERROR, "expected min or max");
}
}
static JValueType
jsonbv_type(JsonbValue *v) {
if(v == NULL){ return JVNull; }
JsonbIterator *array_it;
JsonbValue array_value;
int next_it;
switch(v->type)
{
case jbvNull:
return JVNull;
break;
case jbvBool:
return JVBoolean;
break;
case jbvString:
return JVString;
break;
case jbvNumeric:
return JVNumeric;
break;
case jbvBinary:
case jbvArray:
case jbvObject:
{
array_it = JsonbIteratorInit((JsonbContainer *) v->val.binary.data);
next_it = JsonbIteratorNext(&array_it, &array_value, true);
if(next_it == WJB_BEGIN_ARRAY){
return JVArray;
}
else if(next_it == WJB_BEGIN_OBJECT){
return JVObject;
}
}
break;
default:
return JVNull;
elog(ERROR, "Unknown jsonb type: %d", v->type);
}
return JVNull;
}
static inline StringInfoData *
append_jsonbv_to_buffer(StringInfoData *out, JsonbValue *v){
if (out == NULL)
out = makeStringInfo();
switch(v->type)
{
case jbvNull:
return NULL;
break;
case jbvBool:
appendStringInfoString(out, (v->val.boolean ? "true" : "false"));
break;
case jbvString:
appendBinaryStringInfo(out, v->val.string.val, v->val.string.len);
break;
case jbvNumeric:
appendStringInfoString(out, DatumGetCString(DirectFunctionCall1(numeric_out, PointerGetDatum(v->val.numeric))));
break;
case jbvBinary:
case jbvArray:
case jbvObject:
{
Jsonb *binary = JsonbValueToJsonb(v);
(void) JsonbToCString(out, &binary->root, -1);
}
break;
default:
elog(ERROR, "Wrong jsonb type: %d", v->type);
}
return out;
}
/* this function convert JsonbValue to string, */
/* StringInfoData out buffer is optional */
static inline char *
jsonbv_to_string(StringInfoData *out, JsonbValue *v){
if (out == NULL)
out = makeStringInfo();
append_jsonbv_to_buffer(out, v);
return out->data;
}
text *jsonbv_to_text(StringInfoData *out, JsonbValue *v){
if (v == NULL)
return NULL;
if (out == NULL)
out = makeStringInfo();
appendStringInfoSpaces(out, VARHDRSZ);
append_jsonbv_to_buffer(out, v);
SET_VARSIZE(out->data, out->len);
return (text *)out->data;
}
void initJsonbValue(JsonbValue *jbv, Jsonb *jb) {
jbv->type = jbvBinary;
jbv->val.binary.data = &jb->root;
jbv->val.binary.len = VARSIZE_ANY_EXHDR(jb);
}
/* return value of obj key */
static inline JsonbValue *
jsonb_get_key(JsonbValue *obj, JsonbValue *key){
if(obj->type == jbvBinary){
return findJsonbValueFromContainer((JsonbContainer *) obj->val.binary.data , JB_FOBJECT, key);
} else {
return NULL;
}
}
/*
* Compare two scalar JsonbValues, returning -1, 0, or 1.
*
* Strings are compared using the default collation. Used by B-tree
* operators, where a lexical sort order is generally expected.
*/
static int
compareJsonbScalarValue(JsonbValue *aScalar, JsonbValue *bScalar)
{
if (aScalar->type == bScalar->type)
{
switch (aScalar->type)
{
case jbvNull:
return 0;
case jbvString:
return varstr_cmp(aScalar->val.string.val,
aScalar->val.string.len,
bScalar->val.string.val,
bScalar->val.string.len,
DEFAULT_COLLATION_OID);
case jbvNumeric:
return DatumGetInt32(DirectFunctionCall2(numeric_cmp,
PointerGetDatum(aScalar->val.numeric),
PointerGetDatum(bScalar->val.numeric)));
case jbvBool:
if (aScalar->val.boolean == bScalar->val.boolean)
return 0;
else if (aScalar->val.boolean > bScalar->val.boolean)
return 1;
else
return -1;
default:
elog(ERROR, "invalid jsonb scalar type");
}
}
elog(ERROR, "jsonb scalar type mismatch");
return -1;
}
bool knife_match(JsonbValue *value, JsonbValue *pattern){
if(value == NULL || pattern == NULL) {
return false;
}
JValueType vtype = jsonbv_type(value);
JValueType ptype = jsonbv_type(pattern);
if((vtype == JVString || vtype == JVNumeric || vtype == JVBoolean) && (ptype == JVString || ptype == JVNumeric || ptype == JVBoolean)){
/* elog(INFO, "compare prim %d, %s with %s", */
/* compareJsonbScalarValue(value, pattern), */
/* jsonbv_to_string(NULL, value), */
/* jsonbv_to_string(NULL, pattern)); */
if(compareJsonbScalarValue(value, pattern) == 0) {
return true;
} else {
return false;
}
}
if( vtype == JVObject && ptype == JVObject){
/* elog(INFO, "compare objects"); */
JsonbIterator *patt_it;
patt_it = JsonbIteratorInit((JsonbContainer *) pattern->val.binary.data);
JsonbIterator *val_it;
val_it = JsonbIteratorInit((JsonbContainer *) value->val.binary.data);
bool res = JsonbDeepContains(&val_it, &patt_it);
/* elog(INFO, "MATCH %d, %s with %s", */
/* res, */
/* jsonbv_to_string(NULL, value), */
/* jsonbv_to_string(NULL, pattern)); */
return res;
/* /\* JsonbValue *path_item; *\/ */
/* JsonbValue array_value; */
/* JsonbValue *sample_value = NULL; */
/* int next_it; */
/* bool matched = true; */
/* array_it = JsonbIteratorInit((JsonbContainer *) pattern->val.binary.data); */
/* next_it = JsonbIteratorNext(&array_it, &array_value, true); */
/* while (matched == true && (next_it = JsonbIteratorNext(&array_it, &array_value, true)) != WJB_DONE){ */
/* if (next_it == WJB_KEY){ */
/* elog(INFO, "compare keys"); */
/* sample_value = jsonb_get_key(value, &array_value); */
/* if(sample_value == NULL){ */
/* matched = false; */
/* } */
/* } else if ( next_it == WJB_VALUE ) { */
/* elog(INFO, "compare vals %s: %s", sample_value, &array_value); */
/* if(! knife_match(sample_value, &array_value)){ */
/* matched = false; */
/* } */
/* } */
/* } */
/* elog(INFO, "matched %d", matched); */
/* return matched; */
}
return false;
}
static long
reduce_path(JsonbValue *jbv, JsonbValue **path, int current_idx, int path_len, void *acc, reduce_fn fn)
{
JsonbValue *next_v = NULL;
JsonbValue *path_item = NULL;
JsonbIterator *array_it;
JsonbValue array_value;
int next_it;
long num_results = 0;
check_stack_depth();
/* elog(INFO, "enter with: %s ", jsonbv_to_string(NULL, jbv)); */
if(jbv == NULL) { return 0; }
if( current_idx < path_len ){
path_item = path[current_idx];
}
if(jsonbv_type(jbv) == JVArray && ( path_item == NULL || jsonbv_type(path_item) != JVNumeric )){
array_it = JsonbIteratorInit((JsonbContainer *) jbv->val.binary.data);
next_it = JsonbIteratorNext(&array_it, &array_value, true);
while ((next_it = JsonbIteratorNext(&array_it, &array_value, true)) != WJB_DONE){
if(next_it == WJB_ELEM){
num_results += reduce_path(&array_value, path, current_idx, path_len, acc, fn);
}
}
return num_results;
}
if(current_idx == path_len && jbv != NULL){
fn(acc, jbv);
return 1;
}
switch(jsonbv_type(path_item)) {
case JVString:
/* elog(INFO, " in key: %s", jsonbv_to_string(NULL, path_item)); */
if(jsonbv_type(jbv) == JVObject){
/* elog(INFO, " * in object: %s", jsonbv_to_string(NULL, jbv)); */
next_v = jsonb_get_key(jbv, path_item);
if(next_v != NULL){
num_results += reduce_path(next_v, path, (current_idx + 1), path_len, acc, fn);
}
}
break;
case JVNumeric:
/* elog(INFO, " in index: %s", jsonbv_to_string(NULL, path_item)); */
if(jsonbv_type(jbv) == JVArray) {
array_it = JsonbIteratorInit((JsonbContainer *) jbv->val.binary.data);
next_it = JsonbIteratorNext(&array_it, &array_value, true);
int array_index = 0;
int required_index = DatumGetInt32(DirectFunctionCall1(numeric_int4, NumericGetDatum(path_item->val.numeric)));
/* elog(INFO, "looking for index %d", required_index); */
while ((next_it = JsonbIteratorNext(&array_it, &array_value, true)) != WJB_DONE && array_index != -1){
if(next_it == WJB_ELEM){
/* elog(INFO, " %d = %d", array_index, required_index); */
if(array_index == required_index) {
num_results += reduce_path(&array_value, path, (current_idx +1), path_len, acc, fn);
break;
}
array_index++;
}
}
}
break;
case JVObject:
if(jsonbv_type(jbv) == JVObject){
if(knife_match(jbv, path_item)){
/* elog(INFO, "matched"); */
num_results += reduce_path(jbv, path, (current_idx + 1), path_len, acc, fn);
}
}
break;
case JVArray:
case JVBoolean:
case JVNull:
break;
}
return num_results;
}
/* static */
/* void reduce_debug(void *acc, JsonbValue *val){ */
/* elog(INFO, "leaf: %s", jsonbv_to_string(NULL, val)); */
/* } */
static
void reduce_jsonb_array(void *acc, JsonbValue *val){
ArrayAccumulator *tacc = (ArrayAccumulator *) acc;
/* elog(INFO, "leaf: %s", jsonbv_to_string(NULL, val)); */
if( val != NULL ) {
tacc->acc = accumArrayResult(tacc->acc, (Datum) JsonbValueToJsonb(val), false, JSONBOID, CurrentMemoryContext);
}
}
static
int to_json_path(JsonbValue *arr, JsonbValue **pathArr) {
int path_len = 0;
JsonbIterator *iter;
JsonbValue *item;
int next_it;
if (arr != NULL && arr->type == jbvBinary){
item = palloc(sizeof(JsonbValue));
iter = JsonbIteratorInit((JsonbContainer *) arr->val.binary.data);
next_it = JsonbIteratorNext(&iter, item, true);
if(next_it == WJB_BEGIN_ARRAY){
while ((next_it = JsonbIteratorNext(&iter, item, true)) != WJB_DONE){
/* elog(INFO, "next: %s", jsonbv_to_string(NULL, item)); */
if(next_it == WJB_ELEM){
pathArr[path_len] = item;
path_len++;
}
item = palloc(sizeof(JsonbValue));
}
}
pathArr[path_len + 1] = NULL;
return path_len;
}
return 0;
}
static int
reduce_paths(Jsonb *value, Jsonb *paths, void *acc, reduce_fn fn) {
JsonbValue jdoc;
initJsonbValue(&jdoc, value);
JsonbValue jpaths;
initJsonbValue(&jpaths, paths);
JsonbIterator *path_iter;
JsonbValue path_item;
int next_it;
JsonbValue *pathArr[100];
int path_len;
long num_results = 0;
if (jpaths.type == jbvBinary) {
path_iter = JsonbIteratorInit((JsonbContainer *) jpaths.val.binary.data);
next_it = JsonbIteratorNext(&path_iter, &path_item, true);
if(next_it == WJB_BEGIN_ARRAY){
while ((next_it = JsonbIteratorNext(&path_iter, &path_item, true)) != WJB_DONE){
if(next_it == WJB_ELEM){
path_len = to_json_path(&path_item, pathArr);
num_results += reduce_path(&jdoc, pathArr, 0, path_len, acc, fn);
}
}
}
}
return num_results;
}
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(knife_extract);
Datum
knife_extract(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
ArrayAccumulator acc;
acc.acc = NULL;
acc.case_insensitive = false;
long num_results = reduce_paths(value, paths, &acc, reduce_jsonb_array);
if (num_results > 0 && acc.acc != NULL)
PG_RETURN_ARRAYTYPE_P(makeArrayResult(acc.acc, CurrentMemoryContext));
else
PG_RETURN_NULL();
}
static
void reduce_text_array(void *acc, JsonbValue *val){
ArrayAccumulator *tacc = (ArrayAccumulator *) acc;
/* elog(INFO, "leaf: %s", jsonbv_to_string(NULL, val)); */
if( val != NULL && jsonbv_type(val) == JVString ) {
tacc->acc = accumArrayResult(tacc->acc,
(Datum) jsonbv_to_text(NULL, val),
false, TEXTOID, CurrentMemoryContext);
}
}
PG_FUNCTION_INFO_V1(knife_extract_text);
Datum
knife_extract_text(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
ArrayAccumulator acc;
acc.acc = NULL;
acc.case_insensitive = false;
long num_results = reduce_paths(value, paths, &acc, reduce_text_array);
if (num_results > 0 && acc.acc != NULL)
PG_RETURN_ARRAYTYPE_P(makeArrayResult(acc.acc, CurrentMemoryContext));
else
PG_RETURN_NULL();
}
static
void update_numeric(NumericAccumulator *nacc, Numeric num){
if(nacc->acc == NULL){
nacc->acc = num;
} else {
bool gt = DirectFunctionCall2(numeric_gt, (Datum) nacc->acc, (Datum) num);
/* elog(INFO, "%s > %s, gt %d min %d", numeric_to_cstring(num), numeric_to_cstring(nacc->acc), gt, nacc->minmax); */
if (nacc->minmax == min && gt == 1){
nacc->acc = num;
} else if (nacc->minmax == max && gt == 0){
nacc->acc = num;
}
}
}
static
void reduce_numeric(void *acc, JsonbValue *val){
NumericAccumulator *nacc = acc;
/* elog(INFO, "extract as number [%s] %s", nacc->element_type, jsonbv_to_string(NULL, val)); */
if( val == NULL || val->type == jbvNull) {return;}
if( val->type == jbvNumeric){
update_numeric(nacc, val->val.numeric);
} else if( val->type == jbvString){
long len =val->val.string.len;
char *num_str = palloc( len+ 1);
memcpy(num_str, val->val.string.val, len);
num_str[len] = '\0';
update_numeric(nacc, DatumGetNumeric(DirectFunctionCall3(numeric_in, CStringGetDatum(num_str), 0, -1)));
} else {
elog(ERROR, "Could not extract as number %s", jsonbv_to_string(NULL, val));
}
}
PG_FUNCTION_INFO_V1(knife_extract_max_numeric);
Datum
knife_extract_max_numeric(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
NumericAccumulator acc;
acc.minmax = max;
acc.acc = NULL;
reduce_paths(value, paths, &acc, reduce_numeric);
if (acc.acc != NULL)
PG_RETURN_NUMERIC(acc.acc);
else
PG_RETURN_NULL();
}
PG_FUNCTION_INFO_V1(knife_extract_min_numeric);
Datum
knife_extract_min_numeric(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
NumericAccumulator acc;
acc.minmax = min;
acc.acc = NULL;
reduce_paths(value, paths, &acc, reduce_numeric);
if (acc.acc != NULL)
PG_RETURN_NUMERIC(acc.acc);
else
PG_RETURN_NULL();
}
static
void reduce_numeric_array(void *acc, JsonbValue *val){
ArrayAccumulator *tacc = (ArrayAccumulator *) acc;
/* elog(INFO, "leaf: %s", jsonbv_to_string(NULL, val)); */
if( val != NULL && jsonbv_type(val) == JVNumeric ) {
tacc->acc = accumArrayResult(tacc->acc,
(Datum) val->val.numeric,
false, NUMERICOID, CurrentMemoryContext);
}
}
PG_FUNCTION_INFO_V1(knife_extract_numeric);
Datum
knife_extract_numeric(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
ArrayAccumulator acc;
acc.acc = NULL;
acc.case_insensitive = false;
long num_results = reduce_paths(value, paths, &acc, reduce_numeric_array);
if (num_results > 0 && acc.acc != NULL)
PG_RETURN_ARRAYTYPE_P(makeArrayResult(acc.acc, CurrentMemoryContext));
else
PG_RETURN_NULL();
}
LocalNullableDatum
date_bound(char *date_str, long str_len, MinMax minmax) {
LocalNullableDatum result;
if(date_str != NULL) {
/* elog(INFO, "date_str: '%s', %d", date_str, str_len ); */
char *ref_str = "0000-01-01T00:00:00";
long ref_str_len = strlen(ref_str);
long date_in_len = (str_len > ref_str_len) ? str_len : ref_str_len;
char *date_in = palloc(date_in_len + 1);
memcpy(date_in, date_str, str_len);
if(str_len > 18) {
date_in[str_len] = '\0';
Datum datum = DirectFunctionCall3(timestamptz_in,
CStringGetDatum(date_in),
ObjectIdGetDatum(InvalidOid),
Int32GetDatum(-1));
result.isnull = false;
result.value = datum;
return result;
}
if( str_len < ref_str_len){
long diff = (ref_str_len - str_len);
memcpy(date_in + str_len, ref_str + str_len, diff);
}
date_in[date_in_len] = '\0';
/* elog(INFO, "input: '%s', %d, %d", date_in, date_in_len, ref_str_len); */
Datum min_date = DirectFunctionCall3(timestamptz_in,
CStringGetDatum(date_in),
ObjectIdGetDatum(InvalidOid),
Int32GetDatum(-1));
if(minmax == min) {
result.isnull = false;
result.value = min_date;
return result;
} else if (minmax == max ) {
Timestamp max_date;
int tz;
struct pg_tm tt, *tm = &tt;
fsec_t fsec;
if (timestamp2tm(min_date, &tz, tm, &fsec, NULL, NULL) != 0)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
/* elog(INFO, "get tm %d y %d m %d d %d fsec", tm->tm_year, tm->tm_mon, tm->tm_mday, fsec); */
if (str_len < 5) {
tm->tm_mon = 12;
}
if (str_len < 8) {
tm->tm_mday = day_tab[isleap(tm->tm_year)][tm->tm_mon - 1];
}
if (str_len < 11) {
tm->tm_hour = 23;
}
if (str_len < 14) {
tm->tm_min = 59;
tm->tm_sec = 59;
}
if (str_len < 17) {
tm->tm_sec = 59;
}
/* turn of this millisecond suspicios transform */
/* round fsec up .555 to .555999 */
/* this is not strict algorytm so if user enter .500 we will lose 00 */
/* better to analyze initial string */
/* int fsec_up = 0, temp, count = 1; */
/* if(fsec == 0){ */
/* fsec_up = 999999; */
/* } else { */
/* temp = fsec; */
/* while(temp > 0) { */
/* if(temp%10 == 0) { */
/* temp = temp/10; */
/* fsec_up += 9 * count; */
/* count= count * 10; */
/* } else { */
/* break; */
/* } */
/* } */
/* } */
if (tm2timestamp(tm, fsec, &tz, &max_date) != 0)
ereport(ERROR,
(errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
errmsg("timestamp out of range")));
result.isnull = false;
result.value = TimestampGetDatum(max_date);
return result;
} else {
elog(ERROR, "expected min or max value");
}
} else {
result.isnull = true;
return result;
}
}
static
void reduce_timestamptz(void *acc, JsonbValue *val){
DateAccumulator *dacc = acc;
/* elog(INFO, "extract as date %s as %s", jsonbv_to_string(NULL, val), dacc->element_type); */
if(val != NULL && val->type == jbvString) {
LocalNullableDatum date = date_bound(val->val.string.val, val->val.string.len, dacc->minmax);
if (date.isnull) {
return;
}
if(dacc->minmax == min) {
if(!dacc->acc.isnull){
int gt = DirectFunctionCall2(timestamptz_cmp_timestamp, date.value, dacc->acc.value);
/* elog(INFO, "compare %d", gt); */
if(gt < 0) {
dacc->acc = date;
}
} else {
dacc->acc = date;
}
} else if (dacc->minmax == max ) {
if(!dacc->acc.isnull){
int gt = DirectFunctionCall2(timestamptz_cmp_timestamp, date.value, dacc->acc.value);
if(gt > 0) {
dacc->acc = date;
}
} else {
dacc->acc = date;
}
} else {
elog(ERROR, "expected min or max value");
}
}
}
PG_FUNCTION_INFO_V1(knife_extract_max_timestamptz);
Datum
knife_extract_max_timestamptz(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
DateAccumulator acc;
acc.minmax = max;
LocalNullableDatum datum;
datum.isnull = true;
acc.acc = datum;
reduce_paths(value, paths, &acc, reduce_timestamptz);
if (!acc.acc.isnull)
PG_RETURN_NUMERIC(acc.acc.value);
else
PG_RETURN_NULL();
}
PG_FUNCTION_INFO_V1(knife_extract_min_timestamptz);
Datum
knife_extract_min_timestamptz(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
DateAccumulator acc;
acc.minmax = min;
LocalNullableDatum datum;
datum.isnull = true;
acc.acc = datum;
reduce_paths(value, paths, &acc, reduce_timestamptz);
if (!acc.acc.isnull)
PG_RETURN_NUMERIC(acc.acc.value);
else
PG_RETURN_NULL();
}
static
void reduce_timestamptz_array(void *acc, JsonbValue *val){
ArrayAccumulator *tacc = (ArrayAccumulator *) acc;
/* elog(INFO, "leaf: %s", jsonbv_to_string(NULL, val)); */
if( val != NULL && jsonbv_type(val) == JVString ) {
LocalNullableDatum result = date_bound(val->val.string.val, val->val.string.len, min);
tacc->acc = accumArrayResult(tacc->acc,
result.value,
result.isnull, TIMESTAMPTZOID, CurrentMemoryContext);
}
}
PG_FUNCTION_INFO_V1(knife_extract_timestamptz);
Datum
knife_extract_timestamptz(PG_FUNCTION_ARGS) {
Jsonb *value = PG_GETARG_JSONB(0);
Jsonb *paths = PG_GETARG_JSONB(1);
ArrayAccumulator acc;
acc.acc = NULL;
acc.case_insensitive = false;
long num_results = reduce_paths(value, paths, &acc, reduce_timestamptz_array);
if (num_results > 0 && acc.acc != NULL)
PG_RETURN_ARRAYTYPE_P(makeArrayResult(acc.acc, CurrentMemoryContext));
else
PG_RETURN_NULL();
}
PG_FUNCTION_INFO_V1(knife_date_bound);
Datum
knife_date_bound(PG_FUNCTION_ARGS) {
char *date = text_to_cstring(PG_GETARG_TEXT_P(0));
MinMax minmax = minmax_from_string(text_to_cstring(PG_GETARG_TEXT_P(1)));
LocalNullableDatum res = date_bound(date, strlen(date), minmax);
if(!res.isnull){
return res.value;
} else {
PG_RETURN_NULL();
}
}