-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhelperFunctions.sql
More file actions
7771 lines (7269 loc) · 274 KB
/
Copy pathhelperFunctions.sql
File metadata and controls
7771 lines (7269 loc) · 274 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
------------------------------------------------------------------------------
-- PostgreSQL Table Tranlation Engine - Helper functions installation file
-- Version 0.1 for PostgreSQL 9.x
-- https://github.com/CASFRI/postTranslationEngine
--
-- This is free software; you can redistribute and/or modify it under
-- the terms of the GNU General Public Licence. See the COPYING file.
--
-- Copyright (C) 2018-2020 Pierre Racine <pierre.racine@sbf.ulaval.ca>,
-- Marc Edwards <medwards219@gmail.com>,
-- Pierre Vernier <pierre.vernier@gmail.com>
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_DefaultErrorCode
--
-- rule text - Name of the rule.
-- targetType text - Required type.
--
-- RETURNS text - Default error code for this rule.
--
-- Return a default error code of the specified type for the specified rule.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_DefaultErrorCode(text, text);
CREATE OR REPLACE FUNCTION TT_DefaultErrorCode(
rule text,
targetType text
)
RETURNS text AS $$
DECLARE
BEGIN
rule = lower(rule);
IF targetType = 'integer' OR targetType = 'int' OR targetType = 'double precision' THEN
RETURN CASE WHEN rule = 'translation_error' THEN '-3333'
WHEN rule = 'notnull' THEN '-8888'
WHEN rule = 'notempty' THEN '-8889'
WHEN rule = 'isint' THEN '-9995'
WHEN rule = 'isnumeric' THEN '-9995'
WHEN rule = 'isbetween' THEN '-9999'
WHEN rule = 'isgreaterthan' THEN '-9999'
WHEN rule = 'islessthan' THEN '-9999'
WHEN rule = 'haslength' THEN '-9997'
WHEN rule = 'isunique' THEN '-9997'
WHEN rule = 'matchtable' THEN '-9998'
WHEN rule = 'matchlist' THEN '-9998'
WHEN rule = 'sumintmatchlist' THEN '-9998'
WHEN rule = 'lengthmatchlist' THEN '-9998'
WHEN rule = 'notmatchlist' THEN '-9998'
WHEN rule = 'false' THEN '-8887'
WHEN rule = 'true' THEN '-8887'
WHEN rule = 'hascountofnotnull' THEN '-9997'
WHEN rule = 'hascountofnotnullorzero' THEN '-9997'
WHEN rule = 'isintsubstring' THEN '-9997'
WHEN rule = 'isbetweensubstring' THEN '-9999'
WHEN rule = 'matchlistsubstring' THEN '-9998'
WHEN rule = 'minindexnotnull' THEN '-8888'
WHEN rule = 'maxindexnotnull' THEN '-8888'
WHEN rule = 'minindexnotempty' THEN '-8889'
WHEN rule = 'maxindexnotempty' THEN '-8889'
WHEN rule = 'minindexisint' THEN '-9995'
WHEN rule = 'maxindexisint' THEN '-9995'
WHEN rule = 'minindexisbetween' THEN '-9999'
WHEN rule = 'maxindexisbetween' THEN '-9999'
WHEN rule = 'minindexmatchlist' THEN '-9998'
WHEN rule = 'maxindexmatchlist' THEN '-9998'
WHEN rule = 'minindexnotmatchlist' THEN '-9998'
WHEN rule = 'maxindexnotmatchlist' THEN '-9998'
WHEN rule = 'getindexnotmatchlist' THEN '-9998'
WHEN rule = 'isxminusybetween' THEN '-9999'
WHEN rule = 'matchlisttwice' THEN '-9998'
WHEN rule = 'geoisvalid' THEN '-7779'
WHEN rule = 'geointersects' THEN '-7778'
WHEN rule = 'geointersectiongreaterthan' THEN '-9999'
WHEN rule = 'coalesceisint' THEN '-9995'
WHEN rule = 'coalesceisbetween' THEN '-9999'
WHEN rule = 'hascountofmatchlist' THEN '-9997'
WHEN rule = 'alphanumericmatchlist' THEN '-9997'
WHEN rule = 'getindexnotnull' THEN '-8888'
WHEN rule = 'getindexnotempty' THEN '-8889'
WHEN rule = 'getindexisint' THEN '-9995'
WHEN rule = 'getindexisbetween' THEN '-9999'
WHEN rule = 'getindexmatchlist' THEN '-9998'
ELSE 'NO_DEFAULT_ERROR_CODE' END;
ELSIF targetType = 'geometry' THEN
RETURN CASE WHEN rule = 'translation_error' THEN NULL
WHEN rule = 'notnull' THEN NULL
WHEN rule = 'notempty' THEN NULL
WHEN rule = 'isint' THEN NULL
WHEN rule = 'isnumeric' THEN NULL
WHEN rule = 'isbetween' THEN NULL
WHEN rule = 'isgreaterthan' THEN NULL
WHEN rule = 'islessthan' THEN NULL
WHEN rule = 'haslength' THEN NULL
WHEN rule = 'isunique' THEN NULL
WHEN rule = 'matchtable' THEN NULL
WHEN rule = 'matchlist' THEN NULL
WHEN rule = 'sumintmatchlist' THEN NULL
WHEN rule = 'lengthmatchlist' THEN NULL
WHEN rule = 'notmatchlist' THEN NULL
WHEN rule = 'false' THEN NULL
WHEN rule = 'true' THEN NULL
WHEN rule = 'hascountofnotnull' THEN NULL
WHEN rule = 'hascountofnotnullorzero' THEN NULL
WHEN rule = 'isintsubstring' THEN NULL
WHEN rule = 'isbetweensubstring' THEN NULL
WHEN rule = 'matchlistsubstring' THEN NULL
WHEN rule = 'minindexnotnull' THEN NULL
WHEN rule = 'maxindexnotnull' THEN NULL
WHEN rule = 'minindexnotempty' THEN NULL
WHEN rule = 'maxindexnotempty' THEN NULL
WHEN rule = 'minindexisint' THEN NULL
WHEN rule = 'maxindexisint' THEN NULL
WHEN rule = 'minindexisbetween' THEN NULL
WHEN rule = 'maxindexisbetween' THEN NULL
WHEN rule = 'minindexmatchlist' THEN NULL
WHEN rule = 'maxindexmatchlist' THEN NULL
WHEN rule = 'minindexnotmatchlist' THEN NULL
WHEN rule = 'maxindexnotmatchlist' THEN NULL
WHEN rule = 'getindexnotmatchlist' THEN NULL
WHEN rule = 'isxminusybetween' THEN NULL
WHEN rule = 'matchlisttwice' THEN NULL
WHEN rule = 'geoisvalid' THEN NULL
WHEN rule = 'geointersects' THEN NULL
WHEN rule = 'geointersectiongreaterthan' THEN NULL
WHEN rule = 'coalesceisint' THEN NULL
WHEN rule = 'coalesceisbetween' THEN NULL
WHEN rule = 'hascountofmatchlist' THEN NULL
WHEN rule = 'alphanumericmatchlist' THEN NULL
WHEN rule = 'getindexnotnull' THEN NULL
WHEN rule = 'getindexnotempty' THEN NULL
WHEN rule = 'getindexisint' THEN NULL
WHEN rule = 'getindexisbetween' THEN NULL
WHEN rule = 'getindexmatchlist' THEN NULL
ELSE 'NO_DEFAULT_ERROR_CODE' END;
ELSE
RETURN CASE WHEN rule = 'translation_error' THEN 'TRANSLATION_ERROR'
WHEN rule = 'notnull' THEN 'NULL_VALUE'
WHEN rule = 'notempty' THEN 'EMPTY_STRING'
WHEN rule = 'isint' THEN 'WRONG_TYPE'
WHEN rule = 'isnumeric' THEN 'WRONG_TYPE'
WHEN rule = 'isbetween' THEN 'OUT_OF_RANGE'
WHEN rule = 'isgreaterthan' THEN 'OUT_OF_RANGE'
WHEN rule = 'islessthan' THEN 'OUT_OF_RANGE'
WHEN rule = 'haslength' THEN 'INVALID_VALUE'
WHEN rule = 'isunique' THEN 'INVALID_VALUE'
WHEN rule = 'matchtable' THEN 'NOT_IN_SET'
WHEN rule = 'matchlist' THEN 'NOT_IN_SET'
WHEN rule = 'lengthmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'sumintmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'notmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'false' THEN 'NOT_APPLICABLE'
WHEN rule = 'true' THEN 'NOT_APPLICABLE'
WHEN rule = 'hascountofnotnull' THEN 'INVALID_VALUE'
WHEN rule = 'hascountofnotnullorzero' THEN 'INVALID_VALUE'
WHEN rule = 'isintsubstring' THEN 'INVALID_VALUE'
WHEN rule = 'isbetweensubstring' THEN 'OUT_OF_RANGE'
WHEN rule = 'matchlistsubstring' THEN 'NOT_IN_SET'
WHEN rule = 'minindexnotnull' THEN 'NULL_VALUE'
WHEN rule = 'maxindexnotnull' THEN 'NULL_VALUE'
WHEN rule = 'minindexnotempty' THEN 'EMPTY_STRING'
WHEN rule = 'maxindexnotempty' THEN 'EMPTY_STRING'
WHEN rule = 'minindexisint' THEN 'WRONG_TYPE'
WHEN rule = 'maxindexisint' THEN 'WRONG_TYPE'
WHEN rule = 'minindexisbetween' THEN 'OUT_OF_RANGE'
WHEN rule = 'maxindexisbetween' THEN 'OUT_OF_RANGE'
WHEN rule = 'minindexmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'maxindexmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'minindexnotmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'maxindexnotmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'getindexnotmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'isxminusybetween' THEN 'OUT_OF_RANGE'
WHEN rule = 'matchlisttwice' THEN 'NOT_IN_SET'
WHEN rule = 'geoisvalid' THEN 'INVALID_VALUE'
WHEN rule = 'geointersects' THEN 'NO_INTERSECT'
WHEN rule = 'geointersectiongreaterthan' THEN 'OUT_OF_RANGE'
WHEN rule = 'coalesceisint' THEN 'WRONG_TYPE'
WHEN rule = 'coalesceisbetween' THEN 'OUT_OF_RANGE'
WHEN rule = 'hascountofmatchlist' THEN 'INVALID_VALUE'
WHEN rule = 'alphanumericmatchlist' THEN 'NOT_IN_SET'
WHEN rule = 'getindexnotnull' THEN 'NULL_VALUE'
WHEN rule = 'getindexnotempty' THEN 'EMPTY_STRING'
WHEN rule = 'getindexisint' THEN 'WRONG_TYPE'
WHEN rule = 'getindexisbetween' THEN 'OUT_OF_RANGE'
WHEN rule = 'getindexmatchlist' THEN 'NOT_IN_SET'
ELSE 'NO_DEFAULT_ERROR_CODE' END;
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Test helper functions
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_TestNullAndWrongTypeParams(int, text, text[])
--
-- baseTestNumber integer - Base number of the series of test being performed.
-- fctName string - Name of the function to be tested.
-- params text[] - Array of parameter names and their respective types. Must be
-- a multiple of 2.
--
-- Test a function assigning NULL and wrong types to every parameters in turn
-- starting at the second parameter. The first parameter of the function must
-- always of type text and it is not tested.
--
-- e.g. SELECT (TT_TestNullAndWrongTypeParams(21, 'TT_HasLength', ARRAY['length_test', 'int',
-- 'acceptNull', 'boolean',
-- 'removeSpaces', 'boolean'
-- ])).*
--------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_TestNullAndWrongTypeParams(int, text, text[]);
CREATE OR REPLACE FUNCTION TT_TestNullAndWrongTypeParams(
baseTestNumber int,
fctName text,
params text[]
)
RETURNS TABLE(number text, function_tested text, description text, passed boolean) AS $$
DECLARE
query text;
i integer;
j integer;
paramName text;
paramType text;
subnbr int = 0;
BEGIN
function_tested = fctName;
-- check that all parameters have an associated type (that the number of params parameters is a multiple of 2)
IF array_upper(params, 1) % 2 != 0 THEN
RAISE EXCEPTION 'ERROR when calling TT_TestNullAndWrongTypeParams(): params ARRAY must have an even number of parameters';
END IF;
FOR i IN 1..array_upper(params, 1)/2 LOOP
subnbr = subnbr + 1;
number = baseTestNumber::text || '.' || subnbr::text;
paramName = params[(i - 1) * 2 + 1];
-- test not NULL
query = 'SELECT ' || function_tested || '(''''val'''', ';
FOR j IN 1..array_upper(params, 1)/2 LOOP
paramType = params[(j - 1) * 2 + 2];
IF j = i THEN -- set this parameter to NULL
query = query || 'NULL::text, ';
ELSE -- set other parameters to a valid value
query = query || CASE WHEN paramType = 'int' OR paramType = 'numeric' THEN
'1::text, '
WHEN paramType = 'char' THEN
'0::text, '
WHEN paramType = 'boolean' THEN
'TRUE::text, '
WHEN paramType = 'stringlist' OR paramType = 'charlist' THEN
'''''{''''''''a'''''''', ''''''''b''''''''}''''::text, '
WHEN paramType = 'doublelist' THEN
'''''{''''''''1.3'''''''', ''''''''3.4''''''''}''''::text, '
WHEN paramType = 'intlist' THEN
'''''{''''''''3'''''''', ''''''''4''''''''}''''::text, '
ELSE --text
'''''randomtext'''', '
END;
END IF;
END LOOP;
-- remove the last comma.
query = left(query, char_length(query) - 2) || ');';
description = 'Test NULL ' || paramName || ' "' || query || '"';
query = 'SELECT TT_IsError(''' || query || ''') = ''ERROR in ' || function_tested || '(): ' || paramName || ' is NULL'';';
EXECUTE query INTO passed;
RETURN NEXT;
-- test wrong type (not necessary to test text as everything is valid text)
IF params[(i - 1) * 2 + 2] != 'text' THEN
subnbr = subnbr + 1;
number = baseTestNumber::text || '.' || subnbr::text;
query = 'SELECT ' || function_tested || '(''''val'''', ';
FOR j IN 1..array_upper(params, 1)/2 LOOP
paramType = params[(j - 1) * 2 + 2];
IF j = i THEN
-- test an invalid value
query = query || CASE WHEN paramType = 'int' OR paramType = 'numeric' THEN
'''''1a'''', '
WHEN paramType = 'char' THEN
'''''aa''''::text, '
WHEN paramType = 'stringlist' OR paramType = 'doublelist' OR paramType = 'intlist' OR paramType = 'charlist'THEN
'''''{''''''''string1'''''''',}'''', '
ELSE -- boolean
'2::text, '
END;
ELSE
-- set other to valid value
query = query || CASE WHEN paramType = 'int' OR paramType = 'numeric' THEN
'1::text, '
WHEN paramType = 'char' THEN
'0::text, '
WHEN paramType = 'boolean' THEN
'TRUE::text, '
WHEN paramType = 'stringlist' OR paramType = 'charlist' THEN
'''''{''''''''a'''''''', ''''''''b''''''''}''''::text, '
WHEN paramType = 'doublelist' OR paramType = 'intlist' THEN
'''''{''''''''1'''''''', ''''''''2''''''''}''''::text, '
ELSE
'''''randomtext'''', '
END;
END IF;
END LOOP;
-- remove the last comma.
query = left(query, char_length(query) - 2) || ');';
description = 'Test wrong type for ' || paramName || ' "' || query || '"';
paramType = params[(i - 1) * 2 + 2];
query = 'SELECT TT_IsError(''' || query || ''') = ''ERROR in ' || function_tested || '(): ' || paramName || ' is not a ' || paramType || ' value'';';
EXECUTE query INTO passed;
RETURN NEXT;
END IF;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql STABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Internal functions used in helper functions
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_min_internal(int[])
-- TT_max_internal(int[])
--
-- vals int[] - array of integer values.
-- min and max calculation for internal use. Not a helper function.
------------------------------------------------------------
-- DROP FUNCTION IF EXISTS TT_min_internal(double precision[]);
CREATE OR REPLACE FUNCTION TT_min_internal(
vals double precision[]
)
RETURNS double precision AS $$
BEGIN
RETURN min(a) FROM unnest(vals) a;
END;
$$ LANGUAGE plpgsql;
-- DROP FUNCTION IF EXISTS TT_max_internal(double precision[]);
CREATE OR REPLACE FUNCTION TT_max_internal(
vals double precision[]
)
RETURNS double precision AS $$
BEGIN
RETURN max(a) FROM unnest(vals) a;
END;
$$ LANGUAGE plpgsql;
-------------------------------------------------------------------------------
-- TT_min_max_indexes(int[], text, text)
--
-- vals int[] - array of integer values.
-- min_max text - return index of 'min' or 'max' value?
--
-- internal function returning an array of all indexes of the min or max value.
------------------------------------------------------------
-- DROP FUNCTION IF EXISTS TT_min_max_indexes_internal(int[], text);
CREATE OR REPLACE FUNCTION TT_min_max_indexes_internal(
vals double precision[],
min_max text
)
RETURNS integer[] AS $$
DECLARE
test_val double precision;
BEGIN
IF min_max = 'min' THEN
test_val = tt_min_internal(vals);
END IF;
IF min_max = 'max' THEN
test_val = tt_max_internal(vals);
END IF;
RETURN array_positions(vals, test_val);
END;
$$ LANGUAGE plpgsql;
-------------------------------------------------------------------------------
-- TT_minIndex_getTestVal(text, text)
--
-- intList stringList - list of integers to test with min()
-- testList stringList - list of target values to pass to other functions
-- setNullTo text - defaults to null - optionally convert any nulls in intList to this value
--
-- Find the target values from the testList with a matching
-- index to the smallest integer in the intList.
--
-- If there are multiple occurences of the smallest value, the
-- first non null value with a matching index is used. This is to
-- match the behaviour of TT_MinIndexMapText().
--
-- If setNullTo is provided as an integer, nulls
-- are replaced with the integer in intList. Otherwise nulls ignored
-- when calculating min value.
--
-- This function avoids repeating code many times
------------------------------------------------------------
-- DROP FUNCTION IF EXISTS TT_minIndex_getTestVal(text, text, text);
CREATE OR REPLACE FUNCTION TT_minIndex_getTestVal(
intList text,
testList text,
setNullTo text,
setZeroTo text
)
RETURNS text AS $$
DECLARE
_intList double precision[];
_testList text[];
_indexes int[];
_returnVals text[];
_setNullTo double precision;
_setZeroTo double precision;
i int;
BEGIN
-- parse lists to arrays
_intList = TT_ParseStringList(intList, TRUE);
_testList = TT_ParseStringList(testList, TRUE);
-- if setNullTo is provided, replace any nulls with it
IF upper(setNullTo) != 'NULL' THEN
_setNullTo = setNullTo::double precision;
_intList = array_replace(_intList, null::double precision, _setNullTo);
END IF;
-- if setZeroTo is provided, replace any zeros with it
IF upper(setZeroTo) != 'NULL' THEN
_setZeroTo = setZeroTo::double precision;
_intList = array_replace(_intList, 0::double precision, _setZeroTo);
END IF;
-- get indexes of all min values
_indexes = tt_min_max_indexes_internal(_intList, 'min');
-- get values from returnList matching the _indexes
-- for each index, add the returnList value with that index to _returnVals
FOREACH i IN ARRAY _indexes
LOOP
_returnVals = array_append(_returnVals, _testList[i]);
END LOOP;
-- remove any null values from _returnVals
-- _testVal is now the first element in the list.
-- i.e. the first non-null value matching the index of the min value.
_returnVals = array_remove(_returnVals, NULL);
RETURN _returnVals[1];
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-------------------------------------------------------------------------------
-- TT_maxIndex_getTestVal(text, text)
--
-- Same as above but returning the value matching the max index
------------------------------------------------------------
-- DROP FUNCTION IF EXISTS TT_maxIndex_getTestVal(text, text, text);
CREATE OR REPLACE FUNCTION TT_maxIndex_getTestVal(
intList text,
testList text,
setNullTo text,
setZeroTo text
)
RETURNS text AS $$
DECLARE
_intList double precision[];
_testList text[];
_indexes int[];
_returnVals text[];
_setNullTo double precision;
_setZeroTo double precision;
i int;
BEGIN
-- parse lists to arrays
_intList = TT_ParseStringList(intList, TRUE);
_testList = TT_ParseStringList(testList, TRUE);
-- if setNullTo is provided, replace any nulls with it
IF upper(setNullTo) != 'NULL' THEN
_setNullTo = setNullTo::double precision;
_intList = array_replace(_intList, null::double precision, _setNullTo);
END IF;
-- if setZeroTo is provided, replace any zeros with it
IF upper(setZeroTo) != 'NULL' THEN
_setZeroTo = setZeroTo::double precision;
_intList = array_replace(_intList, 0::double precision, _setZeroTo);
END IF;
-- get indexes of all max values
_indexes = tt_min_max_indexes_internal(_intList, 'max');
-- get values from returnList matching the _indexes
-- for each index, add the returnList value with that index to _returnVals
FOREACH i IN ARRAY _indexes
LOOP
_returnVals = array_append(_returnVals, _testList[i]);
END LOOP;
-- remove any null values from _returnVals
-- _srcVal is now the last element in the list.
-- i.e. the last non-null value matching the index of the max value.
_returnVals = array_remove(_returnVals, NULL);
RETURN _returnVals[array_length(_returnVals, 1)];
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-------------------------------------------------------------------------------
-- TT_getIndexTestVal(text, text, text, text)
--
-- intList stringList - list of integers to order
-- testList stringList - list of target values to pass to other functions
-- setNullTo text - defaults to null - optionally convert any nulls in intList to this value
-- setZeroTo text - defaults to null - optionally convert any zeros in intList to this value
--
-- Order testList by intList and return requested index.
--
-- Matching values should stay in the same order
--
-- If setNullTo is provided as an integer, nulls
-- are replaced with the integer in intList.
------------------------------------------------------------
-- DROP FUNCTION IF EXISTS TT_GetIndexTestVal(text, text, text, text, text, text);
CREATE OR REPLACE FUNCTION TT_GetIndexTestVal(
intList text,
testList text,
setNullTo text,
setZeroTo text,
orderIncreasing text,
indexToReturn text
)
RETURNS text AS $$
DECLARE
_intList double precision[];
_testList text[];
_setNullTo double precision;
_setZeroTo double precision;
_order text;
BEGIN
-- parse lists to arrays
_intList = TT_ParseStringList(intList, TRUE);
_testList = TT_ParseStringList(testList, TRUE);
-- if setNullTo is provided, replace any nulls with it
IF upper(setNullTo) != 'NULL' THEN
_setNullTo = setNullTo::double precision;
_intList = array_replace(_intList, null::double precision, _setNullTo);
END IF;
-- if setZeroTo is provided, replace any zeros with it
IF upper(setZeroTo) != 'NULL' THEN
_setZeroTo = setZeroTo::double precision;
_intList = array_replace(_intList, 0::double precision, _setZeroTo);
END IF;
-- run with specified order
IF orderIncreasing::boolean IS FALSE THEN
RETURN (ARRAY( -- converts table to array
SELECT testVal FROM(
SELECT a testVal, b intVal, a IS NULL::int not_null_order, ROW_NUMBER() OVER () org_order -- concatenates values in column a and b, add index
FROM unnest(
_testList,
_intList
) AS t(a,b) -- converts arrays to a table
ORDER BY intVal DESC, not_null_order, org_order ASC -- order by the values, ties are ordered by not null values first, then ordered by their original order in the string
) x
))[indexToReturn::int];
ELSE
RETURN (ARRAY( -- converts table to array
SELECT testVal FROM(
SELECT a testVal, b intVal, a IS NULL::int not_null_order, ROW_NUMBER() OVER () org_order -- concatenates values in column a and b, add index
FROM unnest(
_testList,
_intList
) AS t(a,b) -- converts arrays to a table
ORDER BY intVal ASC, not_null_order, org_order ASC -- order by the values, ties are ordered by not null values first, then ordered by their original order in the string
) x
))[indexToReturn::int];
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_GetIndexTestVal(text, text, text, text);
CREATE OR REPLACE FUNCTION TT_GetIndexTestVal(
intList text,
testList text,
setNullTo text,
setZeroTo text,
indexToReturn text
)
RETURNS text AS $$
SELECT TT_GetIndexTestVal(intList, testList, setNullTo, setZeroTo, 'TRUE', indexToReturn);
$$ LANGUAGE sql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_GetIndexTestVal(text, text, text, text);
CREATE OR REPLACE FUNCTION TT_GetIndexTestVal(
intList text,
testList text,
orderIncreasing text,
indexToReturn text
)
RETURNS text AS $$
SELECT TT_GetIndexTestVal(intList, testList, NULL::text, NULL::text, orderIncreasing, indexToReturn);
$$ LANGUAGE sql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_GetIndexTestVal(text, text, text);
CREATE OR REPLACE FUNCTION TT_GetIndexTestVal(
intList text,
testList text,
indexToReturn text
)
RETURNS text AS $$
SELECT TT_GetIndexTestVal(intList, testList, NULL::text, NULL::text, 'TRUE', indexToReturn);
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Begin Validation Function Definitions...
-- Validation functions return only boolean values (TRUE or FALSE).
-- Consist of a source value to be validated, and any parameters associated
-- with validation.
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Validation function template
--
-- Validation functions:
--
-- - must begin with "TT_"
-- - can only accept text parameters
-- - always return a boolean
-- - raise an exception on invalid parameters (with the help of the TT_ValidateParams() function)
-- - never fail on invalid values
-- - must properly handle NULL and empty values
-- - must not define DEFAULT parameters (use separate function signatures instead)
-- - if referring to another table, should be STABLE
-------------------------------------------------------------------------------
-- TT_ValidationFctTemplate
--
-- valList text (stringList) - Values to test. Can be a single value or a stringList.
-- param1 text (integer) - First perameter description. Default to 1.
-- param2 text (boolean) - Second parameter description (e.g. When TRUE, ignore case). Default to TRUE.
--
-- Description. e.g. Return TRUE if all vals are not NULL.
-- Return FALSE if any val is NULL.
-- e.g. TT_ValidationFctTemplate('a', 5, FALSE)
-- e.g. TT_ValidationFctTemplate({'a', 'b', 'c'}, 6)
------------------------------------------------------------
-- CREATE OR REPLACE FUNCTION TT_ValidationFctTemplate(
-- valList text,
-- param1 text,
-- param2 text
-- )
-- RETURNS boolean AS $$
-- DECLARE
-- _param1 int;
-- _param2 boolean;
-- _val text;
-- BEGIN
-- -- Validate parameters (trigger EXCEPTION)
-- PERFORM TT_ValidateParams('TT_ValidationFctTemplate',
-- ARRAY['param1', param1, 'int',
-- 'param2', param2, 'boolean']);
--
-- -- cast all parameters not of type text
-- _param1 = param1::int;
-- _param2 = param2::boolean;
--
-- -- More specific parameter validation
-- IF _param1 < 0 OR _param1 > 10 THEN
-- RAISE EXCEPTION 'ERROR in TT_ValidationFctTemplate(): param1 should be greater than 0 and smaller than 10';
-- END IF;
--
-- -- Validate values (val are not NULL and is a string list)
-- IF valList IS NULL OR NOT TT_IsStringList(valList) THEN
-- RETURN FALSE;
-- END IF;
--
-- -- Process value validity taking param1 and param2 into account
-- FOREACH _val IN ARRAY TT_ParseStringList(valList, TRUE) LOOP
-- IF whatever condition determining values invalidity THEN
-- RETURN FALSE;
-- END IF;
-- END LOOP;
-- RETURN TRUE;
-- END
-- $$ LANGUAGE plpgsql IMMUTABLE; -- IMMUTABLE because the function always returns the same value given the same input
--
-- -- Variant with default last parameter values
-- CREATE OR REPLACE FUNCTION TT_ValidationFctTemplate(
-- valList text,
-- param1 text
-- )
-- RETURNS boolean AS $$
-- SELECT TT_ValidationFctTemplate(valList, param1, FALSE::text);
-- $$ LANGUAGE sql IMMUTABLE;
--
-- -- Variant with all default parameter values
-- CREATE OR REPLACE FUNCTION TT_ValidationFctTemplate(
-- valList text
-- )
-- RETURNS boolean AS $$
-- SELECT TT_ValidationFctTemplate(valList, 1::text, FALSE::text);
-- $$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_NotNULL
--
-- val text (string list) - Value(s) to test. Can be one or many.
-- any_ text - default FALSE - if TRUE, return true if any inputs are not null.
--
-- Return TRUE if all vals are not NULL.
-- Return FALSE if any val is NULL.
-- e.g. TT_NotNULL('a')
-- e.g. TT_NotNull({'a', 'b', 'c'})
------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_NotNULL(
val text,
any_ text
)
RETURNS boolean AS $$
DECLARE
_val text[];
_null_count int;
_any boolean := any_::boolean;
BEGIN
-- validate source value (return FALSE)
IF NOT TT_IsStringList(val) THEN
RETURN FALSE;
END IF;
_val = TT_ParseStringList(val, TRUE);
_null_count = array_length(array_positions(_val, NULL), 1); -- counts number of NULLs, if no nulls, returns NULL.
-- if all values are not null, always return true
IF _null_count IS NULL THEN
RETURN TRUE;
END IF;
-- if any is TRUE, return TRUE if null_count is less than length of string list. i.e. at least one val is not null
IF _any THEN
RETURN _null_count < array_length(_val, 1);
END IF;
RETURN FALSE;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION TT_NotNull(
val text
)
RETURNS boolean AS $$
SELECT TT_NotNull(val, FALSE::text);
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_NotEmpty
--
-- val (stringList) text - value to test
-- any text - default FALSE - if TRUE, return true if any inputs are not null.
--
-- Return TRUE if val is not an empty string.
-- Return FALSE if val is empty string or padded spaces (e.g. '' or ' ') or NULL.
-- e.g. TT_NotEmpty('a')
------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_NotEmpty(
val text,
any_ text
)
RETURNS boolean AS $$
DECLARE
_vals text[];
_not_empty_count int := 0;
_any boolean := any_::boolean;
BEGIN
-- validate source value (return FALSE)
IF NOT TT_IsStringList(val) THEN
RETURN FALSE;
END IF;
IF val IS NULL THEN
RETURN FALSE;
END IF;
_vals = TT_ParseStringList(val, TRUE);
-- get count of not empty strings in array
FOR i IN 1..array_length(_vals, 1) LOOP
IF _vals[i] IS NOT NULL THEN
IF replace(_vals[i], ' ', '') != '' THEN
_not_empty_count = _not_empty_count + 1; -- only add count if val is not null or empty string
END IF;
END IF;
END LOOP;
-- return TRUE if any is TRUE and _not_empty_count >0
-- return TRUE if any is FALSE and _not_empty_count = length of _vals array
IF _any THEN
RETURN _not_empty_count > 0; -- any
ELSE
RETURN _not_empty_count = array_length(_vals, 1); -- all
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION TT_NotEmpty(
val text
)
RETURNS boolean AS $$
SELECT TT_NotEmpty(val, FALSE::text);
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_Length
--
-- val text - values to test.
-- removeSpaces boolean - trim spaces from start and end before calculating length?
--
-- Count characters in string
-- e.g. TT_Length('12345')
------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_Length(
val text,
removeSpaces text
)
RETURNS int AS $$
DECLARE
_removeSpaces boolean;
BEGIN
_removeSpaces = removeSpaces::boolean;
IF _removeSpaces THEN
RETURN coalesce(char_length(replace(val, ' ','')), 0);
ELSE
RETURN coalesce(char_length(val), 0);
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION TT_Length(
val text
)
RETURNS int AS $$
SELECT TT_Length(val, FALSE::text);
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_HasLength
--
-- val text - value to test.
-- length - Length to test against
-- acceptNull text - should NULL value return TRUE? Default FALSE.
-- removeSpace text - remove spaces. Default FALSE
--
-- Count characters in string and compare to length_test
-- e.g. TT_HasLength('12345', 5)
------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_HasLength(
val text,
length_test text,
acceptNull text,
removeSpaces text
)
RETURNS boolean AS $$
DECLARE
_val text;
_length_test int;
_acceptNull boolean;
_removeSpaces boolean;
BEGIN
-- validate parameters (trigger EXCEPTION)
PERFORM TT_ValidateParams('TT_HasLength',
ARRAY['acceptNull', acceptNull, 'boolean',
'length_test', length_test, 'int',
'removeSpaces', removeSpaces, 'boolean']);
_acceptNull = acceptNull::boolean;
_length_test = length_test::int;
_removeSpaces = removeSpaces::boolean;
-- get val
IF removeSpaces THEN
_val = replace(val, ' ', '');
ELSE
_val = val;
END IF;
IF TT_Length(_val) = _length_test THEN
RETURN TRUE;
ELSE
RETURN FALSE;
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION TT_HasLength(
val text,
length_test text
)
RETURNS boolean AS $$
SELECT TT_HasLength(val, length_test, FALSE::text, FALSE::text);
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_IsInt
--
-- val text - value to test.
-- acceptNull text - should NULL value return TRUE? Default FALSE.
--
-- Does value represent integer? (e.g. 1 or 1.0)
-- NULL values return FALSE unless acceptNull = TRUE
-- Strings with numeric characters and '.' will be evaluated
-- Strings with anything else (e.g. letter characters) return FALSE.
-- e.g. TT_IsInt('1.0')
------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_IsInt(
val text,
acceptNull text
)
RETURNS boolean AS $$
DECLARE
_val double precision;
_acceptNull boolean;
BEGIN
-- validate parameters (trigger EXCEPTION)
PERFORM TT_ValidateParams('TT_IsInt',
ARRAY['acceptNull', acceptNull, 'boolean']);
_acceptNull = acceptNull::boolean;
IF val IS NULL THEN
IF _acceptNull THEN
RETURN TRUE;
END IF;
RETURN FALSE;
ELSE
BEGIN
_val = val::double precision;
RETURN _val - _val::int = 0;
EXCEPTION WHEN OTHERS THEN
RETURN FALSE;
END;
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION TT_IsInt(
val text
)
RETURNS boolean AS $$
SELECT TT_IsInt(val, FALSE::text);
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_IsNumeric
--
-- val text - Value to test.
-- acceptNull text - should NULL value return TRUE? Default FALSE.
--
-- Can value be cast to double precision? (e.g. 1.1, 1, '1.5')
-- NULL values return FALSE unless acceptNull = TRUE
-- e.g. TT_IsNumeric('1.1')
------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_IsNumeric(
val text,
acceptNull text
)
RETURNS boolean AS $$
DECLARE
_val double precision;
_acceptNull boolean;
BEGIN
-- validate parameters (trigger EXCEPTION)
PERFORM TT_ValidateParams('TT_IsNumeric',
ARRAY['acceptNull', acceptNull, 'boolean']);
_acceptNull = acceptNull::boolean;
IF val IS NULL THEN
IF _acceptNull THEN
RETURN TRUE;
END IF;
RETURN FALSE;
ELSE
BEGIN
_val = val::double precision;
RETURN TRUE;
EXCEPTION WHEN OTHERS THEN
RETURN FALSE;
END;
END IF;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
CREATE OR REPLACE FUNCTION TT_IsNumeric(