-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpg_utilities.sql
More file actions
4271 lines (3406 loc) · 169 KB
/
pg_utilities.sql
File metadata and controls
4271 lines (3406 loc) · 169 KB
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
CREATE SCHEMA IF NOT EXISTS ub
AUTHORIZATION postgres;
GRANT ALL ON SCHEMA ub TO postgres;
-- FUNCTION: ub.util_array_float(double precision[], double precision[], text)
-- DROP FUNCTION IF EXISTS ub.util_array_float(double precision[], double precision[], text);
CREATE OR REPLACE FUNCTION ub.util_array_float(
lntotaldata double precision[],
lnupdatedata double precision[],
lcaggfunc text DEFAULT 'SUM'::text)
RETURNS double precision[]
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_array_float
@desc Process two float arrays. Arrays with different sizes are automatically expanded to the largest one
@desc Aggregate function ub.agg_array_float(lnUpdateData, lcAggFunc) is defined too
@param float[] $1 - initial float array
@param float[] $2 - float array to sum up or merge with
@params text $3 - aggregate function
- SUM: sum two float arrays, with adjusting their length
- MERGE: merge two float arrays
- MERGE_UNIQUE: merge two float arrays with eliminating duplicates
- MERGE_NNN: merge the second array at NNN position
@return float[] - processed float array
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#float array #float array merge #array adjust #array aggregate
*/
BEGIN
lcAggFunc := upper(lcAggFunc);
CASE
-- Sum two float arrays with adjusting their lenghts
WHEN lcAggFunc = 'SUM' THEN
-- Initial array is larger than the second one
IF COALESCE(cardinality(lnTotalData), 0) > COALESCE(cardinality(lnUpdateData), 0) THEN
RETURN (
SELECT
array_agg(COALESCE("element_data".value, 0) + COALESCE(lnUpdateData["element_data".order_id], 0))
FROM unnest(lnTotalData) WITH ORDINALITY AS element_data(value, order_id)
);
-- Initial array is not larger than the second one
ELSE
RETURN (
SELECT
array_agg(COALESCE("element_data".value, 0) + COALESCE(lnTotalData["element_data".order_id], 0))
FROM unnest(lnUpdateData) WITH ORDINALITY AS element_data(value, order_id)
);
END IF;
-- Merge two arrays
WHEN lcAggFunc = 'MERGE' THEN
RETURN lnTotalData || lnUpdateData;
-- Merge the second array at position nnn
WHEN lcAggFunc ~ 'MERGE[0-9]{1,}' THEN
RETURN
-- basic array
lnTotalData
||
-- zero values to fill
array_fill(0::float, ARRAY[GREATEST(substr(lcAggFunc,6)::integer - COALESCE(array_length(lnTotalData, 1), 0) - 1, 0)])
||
-- merged array
lnUpdateData;
-- Merge two arrays with removing duplicates
WHEN lcAggFunc = 'MERGE_UNIQUE' THEN
RETURN
(
SELECT
array_agg(COALESCE(basic_id, update_id))
FROM unnest(lnTotalData) basic_id
FULL JOIN unnest(lnUpdateData) update_id ON
(update_id = basic_id)
);
-- unknown aggregate function => no processing
ELSE
RETURN lnTotalData;
END CASE;
END;
/*
@example
SELECT ub.util_array_float(ARRAY[0.5, 2.1], ARRAY[0.3, 3.2, 5.5], 'SUM');
{0.8,5.3,5.5}
SELECT ub.util_array_float(ARRAY[0.5, 2.1], ARRAY[0.3, 2.1, 5.5], 'MERGE');
{0.5,2.1,0.3,2.1,5.5}
SELECT ub.util_array_float(ARRAY[0.5, 2.1], ARRAY[0.3, 2.1, 5.5], 'MERGE_UNIQUE');
{0.3,2.1,5.5,0.5}
SELECT ub.util_array_float(ARRAY[0.5, 2.1], ARRAY[0.3, 2.1, 5.5], 'MERGE5');
{0.5,2.1,0,0,0.3,2.1,5.5}
*/
$BODY$;
ALTER FUNCTION ub.util_array_float(double precision[], double precision[], text)
OWNER TO postgres;
/*
@function ub.agg_array_float
@desc Aggregate function for operations with float arrays:
- SUM: sum two float arrays, with adjusting their length
- MERGE: merge two float arrays
- MERGE_UNIQUE: merge two float arrays with eliminating duplicates
- MERGE_NNN: merge the second array at NNN position
*/
CREATE OR REPLACE AGGREGATE ub.agg_array_float(double precision[], text) (
SFUNC = ub.util_array_float,
STYPE = float8[] ,
FINALFUNC_MODIFY = READ_ONLY,
MFINALFUNC_MODIFY = READ_ONLY
);
-- FUNCTION: ub.util_array_integer(integer[], integer[], text)
-- DROP FUNCTION IF EXISTS ub.util_array_integer(integer[], integer[], text);
CREATE OR REPLACE FUNCTION ub.util_array_integer(
lntotaldata integer[],
lnupdatedata integer[],
lcaggfunc text DEFAULT 'SUM'::text)
RETURNS integer[]
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_array_integer
@desc Process two integer arrays. Arrays with different sizes are automatically expanded to the largest one
@desc Aggregate function ub.agg_array_integer(lnUpdateData, lcAggFunc) is defined too
@param integer[] $1 - initial integer array
@param integer[] $2 - integer array to sum up or merge with
@params text $3 -
- SUM: sum two integer arrays, with adjusting their length
- MERGE: merge two integer arrays
- MERGE_UNIQUE: merge two integer arrays with eliminating duplicates
- MERGE_NNN: merge the second array at NNN position
@return integer[] - processed float array
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#integer array #integer array merge #array adjust #array aggregate
*/
BEGIN
lcAggFunc := upper(lcAggFunc);
CASE
-- Merge two integer arrays
WHEN lcAggFunc = 'MERGE' THEN
RETURN lnTotalData || lnUpdateData;
-- Merge two integer arrays eliminating duplicates
WHEN lcAggFunc = 'MERGE_UNIQUE' THEN
IF lnTotalData IS NULL THEN
RETURN lnUpdateData;
ELSE
RETURN (
SELECT
array_agg(COALESCE(basic_id, update_id))
FROM unnest(lnTotalData) basic_id
FULL JOIN unnest(lnUpdateData) update_id ON
(update_id = basic_id)
);
END IF;
-- Merge the second array at position nnn
WHEN lcAggFunc ~ 'MERGE[0-9]{1,}' THEN
RETURN
lnTotalData
||
array_fill(0::integer, ARRAY[GREATEST(substr(lcAggFunc,6)::integer - COALESCE(array_length(lnTotalData, 1), 0) - 1, 0)])
||
lnUpdateData;
-- Sum up two integer arrays with adjusting their sizes
WHEN lcAggFunc = 'SUM' THEN
-- Initial array is larger than the second one
IF COALESCE(cardinality(lnTotalData), 0) > COALESCE(cardinality(lnUpdateData), 0) THEN
RETURN (
SELECT
array_agg(COALESCE("element_data".value, 0) + COALESCE(lnUpdateData["element_data".order_id], 0))
FROM unnest(lnTotalData) WITH ORDINALITY AS element_data(value, order_id)
);
-- Initial array is not larger than the second one
ELSE
RETURN (
SELECT
array_agg(COALESCE("element_data".value, 0) + COALESCE(lnTotalData["element_data".order_id], 0))
FROM unnest(lnUpdateData) WITH ORDINALITY AS element_data(value, order_id)
);
END IF;
-- Unknown aggregated function => no processing
ELSE
RETURN lnTotalData;
END CASE;
END;
/*
@example
SELECT ub.util_array_integer(ARRAY[5, 2], ARRAY[3, 2, 8], 'SUM');
{8,4,8}
SELECT ub.util_array_integer(ARRAY[5, 2], ARRAY[3, 2, 8], 'MERGE');
{5,2,3,2,8}
SELECT ub.util_array_integer(ARRAY[5, 2], ARRAY[3, 2, 8], 'MERGE_UNIQUE');
{2,3,5,8}
SELECT ub.util_array_integer(ARRAY[5, 2], ARRAY[3, 2, 8], 'MERGE5');
{5,2,0,0,3,2,8}
*/
$BODY$;
ALTER FUNCTION ub.util_array_integer(integer[], integer[], text)
OWNER TO postgres;
/*
@function ub.agg_array_integer
@desc Aggregate function for operations with integer arrays:
- SUM: sum two float arrays, with adjusting their length
- MERGE: merge two float arrays
- MERGE_UNIQUE: merge two float arrays with eliminating duplicates
- MERGE_NNN: merge the second array at NNN position
*/
CREATE OR REPLACE AGGREGATE ub.agg_array_integer(integer[], text) (
SFUNC = ub.util_array_integer,
STYPE = int4[] ,
FINALFUNC_MODIFY = READ_ONLY,
MFINALFUNC_MODIFY = READ_ONLY
);
-- FUNCTION: ub.util_array_merge(double precision[], double precision[], integer)
-- DROP FUNCTION IF EXISTS ub.util_array_merge(double precision[], double precision[], integer);
CREATE OR REPLACE FUNCTION ub.util_array_merge(
lntotaldata double precision[],
lnupdatedata double precision[],
lnposid integer)
RETURNS double precision[]
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_array_merge
@desc Quick merge of the second float array at the lnPosID of the first float array
@desc Aggregate function ub.agg_array_float_merge(lnUpdateData, lnPosID) is defined too
@param float[] $1 - initial float array
@param float[] $2 - float array to merge at lnPosID
@params integer $3 - position the second array should be inserted at
@return float[] - merged float array
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#float array #float array merge
*/
BEGIN
RETURN
-- basic array
lnTotalData
||
-- zero values to fill the basic array till lnPosID
array_fill(0::float, ARRAY[GREATEST(lnPosID - COALESCE(array_length(lnTotalData, 1), 0) - 1, 0)])
||
-- merged array
lnUpdateData;
END;
/*
@example
SELECT ub.util_array_merge(ARRAY[0.5, 2.1], ARRAY[0.3, 2.1, 5.5], 5);
{0.5,2.1,0,0,0.3,2.1,5.5}
*/
$BODY$;
ALTER FUNCTION ub.util_array_merge(double precision[], double precision[], integer)
OWNER TO postgres;
/*
@function ub.agg_array_merge
@desc Aggregate function to merge two float arrays at arbitrary position
*/
CREATE OR REPLACE AGGREGATE ub.agg_array_merge(double precision[], integer) (
SFUNC = ub.util_array_merge,
STYPE = float8[] ,
FINALFUNC_MODIFY = READ_ONLY,
MFINALFUNC_MODIFY = READ_ONLY
);
-- FUNCTION: ub.util_jsonb_array(jsonb, jsonb, text)
-- DROP FUNCTION IF EXISTS ub.util_jsonb_array(jsonb, jsonb, text);
CREATE OR REPLACE FUNCTION ub.util_jsonb_array(
ljinitialarray jsonb,
ljmergedarray jsonb,
lcarrayflag text DEFAULT 'add'::text)
RETURNS jsonb
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_jsonb_array
@desc process two arrays with replacing | expanding | adding | subtracting | intersecting
@desc Aggregate function ub.agg_jsonb_array(ljMergedArray, lcArrayFlag) is defined too
@param array $1 - initial array
@param array $2 - merged array
@param string|null $3 - how to merge arrays
- replace - replace "initial" array with "merged" array
- expand - add all new keys from "merged" array to "initial" array (exclude duplicates)
- add - add all keys from "merged" array to "initial" array (duplicates are possible) (default)
- sub - subtract elements of the merged array from initial array
- intersect - calculate common keys in both array
@return array $1 - processed array
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#jsonb array #merge jsonb array #expand jsonb array #replace jsonb array #subtract jsonb array #intersect jsonb array
*/
BEGIN
IF (jsonb_typeof(ljInitialArray) IS DISTINCT FROM 'array' AND lcArrayFlag IN ('add', 'expand', 'intersect'))
OR lcArrayFlag = 'replace' THEN
-- Replace array with the "merged" one
RETURN
CASE
WHEN jsonb_typeof(ljMergedArray) IS DISTINCT FROM 'array'
OR lcArrayFlag = 'intersect'
THEN jsonb_build_array()
ELSE ljMergedArray
END;
ELSEIF jsonb_typeof(ljMergedArray) IS DISTINCT FROM 'array' THEN
-- Keep "initial" array as-is
RETURN
CASE
WHEN jsonb_typeof(ljInitialArray) IS DISTINCT FROM 'array'
OR lcArrayFlag = 'intersect'
THEN jsonb_build_array()
ELSE ljInitialArray
END;
ELSEIF lcArrayFlag = 'add' THEN
-- concatenate two arrays
RETURN ljInitialArray || ljMergedArray;
ELSEIF lcArrayFlag = 'expand' THEN
-- concatenate two arrays and exclude duplicates for "number", "string", "boolean" types
RETURN
ljInitialArray
||
COALESCE(
(
WITH
-- unnest merged array
"merged_data" AS MATERIALIZED (
SELECT
ROW_NUMBER() OVER() AS row_id,
merged_element
FROM jsonb_array_elements(ljMergedArray) merged_element
WHERE merged_element IS NOT NULL
),
-- exclude duplicates in merged array
"exclude_duplicates" AS MATERIALIZED (
SELECT
"merged_data".row_id,
ROW_NUMBER() OVER(PARTITION BY "merged_data".merged_element) AS duplicate_id,
"merged_data".merged_element
FROM "merged_data"
)
-- add new elements only
SELECT
jsonb_agg("exclude_duplicates".merged_element ORDER BY "exclude_duplicates".row_id)
FROM "exclude_duplicates"
WHERE "exclude_duplicates".duplicate_id = 1
AND NOT ljInitialArray @> jsonb_build_array("exclude_duplicates".merged_element)
),
jsonb_build_array()
);
ELSEIF lcArrayFlag = 'sub'
AND jsonb_typeof(ljInitialArray) IS NOT DISTINCT FROM 'array' THEN
-- subtract elements of the merged array from initial array
RETURN
COALESCE(
(
SELECT
jsonb_agg(initial_element)
FROM jsonb_array_elements(ljInitialArray) initial_element
LEFT JOIN jsonb_array_elements(ljMergedArray) deleted_element ON
deleted_element = initial_element
WHERE deleted_element IS NULL
),
jsonb_build_array()
);
ELSEIF lcArrayFlag = 'intersect' THEN
-- intersect two arrays
RETURN COALESCE(
(
SELECT
jsonb_agg(initial_element)
FROM jsonb_array_elements(ljInitialArray) initial_element
INNER JOIN jsonb_array_elements(ljMergedArray) merged_element ON
merged_element = initial_element
),
jsonb_build_array()
);
ELSE
-- unknown command => return initial array
RETURN ljInitialArray;
END IF;
END;
/*
@example:
SELECT ub.util_jsonb_array('[2,3]'::jsonb, '[4,3]'::jsonb, 'expand')
=> [2,3,4]
SELECT ub.util_jsonb_array('[2,3]'::jsonb, '[4,3]'::jsonb, 'replace')
=> [4,3]
SELECT ub.util_jsonb_array('[2,3]'::jsonb, '[4,3]'::jsonb, 'add')
=> [2,3,4,3]
SELECT ub.util_jsonb_array('[2,3,4,5]'::jsonb, '[4,3]'::jsonb, 'sub')
=> [2,5]
SELECT ub.util_jsonb_array('[2,3,4,5]'::jsonb, '[4,3,1]'::jsonb, 'intersect')
=> [3,4]
*/
$BODY$;
ALTER FUNCTION ub.util_jsonb_array(jsonb, jsonb, text)
OWNER TO postgres;
/*
@function ub.agg_jsonb_array
@desc Aggregate function to process two jsonb arrays
- replace - replace "initial" array with "merged" array
- expand - add all new keys from "merged" array to "initial" array (exclude duplicates)
- add - add all keys from "merged" array to "initial" array (duplicates are possible) (default)
- sub - subtract elements of the merged array from initial array
- intersect - calculate common keys in both array
*/
CREATE OR REPLACE AGGREGATE ub.agg_jsonb_array(jsonb, text) (
SFUNC = ub.util_jsonb_array,
STYPE = jsonb ,
FINALFUNC_MODIFY = READ_ONLY,
MFINALFUNC_MODIFY = READ_ONLY
);
-- FUNCTION: ub.util_jsonb_concat(jsonb, jsonb)
-- DROP FUNCTION IF EXISTS ub.util_jsonb_concat(jsonb, jsonb);
CREATE OR REPLACE FUNCTION ub.util_jsonb_concat(
ljinitialobject jsonb,
ljconcatobject jsonb)
RETURNS jsonb
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_jsonb_concat
@desc concatenate two objects, considering NULL values
@desc Aggregate function ub.agg_jsonb_concat(ljConcatObject) is defined too
@param object $1 - initial object
@param object $2 - concatenated object
@return object $1 - concatenated object
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#object #merge object #expand array #replace array #add array
*/
BEGIN
IF jsonb_typeof(ljInitialObject) IS DISTINCT FROM 'object' THEN
-- one of objects is null => return the second one
RETURN
CASE
WHEN jsonb_typeof(ljConcatObject) IS DISTINCT FROM 'object'
THEN jsonb_build_object()
ELSE ljConcatObject
END;
ELSEIF jsonb_typeof(ljConcatObject) IS DISTINCT FROM 'object' THEN
-- one of objects is null => return the second one
RETURN ljInitialObject;
END IF;
-- Build response
RETURN ljInitialObject || ljConcatObject;
END;
/*
@example:
SELECT ub.util_jsonb_concat('{"a":{"b":{"c": 1}}}'::jsonb, '{"a":{"b":{"d": 5}}}'::jsonb)
=> {"a":{"b":{"d": 5}}}
SELECT ub.util_jsonb_concat('{"a":{"b":{"c": 1}}}'::jsonb, NULL::jsonb)
=> {"a":{"b":{"c": 1}}}
SELECT ub.util_jsonb_concat(NULL::jsonb, '{"a":{"b":{"c": 1}}}'::jsonb)
=> {"a":{"b":{"d": 5}}}
*/
$BODY$;
ALTER FUNCTION ub.util_jsonb_concat(jsonb, jsonb)
OWNER TO postgres;
/*
@function ub.agg_jsonb_concat
@desc Aggregate function to concatenate two jsonb arrays
*/
CREATE OR REPLACE AGGREGATE ub.agg_jsonb_concat(jsonb) (
SFUNC = ub.util_jsonb_concat,
STYPE = jsonb ,
FINALFUNC_MODIFY = READ_ONLY,
MFINALFUNC_MODIFY = READ_ONLY
);
-- FUNCTION: ub.util_jsonb_merge(jsonb, jsonb, text)
-- DROP FUNCTION IF EXISTS ub.util_jsonb_merge(jsonb, jsonb, text);
CREATE OR REPLACE FUNCTION ub.util_jsonb_merge(
ljinitialobject jsonb,
ljupdatedkeys jsonb,
lcarrayflag text DEFAULT 'expand'::text)
RETURNS jsonb
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_jsonb_merge
@desc merge json object | array | any json type under following rules:
@desc - the appropriate key in the initial object is being expanded with non-null value
@desc - if updated key is ended with ".", the appropriate key in the initial object is being replaced with updated value
@desc - arrays are merged using lcArrayFlag parameter
@desc - "string", "number", "boolean" type are being replaced
@desc Aggregate function ub.agg_jsonb_merge(jsonb, text) is defined too
@param any $1 - initial object | array | any other json type
@param any $2 - object with updated keys & values | array | any other json type
@param string $3 - how to merge arrays: "expand" (default) | "add" | "replace"
@return object $1 - expanded object | array | any other json type
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#object #expand object #expand array #replace object #replace array #merge object #merge array
*/
BEGIN
-- process object with updated keys
IF jsonb_typeof(ljUpdatedKeys) IS NOT DISTINCT FROM 'object' THEN
-- Prepare initial object for further processing
IF jsonb_typeof(ljInitialObject) IS DISTINCT FROM 'object' THEN
ljInitialObject := jsonb_build_object();
END IF;
-- not an object type => merge data of other types
ELSE
-- UpdatedKeys is null
IF COALESCE(jsonb_typeof(ljUpdatedKeys), 'null') = 'null' THEN
RETURN
CASE
WHEN COALESCE(jsonb_typeof(ljInitialObject), 'null') = 'null'
-- both input parameters are null => return empty object
THEN jsonb_build_object()
-- return InitialObject as-is
ELSE ljInitialObject
END;
-- Merge to arrays
ELSEIF jsonb_typeof(ljInitialObject) IS NOT DISTINCT FROM 'array'
AND jsonb_typeof(ljUpdatedKeys) IS NOT DISTINCT FROM 'array' THEN
RETURN ub.util_jsonb_array(ljInitialObject, ljUpdatedKeys, lcArrayFlag);
-- Non object or array => return ljUpdatedKeys as-is
ELSE
RETURN ljUpdatedKeys;
END IF;
END IF;
-- Process updated keys
RETURN ub.util_jsonb_concat(
-- initial object
ljInitialObject,
-- add updated keys
(
SELECT
jsonb_object_agg(
-- key name (remove end "." is present)
rtrim("updated".key, '.'),
-- expanded value
CASE
-- "updated" key is "number" | "string" | "boolean" type => just replace with "updated" value
-- "updated" key is ended with "." => just replace with "updated" value
WHEN jsonb_typeof("updated".value) IN ('number', 'string', 'boolean')
OR "updated".key ~ '\.$' THEN
"updated".value
-- "initial" key is NULL => just replace with "updated" value
WHEN COALESCE(jsonb_typeof(ljInitialObject->("updated".key)), 'null') = 'null' THEN
"updated".value
-- updated value is NULL => keep ljInitialObject->("updated".key)
WHEN jsonb_typeof("updated".value) IN ('null') THEN
ljInitialObject->("updated".key)
-- "array" type => expand the array
WHEN jsonb_typeof("updated".value) IS NOT DISTINCT FROM 'array' THEN
ub.util_jsonb_array(
ljInitialObject->("updated".key),
"updated".value,
lcArrayFlag
)
-- "object" typee => run "ub.util_jsonb_merge" recursively
WHEN jsonb_typeof("updated".value) IS NOT DISTINCT FROM 'object' THEN
ub.util_jsonb_merge(
ljInitialObject->("updated".key),
"updated".value,
lcArrayFlag
)
ELSE
"updated".value
END
)
FROM jsonb_each(ljUpdatedKeys) AS updated(key, value)
)
);
END;
/*
@example:
SELECT ub.util_jsonb_merge('{"a": {"b": {"c": 1}}}'::jsonb, '{"a": {"b": {"d": 5}}}'::jsonb, 'expand')
=> {"a": {"b": {"c": 1, "d": 5}}} (objects are expanded)
SELECT ub.util_jsonb_merge('{"a.b": {"c": 5}}'::jsonb, '{"a.b": {"d": 8}}'::jsonb, 'expand')
=> {"a.b": {"c": 5, "d": 8}} (objects are expanded)
SELECT ub.util_jsonb_merge('{"a": {"c": 5, "d": [1,2]}}'::jsonb, '{"a": {"b": 8, "d": [3,4]}}'::jsonb, 'replace')
=> {"a":{"b":8,"c":5,"d":[3,4]}} (arrays are replaced)
SELECT ub.util_jsonb_merge('{"a": {"c": 5, "d": [1,2]}}'::jsonb, '{"a": {"b": 8, "d": [3,4]}}'::jsonb, 'add')
=> {"a":{"b":8,"c":5,"d":[1,2,3,4]}} (arrays are concatenated)
*/
$BODY$;
ALTER FUNCTION ub.util_jsonb_merge(jsonb, jsonb, text)
OWNER TO postgres;
/*
@function ub.agg_jsonb_merge
@desc Aggregate function to merge two multi-level jsonb arrays
*/
CREATE OR REPLACE AGGREGATE ub.agg_jsonb_merge(jsonb, text) (
SFUNC = ub.util_jsonb_merge,
STYPE = jsonb ,
FINALFUNC_MODIFY = READ_ONLY,
MFINALFUNC_MODIFY = READ_ONLY
);
-- FUNCTION: ub.util_jsonb_merge_null(jsonb, jsonb)
-- DROP FUNCTION IF EXISTS ub.util_jsonb_merge_null(jsonb, jsonb);
CREATE OR REPLACE FUNCTION ub.util_jsonb_merge_null(
ljinitialobject jsonb,
ljconcatobject jsonb)
RETURNS jsonb
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_jsonb_merge_null
@desc concatenate two objects and set all old keys to NULL values
@param object $1 - initial object
@param object $2 - concatenated object
@return object $1 - concatenated object
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#object #merge object #set null
*/
BEGIN
IF jsonb_typeof(ljInitialObject) IS DISTINCT FROM 'object' THEN
-- one of objects is null => return the second one
RETURN
CASE
WHEN jsonb_typeof(ljConcatObject) IS DISTINCT FROM 'object'
THEN jsonb_build_object()
ELSE ljConcatObject
END;
ELSEIF jsonb_typeof(ljConcatObject) IS DISTINCT FROM 'object' THEN
-- one of objects is null => return the second one
RETURN ljInitialObject;
END IF;
-- Build response
RETURN ljConcatObject || COALESCE(
(
SELECT
jsonb_object_agg("initial".key, NULL)
FROM jsonb_each(ljInitialObject) AS initial(key, value)
WHERE ljConcatObject->>("initial".key) IS NULL
),
jsonb_build_object()
);
END;
/*
@example:
SELECT ub.util_jsonb_merge_null('{"a": 1, "b": 2},'::jsonb, '{"b": 3}'::jsonb)
=> {"a": null, "b": 3}
*/
$BODY$;
ALTER FUNCTION ub.util_jsonb_merge_null(jsonb, jsonb)
OWNER TO postgres;
-- FUNCTION: ub.util_jsonb_multi_array(text, jsonb[])
-- DROP FUNCTION IF EXISTS ub.util_jsonb_multi_array(text, jsonb[]);
CREATE OR REPLACE FUNCTION ub.util_jsonb_multi_array(
lcarrayflag text,
VARIADIC ljarray jsonb[])
RETURNS jsonb
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_jsonb_multi_array
@desc process multiple arrays, considering NULL values and merge rules
@param string $1 - how to merge arrays
- expand - add all new keys from "merged" array to "initial" array (exclude duplicates)
- add - add all keys from "merged" array to "initial" array (duplicates are possible) (default)
- sub - subtract elements of the merged array from initial array
- intersect - calculate common keys in both array
@param array $n - arrays to process
@return object $1 - processed array
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#array #expand array #multiple arrays #add array #subtract array #intersect array
*/
DECLARE
ljResult jsonb := -- merge first two arrays
ub.util_jsonb_array(ljArray[1], ljArray[2], lcArrayFlag);
lnArrayID integer; -- array ID to merge
BEGIN
-- concatenate all arrays in the input array
FOR lnArrayID IN 3..array_length(ljArray, 1) LOOP
ljResult := ub.util_jsonb_array(ljResult, ljArray[lnArrayID], lcArrayFlag);
END LOOP;
RETURN ljResult;
END;
/*
@example:
SELECT ub.util_jsonb_multi_array('expand', '[2,3]'::jsonb, '[4,3]'::jsonb, '[5,3,2]'::jsonb)
=> [2,3,4,5]
SELECT ub.util_jsonb_multi_array('add', '[2,3]'::jsonb, '[4,3]'::jsonb, '[5,3,2]'::jsonb)
=> [2,3,4,3,5,3,2]
SELECT ub.util_jsonb_multi_array('intersect', '[2,3]'::jsonb, '[4,3]'::jsonb, '[5,3,2]'::jsonb)
=> [3]
*/
$BODY$;
ALTER FUNCTION ub.util_jsonb_multi_array(text, jsonb[])
OWNER TO postgres;
-- FUNCTION: ub.util_jsonb_multi_concat(jsonb[])
-- DROP FUNCTION IF EXISTS ub.util_jsonb_multi_concat(jsonb[]);
CREATE OR REPLACE FUNCTION ub.util_jsonb_multi_concat(
VARIADIC ljobject jsonb[])
RETURNS jsonb
LANGUAGE 'plpgsql'
COST 1
IMMUTABLE PARALLEL SAFE
AS $BODY$
/*
@function ub.util_jsonb_multi_concat
@desc concatenate multiple objects, considering NULL values
@param object $n - object to concatenate to the result
@return object $1 - concatenated object
@version 0.5.1
@author Oleg Pravdin <o.pravdin@unibackend.org>
#object #concat object #multiple concat
*/
DECLARE
ljResult jsonb := -- result object to response
CASE
WHEN jsonb_typeof(ljObject[1]) IS DISTINCT FROM 'object'
THEN jsonb_build_object()
ELSE ljObject[1]
END;
lnObject integer; -- object ID
BEGIN
-- concatenate all objects in the input array
FOR lnObject IN 2..array_length(ljObject, 1) LOOP
ljResult := ljResult ||
-- transform NULL to {}
CASE
WHEN jsonb_typeof(ljObject[lnObject]) IS DISTINCT FROM 'object'
THEN jsonb_build_object()
ELSE ljObject[lnObject]
END;