-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathengine.sql
More file actions
3053 lines (2886 loc) · 138 KB
/
Copy pathengine.sql
File metadata and controls
3053 lines (2886 loc) · 138 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 - Main 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>
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- Types Definitions...
-------------------------------------------------------------------------------
--DROP TYPE TT_RuleDef_old CASCADE;
CREATE TYPE TT_RuleDef_old AS (
fctName text,
args text[],
errorCode text,
stopOnInvalid boolean
);
--DROP TYPE TT_RuleDef CASCADE;
CREATE TYPE TT_RuleDef AS (
fctName text,
args text,
errorCode text,
stopOnInvalid boolean
);
-- Debug configuration variable. Set tt.debug to TRUE to display all RAISE NOTICE
SET tt.debug TO FALSE;
-------------------------------------------------------------------------------
-- Function Definitions...
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_IsError(text)
-- Function to test if helper functions return errors
-------------------------------------------------------------------------------
CREATE OR REPLACE FUNCTION TT_IsError(
functionString text
)
RETURNS text AS $$
DECLARE
result boolean;
BEGIN
EXECUTE functionString INTO result;
RETURN 'FALSE';
EXCEPTION WHEN OTHERS THEN
RETURN SQLERRM;
END;
$$ LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------------------------
-- TT_NameRegex
-------------------------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_NameRegex();
CREATE OR REPLACE FUNCTION TT_NameRegex()
RETURNS text AS $$
SELECT '(?:[[:alpha:]_][[:alnum:]_]*|"[^" ]*")'
--SELECT '(?:\A(?:[[:alpha:]_][[:alnum:]_]*|(?:"[^" ]*")+)\M)'
$$ LANGUAGE sql STRICT;
/*
SELECT TT_IsName('"12_toto"') -- TRUE
SELECT TT_IsName('"12 toto"')-- FALSE
SELECT TT_IsName('12_toto') -- FALSE
SELECT TT_IsName('a12_toto') -- TRUE
SELECT TT_IsName('aa') -- TRUE
SELECT 'true' ~ TT_NameRegex() -- TRUE
SELECT '"1true"' ~ TT_NameRegex() -- TRUE
SELECT ' "1true"' ~ TT_NameRegex() -- FALSE
SELECT ' true' ~ TT_NameRegex() -- FALSE
SELECT 'true ' ~ TT_NameRegex() -- TRUE
SELECT 'true' ~ '(?:[[:alpha:]_][[:alnum:]_]*|(?:"[^" ]*")+)' -- TRUE
SELECT regexp_matches(' true false', '(' || TT_NameRegex() || ')', 'g')
*/
-------------------------------------------------------------------------------
-- TT_AllSpecialCharsRegex
-------------------------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_AllSpecialCharsRegex();
CREATE OR REPLACE FUNCTION TT_AllSpecialCharsRegex()
RETURNS text AS $$
SELECT '\s\|\(\)\[\]\{\}\^\$\.\*\?\+\\'
$$ LANGUAGE sql STRICT;
--SELECT TT_AllSpecialCharsRegex();
-------------------------------------------------------------------------------
-- TT_AnythingBetweenSingleQuotesRegex
-------------------------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_AnythingBetweenSingleQuotesRegex();
CREATE OR REPLACE FUNCTION TT_AnythingBetweenSingleQuotesRegex()
RETURNS text AS $$
SELECT '''(?:[^'']|'''')*'''
$$ LANGUAGE sql STRICT;
/*
SELECT 'aa' ~ ('^' || TT_AnythingBetweenSingleQuotesRegex() || '$');
SELECT '''aa''' ~ ('^' || TT_AnythingBetweenSingleQuotesRegex() || '$');
SELECT '''aa''''bb''' ~ ('^' || TT_AnythingBetweenSingleQuotesRegex() || '$');
SELECT '''aa'',''bb''' ~ ('^' || TT_AnythingBetweenSingleQuotesRegex() || '$');
*/
-------------------------------------------------------------------------------
-- TT_NumberRegex
-------------------------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_NumberRegex();
CREATE OR REPLACE FUNCTION TT_NumberRegex()
RETURNS text AS $$
SELECT '(?<![^[:space:],\{\[\(])-?\d+\.?\d*(?![^[:space:],\}\]\):])'
$$ LANGUAGE sql STRICT;
/*
WITH tests AS (
SELECT '''037365'' ~ (''^'' || TT_NumberRegex() || ''$'')' test, true expect
UNION ALL
SELECT '''037365'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''p1'' ~ TT_NumberRegex()' test, false
UNION ALL
SELECT '''10::'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''p1,34'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''p1,34'' ~ (''^'' || TT_NumberRegex() || ''$'')' test, false
UNION ALL
SELECT '''p1-34'' ~ TT_NumberRegex()' test, false
UNION ALL
SELECT '''p1(-34)'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''p1([-34])'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''p1({-34})'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''-37465.4567'' ~ (''^'' || TT_NumberRegex() || ''$'')' test, true
UNION ALL
SELECT '''-37465.4567'' ~ TT_NumberRegex()' test, true
UNION ALL
SELECT '''- 37465.4567'' ~ (''^'' || TT_NumberRegex() || ''$'')' test, false
UNION ALL
SELECT '''11b'' ~ (''^'' || TT_NumberRegex() || ''$'')' test, false
UNION ALL
SELECT '''11b'' ~ TT_NumberRegex()' test, false
)
SELECT test, eval(test) = expect::text passed
FROM tests
*/
-------------------------------------------------------------------------------
-- TT_OneLevelFctCallRegex
-------------------------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_OneLevelFctCallRegex();
CREATE OR REPLACE FUNCTION TT_OneLevelFctCallRegex()
RETURNS text AS $$
--SELECT TT_NameRegex() || '\((?:' || TT_NumberRegex() || '\s*,?\s*|' || TT_NameRegex() || '\s*,?\s*|' || TT_AnythingBetweenSingleQuotesRegex() || '\s*,?\s*)*\)'
--SELECT TT_NameRegex() || '\((?:' || TT_NumberRegex() || '|' || TT_NameRegex() || '|' || TT_AnythingBetweenSingleQuotesRegex() || ')?(?:\s*,\s*(?:' || TT_NumberRegex() || '|' || TT_NameRegex() || '|' || TT_AnythingBetweenSingleQuotesRegex() || '))*\)'
SELECT TT_NameRegex() || '\(\{?(?:' || TT_NumberRegex() || '|' || TT_NameRegex() || '|' || TT_AnythingBetweenSingleQuotesRegex() || ')?\}?(?:\s*,\s*\{?(?:' || TT_NumberRegex() || '|' || TT_NameRegex() || '|' || TT_AnythingBetweenSingleQuotesRegex() || ')+\}?)*\)'
$$ LANGUAGE sql STRICT;
/*
SELECT unnest(regexp_matches('aa()', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g'));
SELECT unnest(regexp_matches('aa(bbb)', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- true
SELECT unnest(regexp_matches('aa(11)', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- true
SELECT unnest(regexp_matches('aa(11b)', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- false
SELECT unnest(regexp_matches('aa(''bbb'')', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- true
SELECT unnest(regexp_matches('aa(''bb'', cc)', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- true
SELECT unnest(regexp_matches('aa(bb(''cc'', dd))', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- false
SELECT unnest(regexp_matches('aa({''bbb''})', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- true
SELECT unnest(regexp_matches('aa({''bbb''}, {11, 44})', ('^' || TT_OneLevelFctCallRegex() || '$'), 'g')); -- true
SELECT unnest(regexp_matches('matchTable(minIndexCopyText({mod_1_year, mod_2_year},{mod_1,mod_2}),''translation'',''qc_disturbance_lookup'',''source_val'')', TT_OneLevelFctCallRegex(), 'g')); -- true
SELECT unnest(regexp_matches('minIndexCopyText({mod_1_year, mod_2_year},{mod_1,mod_2})', TT_OneLevelFctCallRegex(), 'g')); -- true
SELECT unnest(regexp_matches('minIndexCopyText({mod_1,mod_2}, {mod_1,mod_2})', TT_OneLevelFctCallRegex(), 'g')); -- true
SELECT unnest(regexp_matches('minIndexCopyText(aa, {mod_1,mod_2}, bb)', TT_OneLevelFctCallRegex(), 'g')); -- true
SELECT unnest(regexp_matches('minIndexCopyText({mod_1,mod_2}, {mod_1,mod_2}, ''9999'', ''9999'')', TT_OneLevelFctCallRegex(), 'g')); -- true
*/
-------------------------------------------------------------------------------
-- TT_FctExist
-- Function to test if a function exists.
------------------------------------------------------------
-- Self contained example:
--
-- SELECT TT_FctExists('TT_FctEval', {'text', 'text[]', 'jsonb', 'anyelement'})
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_FctExists(text, text, text[]);
CREATE OR REPLACE FUNCTION TT_FctExists(
schemaName name,
fctName name,
argTypes text[] DEFAULT NULL
)
RETURNS boolean AS $$
DECLARE
cnt int = 0;
debug boolean = TT_Debug();
BEGIN
IF debug THEN RAISE NOTICE 'TT_FctExists BEGIN';END IF;
fctName = 'tt_' || fctName;
IF lower(schemaName) = 'public' OR schemaName IS NULL THEN
schemaName = '';
END IF;
IF schemaName != '' THEN
fctName = schemaName || '.' || fctName;
END IF;
IF fctName IS NULL THEN
RETURN NULL;
END IF;
IF fctName = '' OR fctName = '.' THEN
RETURN FALSE;
END IF;
fctName = lower(fctName);
IF debug THEN RAISE NOTICE 'TT_FctExists 11 fctName=%, args=%', fctName, array_to_string(TT_LowerArr(argTypes), ',');END IF;
SELECT count(*)
FROM pg_proc
WHERE schemaName = '' AND argTypes IS NULL AND proname = fctName OR
oid::regprocedure::text = fctName || '(' || array_to_string(TT_LowerArr(argTypes), ',') || ')'
INTO cnt;
IF cnt > 0 THEN
IF debug THEN RAISE NOTICE 'TT_FctExists END TRUE';END IF;
RETURN TRUE;
END IF;
IF debug THEN RAISE NOTICE 'TT_FctExists END FALSE';END IF;
RETURN FALSE;
END;
$$ LANGUAGE plpgsql STABLE;
---------------------------------------------------
CREATE OR REPLACE FUNCTION TT_FctExists(
fctName name,
argTypes text[] DEFAULT NULL
)
RETURNS boolean AS $$
SELECT TT_FctExists(''::name, fctName, argTypes)
$$ LANGUAGE sql STABLE;
---------------------------------------------------
-- TT_Debug
--
-- RETURNS boolean - True if tt_debug is set to true. False if set to false or not set.
--
-- Wrapper to catch error when tt.error is not set.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_Debug(int);
CREATE OR REPLACE FUNCTION TT_Debug(
level int DEFAULT NULL
)
RETURNS boolean AS $$
DECLARE
BEGIN
RETURN current_setting('tt.debug' || CASE WHEN level IS NULL THEN '' ELSE '_l' || level::text END)::boolean;
EXCEPTION WHEN OTHERS THEN -- if tt.debug is not set
RETURN FALSE;
END;
$$ LANGUAGE plpgsql STABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_DefaultProjectErrorCode
--
-- rule text - Name of the rule.
-- type text - Required type.
--
-- RETURNS text - Default error code for this rule.
--
-- Default project error code function to be overwritten by specific projects
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_DefaultProjectErrorCode(text, text);
CREATE OR REPLACE FUNCTION TT_DefaultProjectErrorCode(
rule text,
targetType text
)
RETURNS text AS $$
DECLARE
rulelc text = lower(rule);
targetTypelc text = lower(targetType);
BEGIN
IF targetTypelc = 'integer' OR targetTypelc = 'int' OR targetTypelc = 'double precision' THEN
RETURN CASE WHEN rulelc = 'projectrule1' THEN '-9999'
ELSE TT_DefaultErrorCode(rulelc, targetTypelc) END;
ELSIF targetTypelc = 'geometry' THEN
RETURN CASE WHEN rulelc = 'projectrule1' THEN NULL
ELSE TT_DefaultErrorCode(rulelc, targetTypelc) END;
ELSE
RETURN CASE WHEN rulelc = 'projectrule1' THEN 'ERROR_CODE'
ELSE TT_DefaultErrorCode(rulelc, targetTypelc) END;
END IF;
END;
$$ LANGUAGE plpgsql;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_FullTableName
--
-- schemaName name - Name of the schema.
-- tableName name - Name of the table.
--
-- RETURNS text - Full name of the table.
--
-- Return a well quoted, full table name, including the schema.
-- The schema default to 'public' if not provided.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_FullTableName(name, name);
CREATE OR REPLACE FUNCTION TT_FullTableName(
schemaName name,
tableName name
)
RETURNS text AS $$
DECLARE
newSchemaName text = '';
BEGIN
IF length(schemaName) > 0 THEN
newSchemaName = schemaName;
ELSE
newSchemaName = 'public';
END IF;
RETURN quote_ident(newSchemaName) || '.' || quote_ident(tableName);
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_FullFunctionName
--
-- schemaName name - Name of the schema.
-- fctName name - Name of the function.
--
-- RETURNS text - Full name of the table.
--
-- Return a full function name, including the schema.
-- The schema default to 'public' if not provided.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_FullFunctionName(name, name);
CREATE OR REPLACE FUNCTION TT_FullFunctionName(
schemaName name,
fctName name
)
RETURNS text AS $$
DECLARE
BEGIN
IF fctName IS NULL THEN
RETURN NULL;
END IF;
fctName = 'tt_' || lower(fctName);
schemaName = lower(schemaName);
IF schemaName = 'public' OR schemaName IS NULL THEN
schemaName = '';
END IF;
IF schemaName != '' THEN
fctName = schemaName || '.' || fctName;
END IF;
RETURN fctName;
END;
$$ LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_TableExists
--
-- schemaName text
-- tableName text
--
-- Return boolean (success or failure)
--
-- Determine if a table exists.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_TableExists(text, text);
CREATE OR REPLACE FUNCTION TT_TableExists(
schemaName text,
tableName text
)
RETURNS boolean AS $$
SELECT NOT to_regclass(TT_FullTableName(schemaName, tableName)) IS NULL;
$$ LANGUAGE sql VOLATILE;
-------------------------------------------------------------------------------]
-------------------------------------------------------------------------------
-- TT_GetGeomColName
--
-- schemaName text
-- tableName text
--
-- Return text
--
-- Determine the name of the first geometry column if it exists (otherwise return NULL)
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_GetGeomColName(text, text);
CREATE OR REPLACE FUNCTION TT_GetGeomColName(
schemaName text,
tableName text
)
RETURNS text AS $$
SELECT column_name::text FROM information_schema.columns
WHERE table_schema = lower(schemaName) AND table_name = lower(tableName) AND udt_name= 'geometry'
LIMIT 1
$$ LANGUAGE sql VOLATILE;
--SELECT TT_GetGeomColName('rawfri', 'AB16r')
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_PrettyDuration
--
-- seconds int
--
-- Format passed number of seconds into a pretty print time interval
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_PrettyDuration(double precision, int, int) CASCADE;
CREATE OR REPLACE FUNCTION TT_PrettyDuration(
seconds double precision,
secDigits int DEFAULT NULL,
levels int DEFAULT NULL
)
RETURNS text AS $$
DECLARE
nbDays int;
nbHours int;
nbMinutes int;
formatedDuration text = '';
firstLevelSet boolean := FALSE;
BEGIN
IF seconds < 5 THEN
IF NOT secDigits IS NULL THEN
RETURN round(seconds::numeric, secDigits) || 's';
ELSE
RETURN seconds || 's';
END IF;
END IF;
IF NOT levels IS NULL THEN
levels := greatest(least(levels, 4), 1);
END IF;
nbDays = floor(seconds/(24*3600));
seconds = seconds - nbDays*24*3600;
nbHours = floor(seconds/3600);
seconds = seconds - nbHours*3600;
nbMinutes = floor(seconds::int/60);
seconds = seconds - nbMinutes*60;
--RAISE NOTICE 'nbDays=%', nbDays;
--RAISE NOTICE 'nbHours=%', nbHours;
--RAISE NOTICE 'nbMinutes=%', nbMinutes;
--RAISE NOTICE 'seconds=%', seconds;
-- Display time units only when they are different from 0 or when they are in between two units different than 0
-- and when there are some remaining significant levels to display (if specified)
IF nbDays > 0 THEN
formatedDuration = nbDays || 'd';
IF NOT levels IS NULL THEN
levels = levels - 1;
END IF;
firstLevelSet := TRUE;
END IF;
IF ((nbHours > 0 AND (levels IS NULL OR levels > 0)) OR
(nbDays > 0 AND (nbMinutes > 0 OR seconds > 0) AND (levels IS NULL OR levels > 1))) THEN
formatedDuration = formatedDuration || lpad(nbHours::text, CASE WHEN nbDays > 0 OR nbHours > 9 THEN 2 ELSE 1 END, '0') || 'h';
firstLevelSet := TRUE;
END IF;
IF NOT levels IS NULL AND firstLevelSet THEN
levels = levels - 1;
END IF;
IF ((nbMinutes > 0 AND (levels IS NULL OR levels > 0)) OR
((nbDays > 0 OR nbHours > 0) AND (seconds > 0) AND (levels IS NULL OR levels > 1))) THEN
formatedDuration = formatedDuration || lpad(nbMinutes::text, CASE WHEN nbDays > 0 OR nbHours > 0 OR nbMinutes > 9 THEN 2 ELSE 1 END, '0') || 'm';
firstLevelSet := TRUE;
END IF;
IF NOT levels IS NULL AND firstLevelSet THEN
levels = levels - 1;
END IF;
IF ((seconds > 0 AND (levels IS NULL OR levels > 0)) OR
(nbDays = 0 AND nbHours = 0 AND nbMinutes = 0) AND (levels IS NULL OR levels > 1)) THEN
formatedDuration = formatedDuration || lpad(seconds::int::text, CASE WHEN nbDays > 0 OR nbHours > 0 OR nbMinutes > 0 OR seconds > 9 THEN 2 ELSE 1 END, '0') || 's';
END IF;
/*
RETURN CASE WHEN nbDays > 0 THEN nbDays || 'd' ELSE '' END ||
CASE WHEN nbHours > 0 OR (nbDays > 0 AND (nbMinutes > 0 OR seconds > 0)) THEN lpad(nbHours::text, 2, '0') || 'h' ELSE '' END ||
CASE WHEN nbMinutes > 0 OR ((nbDays > 0 OR nbHours > 0) AND (seconds > 0)) THEN lpad(nbMinutes::text, 2, '0') || 'm' ELSE '' END ||
CASE WHEN seconds > 0 OR (nbDays = 0 AND nbHours = 0 AND nbMinutes = 0) THEN lpad(seconds::int::text, 2, '0') || 's' ELSE '' END;
*/
RETURN formatedDuration;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
/*
SELECT TT_PrettyDuration(0.654); -- '0.654s'
SELECT TT_PrettyDuration(0.6547437); -- '0.6547437s'
SELECT TT_PrettyDuration(0.6547437, 3); -- '0.655s'
SELECT TT_PrettyDuration(0); -- '0s'
SELECT TT_PrettyDuration(1); -- '1s'
SELECT TT_PrettyDuration(1, 3); -- '1.000s'
SELECT TT_PrettyDuration(1.4536); -- '1.4536s'
SELECT TT_PrettyDuration(3, 4); -- '3.0000s'
SELECT TT_PrettyDuration(60); -- '1m'
SELECT TT_PrettyDuration(61); -- '1m01s'
SELECT TT_PrettyDuration(61, 3); -- '1m01s'
SELECT TT_PrettyDuration(3600); -- '1h'
SELECT TT_PrettyDuration(3603); -- '1h00m03s'
SELECT TT_PrettyDuration(3661); -- '1h01m01s'
SELECT TT_PrettyDuration(24*3600); -- '1d'
SELECT TT_PrettyDuration(24*3602); -- '1d00h00m48s'
SELECT TT_PrettyDuration(111.297334221); -- '1m51s'
SELECT TT_PrettyDuration(59.9); -- '1m'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2); -- '1d02h02m02s'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2, NULL, 5); -- '1d02h02m02s'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2, NULL, 4); -- '1d02h02m02s'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2, NULL, 3); -- '1d02h02m'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2, NULL, 2); -- '1d02h'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2, NULL, 1); -- '1d'
SELECT TT_PrettyDuration(26*3600 + 2*60 + 2, NULL, 0); -- '1d'
SELECT TT_PrettyDuration(2*3600 + 2*60 + 2, NULL, 3); -- '2h02m02s'
SELECT TT_PrettyDuration(2*3600 + 2*60 + 2, NULL, 2); -- '2h02m'
SELECT TT_PrettyDuration(2*3600 + 2*60 + 2, NULL, 1); -- '2h'
SELECT TT_PrettyDuration(2*60 + 2, NULL, 2); -- '2m02s'
SELECT TT_PrettyDuration(2*60 + 2, NULL, 1); -- '2m'
SELECT TT_PrettyDuration(501, NULL, 2); -- '2m'
SELECT TT_PrettyDuration(601, NULL, 2); -- '2m'
*/
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_LogInit
--
-- schemaName text
-- translationTableName text
-- sourceTableName
-- increment boolean
-- dupLogEntriesHandling text
--
-- Return the suffix of the created log table. 'FALSE' if creation failed.
-- Create a new or overwrite former log table and initialize a new one.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_LogInit(text, text, text, boolean, text);
CREATE OR REPLACE FUNCTION TT_LogInit(
schemaName text,
translationTableName text,
sourceTableName text,
increment boolean DEFAULT TRUE,
dupLogEntriesHandling text DEFAULT '100'
)
RETURNS text AS $$
DECLARE
query text;
logInc int = 1;
logTableName text;
action text = 'Creating';
BEGIN
IF NOT (TT_NotEmpty(translationTableName) AND TT_NotEmpty(sourceTableName)) THEN
RAISE EXCEPTION 'TT_LogInit() ERROR: Invalid translation table name...';
END IF;
logTableName = translationTableName || '_4_' || sourceTableName || '_log_' || TT_Pad(logInc::text, 3::text, '0');
IF increment THEN
-- find an available table name
WHILE TT_TableExists(schemaName, logTableName) LOOP
logInc = logInc + 1;
logTableName = translationTableName || '_4_' || sourceTableName || '_log_' || TT_Pad(logInc::text, 3::text, '0');
END LOOP;
ELSIF TT_TableExists(schemaName, logTableName) THEN
action = 'Overwriting';
query = 'DROP TABLE IF EXISTS ' || TT_FullTableName(schemaName, logTableName) || ';';
BEGIN
EXECUTE query;
EXCEPTION WHEN OTHERS THEN
RETURN 'FALSE';
END;
END IF;
query = 'CREATE TABLE ' || TT_FullTableName(schemaName, logTableName) || ' (' ||
'logID SERIAL, logTime timestamp with time zone, logEntryType text,
firstRowId text, message text, currentRowNb int, count int);';
-- display the name of the logging table being produced
RAISE NOTICE 'TT_LogInit(): % log table ''%''...', action, TT_FullTableName(schemaName, logTableName);
-- display the type of handling for invalid values.
IF dupLogEntriesHandling = 'ALL_OWN_ROW' THEN
RAISE NOTICE 'TT_LogInit(): All invalid and translation error messages in their own rows...';
ELSE
IF dupLogEntriesHandling = 'ALL_GROUPED' THEN
RAISE NOTICE 'TT_LogInit(): All invalid and translation error messages of the same type grouped in the same row.';
ELSE
RAISE NOTICE 'TT_LogInit(): Maximum of % invalid or translation error messages of the same type grouped in the same row...', dupLogEntriesHandling;
END IF;
END IF;
BEGIN
EXECUTE query;
EXCEPTION WHEN OTHERS THEN
RETURN 'FALSE';
END;
-- create an md5 index on the message column
query = 'CREATE ' ||
CASE WHEN dupLogEntriesHandling != 'ALL_OWN_ROW' THEN 'UNIQUE ' ELSE '' END ||
'INDEX ON ' || TT_FullTableName(schemaName, logTableName) ||
' (md5(message));';
EXECUTE query;
RETURN logTableName;
END;
$$ LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_ShowLastLog
--
-- schemaName text
-- translationTableName text
--
-- Return the last log table for the provided translation table.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_ShowLastLog(text, text, text, int);
CREATE OR REPLACE FUNCTION TT_ShowLastLog(
schemaName text,
translationTableName text,
sourceTableName text,
logNb int DEFAULT NULL
)
RETURNS TABLE (logID int,
logTime timestamp with time zone,
logEntryType text,
firstRowId text,
message text,
currentRowNb int,
count int) AS $$
DECLARE
query text;
logInc int = 1;
logTableName text;
suffix text;
BEGIN
IF NOT logNb IS NULL THEN
logInc = logNb;
END IF;
suffix = '_log_' || TT_Pad(logInc::text, 3::text, '0');
logTableName = translationTableName || '_4_' || sourceTableName || suffix;
IF TT_FullTableName(schemaName, logTableName) = 'public.' || suffix THEN
RAISE NOTICE 'TT_ShowLastLog() ERROR: Invalid translation table name or number (%.%)...', schemaName, logTableName;
RETURN;
END IF;
IF logNb IS NULL THEN
-- find the last log table name
WHILE TT_TableExists(schemaName, logTableName) LOOP
logInc = logInc + 1;
logTableName = translationTableName || '_4_' || sourceTableName || '_log_' || TT_Pad(logInc::text, 3::text, '0');
END LOOP;
-- if logInc = 1 means no log table exists
IF logInc = 1 THEN
RAISE NOTICE 'TT_ShowLastLog() ERROR: No translation log to show for translation table ''%.%'' and source table %...', schemaName, translationTableName, sourceTableName;
RETURN;
END IF;
logInc = logInc - 1;
ELSE
IF NOT TT_TableExists(schemaName, logTableName) THEN
RAISE NOTICE 'TT_ShowLastLog() ERROR: Translation log table ''%.%'' does not exist...', schemaName, logTableName;
RETURN;
END IF;
END IF;
logTableName = translationTableName || '_4_' || sourceTableName || '_log_' || TT_Pad(logInc::text, 3::text, '0');
RAISE NOTICE 'TT_ShowLastLog(): Displaying log table ''%''', logTableName;
query = 'SELECT logID, logTime, logEntryType, firstRowId, message, currentRowNb, count FROM ' ||
TT_FullTableName(schemaName, logTableName) || ' ORDER BY logid;';
RETURN QUERY EXECUTE query;
END;
$$ LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_DeleteAllLogs
--
-- schemaName text
-- translationTableName text
--
-- Delete all log table associated with the target table.
-- If translationTableName is NULL, delete all log tables in schema.
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_DeleteAllLogs(text, text);
CREATE OR REPLACE FUNCTION TT_DeleteAllLogs(
schemaName text,
translationTableName text DEFAULT NULL
)
RETURNS SETOF text AS $$
DECLARE
res RECORD;
BEGIN
IF translationTableName IS NULL THEN
FOR res IN SELECT 'DROP TABLE IF EXISTS ' || TT_FullTableName(schemaName, table_name) || ';' query
FROM information_schema.tables
WHERE lower(table_schema) = schemaName AND right(table_name, 8) ~ '_log_[0-9][0-9][0-9]'
ORDER BY table_name LOOP
EXECUTE res.query;
RETURN NEXT res.query;
END LOOP;
ELSE
FOR res IN SELECT 'DROP TABLE IF EXISTS ' || TT_FullTableName(schemaName, table_name) || ';' query
FROM information_schema.tables
WHERE char_length(table_name) > char_length(translationTableName) AND left(table_name, char_length(translationTableName)) = translationTableName
ORDER BY table_name LOOP
EXECUTE res.query;
RETURN NEXT res.query;
END LOOP;
END IF;
RETURN;
END;
$$ LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_Log
--
-- schemaName text - Schema name of the logging table
-- logTableName text - Logging table name
-- logEntryType text - Type of logging entry (PROGRESS, INVALIDATION)
-- firstRowId text - rowID of the first source triggering the logging entry.
-- message text - Message to log
-- currentRowNb int - Number of the row being processed
-- count int - Number of rows associated with this log entry
--
-- Return boolean -- Success or failure.
-- Log an entry in the log table.
-- The log table has the following structure:
-- logid integer NOT NULL DEFAULT nextval('source_log_001_logid_seq'::regclass),
-- logtime timestamp,
-- logentrytype text,
-- firstrowid text,
-- message text,
-- currentrownb int,
-- count integer
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_Log(text, text, text, text, text, text, int, int);
CREATE OR REPLACE FUNCTION TT_Log(
schemaName text,
logTableName text,
dupLogEntriesHandling text,
logEntryType text,
firstRowId text,
msg text,
currentRowNb int,
count int DEFAULT NULL
)
RETURNS boolean AS $$
DECLARE
query text;
BEGIN
IF upper(logEntryType) = 'PROGRESS' THEN
query = 'INSERT INTO ' || TT_FullTableName(schemaName, logTableName) || ' VALUES (' ||
'DEFAULT, now(), ''PROGRESS'', $1, $2, $3, $4);';
EXECUTE query USING firstRowId, msg, currentRowNb, count;
RETURN TRUE;
ELSIF upper(logEntryType) = 'INVALID_VALUE' OR upper(logEntryType) = 'TRANSLATION_ERROR' THEN
query = 'INSERT INTO ' || TT_FullTableName(schemaName, logTableName) || ' AS tbl VALUES (' ||
'DEFAULT, now(), ''' || upper(logEntryType) || ''', $1, $2, $3, $4) ';
IF dupLogEntriesHandling != 'ALL_OWN_ROW' THEN
query = query || 'ON CONFLICT (md5(message)) DO UPDATE SET count = tbl.count + 1';
IF dupLogEntriesHandling != 'ALL_GROUPED' THEN
query = query || 'WHERE tbl.count < ' || dupLogEntriesHandling;
END IF;
END IF;
query = query || ';';
EXECUTE query USING firstRowId, msg, currentRowNb, 1;
RETURN TRUE;
ELSE
RAISE EXCEPTION 'TT_Log() ERROR: Invalid logEntryType (%)...', logEntryType;
RETURN FALSE;
END IF;
END;
$$ LANGUAGE plpgsql VOLATILE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_IsCastableTo
--
-- val text
-- targetType text
--
-- RETURNS boolean
--
-- Can value be cast to target type
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_IsCastableTo(text, text);
CREATE OR REPLACE FUNCTION TT_IsCastableTo(
val text,
targetType text
)
RETURNS boolean AS $$
DECLARE
query text;
BEGIN
-- NULL values are castable to everything
IF NOT val IS NULL THEN
query = 'SELECT ' || '''' || val || '''' || '::' || targetType || ';';
EXECUTE query;
END IF;
RETURN TRUE;
EXCEPTION WHEN OTHERS THEN
RETURN FALSE;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_IsSingleQuoted
-- DROP FUNCTION IF EXISTS TT_IsSingleQuoted(text);
CREATE OR REPLACE FUNCTION TT_IsSingleQuoted(
str text
)
RETURNS boolean AS $$
SELECT left(str, 1) = '''' AND right(str, 1) = '''';
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_UnSingleQuote
-- DROP FUNCTION IF EXISTS TT_UnSingleQuote(text);
CREATE OR REPLACE FUNCTION TT_UnSingleQuote(
str text
)
RETURNS text AS $$
SELECT CASE WHEN left(str, 1) = '''' AND right(str, 1) = '''' THEN btrim(str, '''') ELSE str END;
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_EscapeSingleQuotes
-- DROP FUNCTION IF EXISTS TT_EscapeSingleQuotes(text);
CREATE OR REPLACE FUNCTION TT_EscapeSingleQuotes(
str text
)
RETURNS text AS $$
SELECT replace(str, '''', '''''');
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_EscapeDoubleQuotes
-- DROP FUNCTION IF EXISTS TT_EscapeDoubleQuotesAndBackslash(text);
CREATE OR REPLACE FUNCTION TT_EscapeDoubleQuotesAndBackslash(
str text
)
RETURNS text AS $$
SELECT replace(replace(str, '\', '\\'), '"', '\"'); -- '''
$$ LANGUAGE sql IMMUTABLE;
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_IsSurroundedByChars
-- DROP FUNCTION IF EXISTS TT_IsSurroundedByChars(text, text[]);
CREATE OR REPLACE FUNCTION TT_IsSurroundedByChars(
str text,
chars text[]
)
RETURNS boolean AS $$
DECLARE
BEGIN
IF cardinality(chars) != 2 THEN
RAISE EXCEPTION 'TT_IsSurroundedByChars() ERROR: Number of chars must be 2 not %...', cardinality(chars);
END IF;
IF char_length(chars[1]) != 1 OR char_length(chars[2]) != 1 THEN
RAISE EXCEPTION 'TT_IsSurroundedByChars() ERROR: Both chars (%) and (%) must be one and only one character long...', chars[1], chars[2];
END IF;
RETURN left(str, 1) = chars[1] AND right(str, 1) = chars[2];
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_IsSurroundedByChars(text, text);
CREATE OR REPLACE FUNCTION TT_IsSurroundedByChars(
inStr text,
chars text
)
RETURNS boolean AS $$
SELECT TT_IsSurroundedByChars(inStr, ARRAY[chars, chars]);
$$ LANGUAGE sql IMMUTABLE;
/*
SELECT TT_IsSurroundedByChars('''aa', '''')
SELECT TT_IsSurroundedByChars('''aa''', '''')
SELECT TT_IsSurroundedByChars('aa)', ARRAY['(', ')'])
SELECT TT_IsSurroundedByChars('(aa)', ARRAY['(', ')'])
*/
-------------------------------------------------------------------------------
-- TT_ReplaceAroundChars()
---------------------------------------------------------------
-- DROP FUNCTION IF EXISTS TT_ReplaceAroundChars(text, text[], text[], text[], boolean);
CREATE OR REPLACE FUNCTION TT_ReplaceAroundChars(
inStr text,
chars text[],
searchStrings text[],
replacementStrings text[],
outside boolean DEFAULT FALSE
)
RETURNS text AS $$
DECLARE
i int;
newStr text;
returnStr text;
str text[];
strArr text[];
searchRegex text;
surrounded boolean;
escapedChars text[];
BEGIN
--RAISE NOTICE 'TT_ReplaceAroundChars() 11 inStr=%', inStr;
IF cardinality(chars) != 2 THEN
RAISE EXCEPTION 'TT_ReplaceAroundChars() ERROR: Number of chars must be 2 not %...', cardinality(chars);
END IF;
IF char_length(chars[1]) != 1 OR char_length(chars[2]) != 1 THEN
RAISE EXCEPTION 'TT_ReplaceAroundChars() ERROR: Both chars (%) and (%) must be one and only one character long...', chars[1], chars[2];
END IF;
IF searchStrings IS NULL OR searchStrings[1] IS NULL THEN
RETURN inStr;
END IF;
IF replacementStrings IS NULL OR replacementStrings[1] IS NULL THEN
RAISE EXCEPTION 'TT_ReplaceAroundChars() ERROR: replacementStrings is NULL...';
END IF;
IF cardinality(searchStrings) != cardinality(replacementStrings) THEN
RAISE EXCEPTION 'TT_ReplaceAroundChars() ERROR: Number of searchStrings (%) different from number of replacementStrings(%)...', cardinality(searchStrings), cardinality(replacementStrings);
END IF;
-- Escape both chars before being used as regex
escapedChars[1] = regexp_replace(chars[1], '([' || TT_AllSpecialCharsRegex() || '])', '\\\1');
escapedChars[2] = regexp_replace(chars[2], '([' || TT_AllSpecialCharsRegex() || '])', '\\\1');
-- Build the array of substring to replace into
searchRegex = '(?:' || escapedChars[1] || '[^' || escapedChars[1] || escapedChars[2] || ']*' || escapedChars[2] || '|[^' || escapedChars[1] || escapedChars[2] || ']*)';
returnStr = inStr;
FOR str IN SELECT regexp_matches(returnStr, searchRegex, 'g') LOOP
--RAISE NOTICE 'TT_ReplaceAroundChars() 22 str=%', str;
newStr = str[1];
surrounded = TT_IsSurroundedByChars(newStr, chars);
IF (outside AND NOT surrounded) OR (NOT outside AND surrounded) THEN
-- Replace all provided search string with the corresponding replacement string
FOR i IN 1..cardinality(searchStrings) LOOP
--RAISE NOTICE 'TT_ReplaceAroundChars() 33 searchStrings[%]=%', i, searchStrings[i];
IF searchStrings[i] IS NULL THEN
RAISE EXCEPTION 'TT_ReplaceAroundChars() ERROR: searchStrings # % is NULL...', i;
END IF;
IF replacementStrings[i] IS NULL THEN
RAISE EXCEPTION 'TT_ReplaceAroundChars() ERROR: replacementStrings # % is NULL...', i;
END IF;
IF TT_IsSurroundedByChars(searchStrings[i], '\') THEN
newStr = regexp_replace(newStr, btrim(searchStrings[i], '\\'), replacementStrings[i], 'g');
ELSE
newStr = replace(newStr, searchStrings[i], replacementStrings[i]);
END IF;
--RAISE NOTICE 'TT_ReplaceAroundChars() 44 newStr=%', newStr;
END LOOP;
-- Replace the quoted string with the new string in the final string
returnStr = replace(returnStr, str[1], newStr);
--RAISE NOTICE 'TT_ReplaceAroundChars() 55 returnStr=%', returnStr;
END IF;
END LOOP;
RETURN returnStr;
END;
$$ LANGUAGE plpgsql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_ReplaceAroundChars(text, text, text, text, boolean);
CREATE OR REPLACE FUNCTION TT_ReplaceAroundChars(
inStr text,
chars text,
searchStrings text,
replacementStrings text,
outside boolean DEFAULT FALSE
)
RETURNS text AS $$
SELECT TT_ReplaceAroundChars(inStr, ARRAY[chars, chars], ARRAY[searchStrings], ARRAY[replacementStrings], outside);
$$ LANGUAGE sql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_ReplaceAroundChars(text, text, text[], text[], boolean);
CREATE OR REPLACE FUNCTION TT_ReplaceAroundChars(
inStr text,
chars text,
searchStrings text[],
replacementStrings text[],
outside boolean DEFAULT FALSE
)
RETURNS text AS $$
SELECT TT_ReplaceAroundChars(inStr, ARRAY[chars, chars], searchStrings, replacementStrings, outside);
$$ LANGUAGE sql IMMUTABLE;
-- DROP FUNCTION IF EXISTS TT_ReplaceAroundChars(text, text[], text text, boolean);
CREATE OR REPLACE FUNCTION TT_ReplaceAroundChars(
inStr text,
chars text[],
searchStrings text,
replacementStrings text,
outside boolean DEFAULT FALSE
)
RETURNS text AS $$
SELECT TT_ReplaceAroundChars(inStr, chars, ARRAY[searchStrings], ARRAY[replacementStrings], outside);
$$ LANGUAGE sql IMMUTABLE;
/*
SELECT TT_ReplaceAroundChars('aa', '''', '\\a\', 'x\1y', TRUE);
SELECT TT_ReplaceAroundChars('{aa}', '''', ARRAY['\{\', '\}\'], ARRAY['ARRAY[',']'], TRUE);
*/
-------------------------------------------------------------------------------
-------------------------------------------------------------------------------
-- TT_LowerArr
-- Lowercase text array (often to compare them while ignoring case)
------------------------------------------------------------
--DROP FUNCTION IF EXISTS TT_LowerArr(text[]);
CREATE OR REPLACE FUNCTION TT_LowerArr(
arr text[] DEFAULT NULL