-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsrvc.sql
More file actions
2796 lines (2321 loc) · 82.2 KB
/
Copy pathsrvc.sql
File metadata and controls
2796 lines (2321 loc) · 82.2 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
-- Disable check on function's body
SET check_function_bodies = off;
--
-- PostgreSQL database dump
--
-- Dumped from database version 15.7 (Ubuntu 15.7-0ubuntu0.23.10.1)
-- Dumped by pg_dump version 15.7 (Ubuntu 15.7-0ubuntu0.23.10.1)
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: srvc; Type: SCHEMA; Schema: -; Owner: -
--
CREATE SCHEMA srvc;
--
-- Name: object_type_enum; Type: TYPE; Schema: srvc; Owner: -
--
CREATE TYPE srvc.object_type_enum AS ENUM (
'table',
'view',
'materialized_view',
'function',
'aggregate',
'domain',
'trigger',
'cast',
'operator'
);
--
-- Name: __pckmgr__get_aggregate_definition(oid); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_aggregate_definition(p_aggregate_oid oid) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
v_name text;
v_comment text;
v_def text;
begin
-- Get common properties
select proname, obj_description(p_aggregate_oid, 'pg_proc')
into v_name, v_comment
from pg_proc
where oid = p_aggregate_oid;
-- Try to get the full aggregate definition (PostgreSQL 11+)
begin
select pg_get_aggregatedef(p_aggregate_oid) into v_def;
v_definition := jsonb_build_object(
'object_type', 'aggregate',
'name', v_name,
'source_code', v_def,
'comment', v_comment
);
exception when undefined_function then
-- Fallback for older PostgreSQL versions
raise notice 'Function pg_get_aggregatedef() not found. A basic definition will be provided.';
v_definition := jsonb_build_object(
'object_type', 'aggregate',
'name', v_name,
'source_code', format('/* The definition for the aggregate "%s" is not available on this version of PostgreSQL. */', v_name),
'comment', v_comment
);
end;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_aggregate_definition(p_aggregate_oid oid); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_aggregate_definition(p_aggregate_oid oid) IS 'Function to get the JSONB definition of an aggregate. This is a private method.';
--
-- Name: __pckmgr__get_cast_definition(oid); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_cast_definition(p_cast_oid oid) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
begin
select jsonb_build_object(
'object_type', 'cast',
'source_type', format_type(c.castsource, null),
'target_type', format_type(c.casttarget, null),
'cast_context', c.castcontext,
'cast_method', c.castmethod,
'function_name', (select proname from pg_proc where oid = c.castfunc),
'comment', obj_description(c.oid, 'pg_cast')
)
into v_definition
from pg_cast c
where c.oid = p_cast_oid;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_cast_definition(p_cast_oid oid); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_cast_definition(p_cast_oid oid) IS 'Function to get the JSONB definition of a cast. This is a private method.';
--
-- Name: __pckmgr__get_domain_definition(text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_domain_definition(p_schema_name text, p_domain_name text) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
v_oid oid;
begin
select t.oid from pg_type t
join pg_namespace n on n.oid = t.typnamespace
where n.nspname = p_schema_name
and t.typname = p_domain_name
and t.typtype = 'd'
into v_oid;
if v_oid is null then
return null;
end if;
select jsonb_build_object(
'object_type', 'domain',
'schema', n.nspname,
'name', t.typname,
'base_type', format_type(t.typbasetype, null),
'is_not_null', t.typnotnull,
'default_value', pg_get_expr(t.typdefaultbin, 0),
'comment', obj_description(t.oid, 'pg_type')
)
into v_definition
from pg_type t
join pg_namespace n on n.oid = t.typnamespace
where t.oid = v_oid;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_domain_definition(p_schema_name text, p_domain_name text); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_domain_definition(p_schema_name text, p_domain_name text) IS 'Function to get the JSONB definition of a domain. This is a private method.';
--
-- Name: __pckmgr__get_function_definition(oid); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_function_definition(p_function_oid oid) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
begin
select jsonb_build_object(
'object_type', 'function',
'name', p.proname,
'schema', n.nspname,
'oid', p.oid,
'signature', pg_get_function_arguments(p.oid),
'return_type', format_type(p.prorettype, null),
'source_code', pg_get_functiondef(p_function_oid),
'comment', obj_description(p_function_oid, 'pg_proc')
)
into v_definition
from pg_catalog.pg_proc p
join pg_catalog.pg_namespace n on n.oid = p.pronamespace
where p.oid = p_function_oid;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_function_definition(p_function_oid oid); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_function_definition(p_function_oid oid) IS 'Function to get the JSONB definition of a function. This is a private method.';
--
-- Name: __pckmgr__get_operator_definition(text, text, oid, oid); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_operator_definition(p_schema_name text, p_operator_name text, p_left_type_oid oid, p_right_type_oid oid) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
begin
select jsonb_build_object(
'object_type', 'operator',
'schema', n.nspname,
'name', o.oprname,
'left_type', format_type(o.oprleft, null),
'right_type', format_type(o.oprright, null),
'function_oid', o.oprcode,
'comment', obj_description(o.oid, 'pg_operator')
)
into v_definition
from pg_catalog.pg_operator o
join pg_catalog.pg_namespace n on n.oid = o.oprnamespace
where n.nspname = p_schema_name
and o.oprname = p_operator_name
and o.oprleft = p_left_type_oid
and o.oprright = p_right_type_oid;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_operator_definition(p_schema_name text, p_operator_name text, p_left_type_oid oid, p_right_type_oid oid); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_operator_definition(p_schema_name text, p_operator_name text, p_left_type_oid oid, p_right_type_oid oid) IS 'Function to get the JSONB definition of an operator. This is a private method.';
--
-- Name: __pckmgr__get_table_definition(text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_table_definition(p_schema_name text, p_table_name text) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
v_cols jsonb;
v_constraints jsonb;
v_indexes jsonb;
v_pk_uk_indexes oid[];
begin
-- Gets column definitions
select jsonb_agg(
jsonb_build_object(
'column_id', a.attnum,
'column_name', a.attname,
'ordinal_position', a.attnum,
'data_type', format_type(a.atttypid, a.atttypmod),
'is_nullable', not a.attnotnull,
'default_value', pg_get_expr(ad.adbin, 0),
'identity_generation', case a.attidentity when 'd' then 'by default' when 'a' then 'always' else null end,
'generated_type', case a.attgenerated when 's' then 'stored' else null end,
'comment', col_description(a.attrelid, a.attnum)
)
order by a.attnum
)
into v_cols
from pg_catalog.pg_attribute a
left join pg_catalog.pg_attrdef ad on ad.adrelid = a.attrelid and ad.adnum = a.attnum
where a.attrelid = (p_schema_name || '.' || p_table_name)::regclass
and a.attnum > 0
and not a.attisdropped;
-- Gets the OIDs of indexes for primary and unique keys
select array_agg(conindid)
into v_pk_uk_indexes
from pg_catalog.pg_constraint
where conrelid = (p_schema_name || '.' || p_table_name)::regclass
and contype in ('p', 'u');
-- Gets constraint definitions (excluding indexes)
select jsonb_agg(
jsonb_build_object(
'constraint_name', conname,
'constraint_type', case contype
when 'p' then 'PRIMARY KEY'
when 'f' then 'FOREIGN KEY'
when 'u' then 'UNIQUE'
when 'c' then 'CHECK'
end,
'definition', pg_get_constraintdef(oid),
'comment', obj_description(oid, 'pg_constraint')
)
)
into v_constraints
from pg_catalog.pg_constraint
where conrelid = (p_schema_name || '.' || p_table_name)::regclass;
-- Gets index definitions (excluding those created by PK/UK)
select jsonb_agg(
jsonb_build_object(
'index_name', i.relname,
'definition', pg_get_indexdef(i.oid),
'comment', obj_description(i.oid, 'pg_class')
)
)
into v_indexes
from pg_catalog.pg_class i
join pg_catalog.pg_index ix on ix.indexrelid = i.oid
where i.relkind = 'i'
and ix.indrelid = (p_schema_name || '.' || p_table_name)::regclass
and not (i.oid = any(v_pk_uk_indexes));
select jsonb_build_object(
'object_type', 'table',
'schema', p_schema_name,
'name', p_table_name,
'comment', obj_description(format('%I.%I', p_schema_name, p_table_name)::regclass, 'pg_class'),
'columns', v_cols,
'constraints', v_constraints,
'indexes', v_indexes
)
into v_definition;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_table_definition(p_schema_name text, p_table_name text); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_table_definition(p_schema_name text, p_table_name text) IS 'Function to get the JSONB definition of a table. This is a private method.';
--
-- Name: __pckmgr__get_trigger_definition(oid); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_trigger_definition(p_trigger_oid oid) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
begin
select jsonb_build_object(
'object_type', 'trigger',
'name', tg.tgname,
'table_name', c.relname,
'function_name', f.proname,
'definition', pg_get_triggerdef(tg.oid),
'comment', obj_description(tg.oid, 'pg_trigger')
)
into v_definition
from pg_trigger tg
join pg_class c on c.oid = tg.tgrelid
join pg_proc f on f.oid = tg.tgfoid
where tg.oid = p_trigger_oid;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_trigger_definition(p_trigger_oid oid); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_trigger_definition(p_trigger_oid oid) IS 'Function to get the JSONB definition of a trigger. This is a private method.';
--
-- Name: __pckmgr__get_view_definition(text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__get_view_definition(p_schema_name text, p_view_name text) RETURNS jsonb
LANGUAGE plpgsql
AS $$
declare
v_definition jsonb;
begin
select jsonb_build_object(
'object_type', 'view',
'schema', p_schema_name,
'name', p_view_name,
'source_code', pg_get_viewdef(format('%I.%I', p_schema_name, p_view_name)),
'comment', obj_description(format('%I.%I', p_schema_name, p_view_name)::regclass, 'pg_class')
)
into v_definition;
return v_definition;
end;
$$;
--
-- Name: FUNCTION __pckmgr__get_view_definition(p_schema_name text, p_view_name text); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__get_view_definition(p_schema_name text, p_view_name text) IS 'Function to get the JSONB definition of a view. This is a private method.';
--
-- Name: __pckmgr__is_table_compatible(jsonb, jsonb); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.__pckmgr__is_table_compatible(old_def jsonb, new_def jsonb) RETURNS boolean
LANGUAGE plpgsql
AS $$
declare
v_old_cols jsonb;
v_new_cols jsonb;
v_old_col jsonb;
v_new_col jsonb;
v_compatible boolean := true;
begin
-- Retrieves column lists
v_old_cols := old_def->'columns';
v_new_cols := new_def->'columns';
-- Checks if table definitions are valid
if v_old_cols is null or v_new_cols is null then
return false;
end if;
-- Iterates over the columns of the old definition
for v_old_col in select * from jsonb_array_elements(v_old_cols) loop
-- Searches for the corresponding column in the new definition
select val into v_new_col
from jsonb_array_elements(v_new_cols) with ordinality as t(val, ord)
where val->>'column_name' = v_old_col->>'column_name';
-- If an old column is no longer present, it is not compatible
if v_new_col is null then
v_compatible := false;
exit;
end if;
-- Checks if the data type has changed
if v_old_col->>'data_type' is distinct from v_new_col->>'data_type' then
-- For now, we consider any type change as incompatible
v_compatible := false;
exit;
end if;
-- Checks if a column has become NOT NULL
if (v_old_col->>'is_nullable')::boolean and not (v_new_col->>'is_nullable')::boolean then
v_compatible := false;
exit;
end if;
end loop;
return v_compatible;
end;
$$;
--
-- Name: FUNCTION __pckmgr__is_table_compatible(old_def jsonb, new_def jsonb); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.__pckmgr__is_table_compatible(old_def jsonb, new_def jsonb) IS 'Private function to determine if a table has undergone incompatible changes.';
--
-- Name: analyze_schema_functions(text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.analyze_schema_functions(p_schema_name text) RETURNS TABLE(function_type text, count_functions bigint, total_lines bigint, avg_complexity numeric)
LANGUAGE sql
AS $$
select
case p.prokind
when 'f' then 'function'
when 'p' then 'procedure'
when 'a' then 'aggregate'
when 'w' then 'window'
else 'unknown'
end as function_type,
count(*) as count_functions,
-- Per le aggregate non possiamo usare pg_get_functiondef, usiamo un valore fisso
sum(
case
when p.prokind = 'a' then 5 -- Linee approssimative per aggregate
else array_length(string_to_array(pg_get_functiondef(p.oid), E'\n'), 1)
end
) as total_lines,
avg(
case
when p.prokind = 'a' then 5 -- Complessità approssimativa per aggregate
else array_length(string_to_array(pg_get_functiondef(p.oid), E'\n'), 1)
end
) as avg_complexity
from pg_proc p
join pg_namespace n on n.oid = p.pronamespace
where n.nspname = p_schema_name
group by p.prokind
order by count_functions desc;
$$;
--
-- Name: clone_schema(text, text, boolean); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.clone_schema(source_schema text, dest_schema text, include_recs boolean) RETURNS void
LANGUAGE plpgsql
AS $$
-- This function will clone all sequences, tables, data, views & functions from any existing schema to a new one
-- SAMPLE CALL:
-- SELECT clone_schema('public', 'new_schema', TRUE);
DECLARE
src_oid oid;
tbl_oid oid;
func_oid oid;
object text;
buffer text;
srctbl text;
default_ text;
column_ text;
qry text;
dest_qry text;
v_def text;
seqval bigint;
sq_last_value bigint;
sq_max_value bigint;
sq_start_value bigint;
sq_increment_by bigint;
sq_min_value bigint;
sq_cache_value bigint;
sq_log_cnt bigint;
sq_is_called boolean;
sq_is_cycled boolean;
sq_cycled char(10);
BEGIN
-- Check that source_schema exists
SELECT oid INTO src_oid
FROM pg_namespace
WHERE nspname = quote_ident(source_schema);
IF NOT FOUND
THEN
RAISE NOTICE 'source schema % does not exist!', source_schema;
RETURN ;
END IF;
-- Check that dest_schema does not yet exist
PERFORM nspname
FROM pg_namespace
WHERE nspname = quote_ident(dest_schema);
IF FOUND
THEN
RAISE NOTICE 'dest schema % already exists!', dest_schema;
RETURN ;
END IF;
EXECUTE 'CREATE SCHEMA ' || quote_ident(dest_schema) ;
-- Create sequences
-- TODO: Find a way to make this sequence's owner is the correct table.
FOR object IN
SELECT sequence_name::text
FROM information_schema.sequences
WHERE sequence_schema = quote_ident(source_schema)
LOOP
EXECUTE 'CREATE SEQUENCE ' || quote_ident(dest_schema) || '.' || quote_ident(object);
srctbl := quote_ident(source_schema) || '.' || quote_ident(object);
EXECUTE 'SELECT last_value, max_value, start_value, increment_by, min_value, cache_value, log_cnt, is_cycled, is_called
FROM ' || quote_ident(source_schema) || '.' || quote_ident(object) || ';'
INTO sq_last_value, sq_max_value, sq_start_value, sq_increment_by, sq_min_value, sq_cache_value, sq_log_cnt, sq_is_cycled, sq_is_called ;
IF sq_is_cycled
THEN
sq_cycled := 'CYCLE';
ELSE
sq_cycled := 'NO CYCLE';
END IF;
EXECUTE 'ALTER SEQUENCE ' || quote_ident(dest_schema) || '.' || quote_ident(object)
|| ' INCREMENT BY ' || sq_increment_by
|| ' MINVALUE ' || sq_min_value
|| ' MAXVALUE ' || sq_max_value
|| ' START WITH ' || sq_start_value
|| ' RESTART ' || sq_min_value
|| ' CACHE ' || sq_cache_value
|| sq_cycled || ' ;' ;
buffer := quote_ident(dest_schema) || '.' || quote_ident(object);
IF include_recs
THEN
EXECUTE 'SELECT setval( ''' || buffer || ''', ' || sq_last_value || ', ' || sq_is_called || ');' ;
ELSE
EXECUTE 'SELECT setval( ''' || buffer || ''', ' || sq_start_value || ', ' || sq_is_called || ');' ;
END IF;
END LOOP;
-- Create tables
FOR object IN
SELECT TABLE_NAME::text
FROM information_schema.tables
WHERE table_schema = quote_ident(source_schema)
AND table_type = 'BASE TABLE'
LOOP
buffer := dest_schema || '.' || quote_ident(object);
EXECUTE 'CREATE TABLE ' || buffer || ' (LIKE ' || quote_ident(source_schema) || '.' || quote_ident(object)
|| ' INCLUDING ALL)';
IF include_recs
THEN
-- Insert records from source table
EXECUTE 'INSERT INTO ' || buffer || ' SELECT * FROM ' || quote_ident(source_schema) || '.' || quote_ident(object) || ';';
END IF;
FOR column_, default_ IN
SELECT column_name::text,
REPLACE(column_default::text, source_schema, dest_schema)
FROM information_schema.COLUMNS
WHERE table_schema = dest_schema
AND TABLE_NAME = object
AND column_default LIKE 'nextval(%' || quote_ident(source_schema) || '%::regclass)'
LOOP
EXECUTE 'ALTER TABLE ' || buffer || ' ALTER COLUMN ' || column_ || ' SET DEFAULT ' || default_;
END LOOP;
END LOOP;
-- add FK constraint
FOR qry IN
SELECT 'ALTER TABLE ' || quote_ident(dest_schema) || '.' || quote_ident(rn.relname)
|| ' ADD CONSTRAINT ' || quote_ident(ct.conname) || ' ' || pg_get_constraintdef(ct.oid) || ';'
FROM pg_constraint ct
JOIN pg_class rn ON rn.oid = ct.conrelid
WHERE connamespace = src_oid
AND rn.relkind = 'r'
AND ct.contype = 'f'
LOOP
EXECUTE qry;
END LOOP;
-- Create views
FOR object IN
SELECT table_name::text,
view_definition
FROM information_schema.views
WHERE table_schema = quote_ident(source_schema)
LOOP
buffer := dest_schema || '.' || quote_ident(object);
SELECT view_definition INTO v_def
FROM information_schema.views
WHERE table_schema = quote_ident(source_schema)
AND table_name = quote_ident(object);
EXECUTE 'CREATE OR REPLACE VIEW ' || buffer || ' AS ' || v_def || ';' ;
END LOOP;
-- Create functions
FOR func_oid IN
SELECT oid
FROM pg_proc
WHERE pronamespace = src_oid
LOOP
SELECT pg_get_functiondef(func_oid) INTO qry;
SELECT replace(qry, source_schema, dest_schema) INTO dest_qry;
EXECUTE dest_qry;
END LOOP;
RETURN;
END;
$$;
--
-- Name: create_additional_table(text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.create_additional_table(table_schema text, table_name text) RETURNS boolean
LANGUAGE plpgsql
AS $$declare
/*
IN table_schema text,
IN table_name text
*/
_sqlStr text;
begin
_sqlStr = srvc.ddl_get__history_table(
table_schema, table_name
) || srvc.ddl_get__bitemporal_view(
table_schema, table_name
);
raise notice '%', _sqlStr;
execute _sqlStr;
return true;
end;
$$;
--
-- Name: ddl_get__bitemporal_view(text, text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.ddl_get__bitemporal_view(table_schema text, table_name text, full_view_name text DEFAULT NULL::text) RETURNS text
LANGUAGE plpgsql
AS $_$declare
/*
IN table_schema text
, IN table_name text
, IN full_view_name text DEFAULT null
*/
_table_schema alias for table_schema;
_table_name alias for table_name;
_view_name text;
_view_schema text;
_colName text;
_ret text='';
_trigger_name text;
_array text[];
_i integer;
begin
if full_view_name is null then
_view_schema=_table_schema;
_i= strpos ( _table_name, '_current' );
if _i >0 then
_view_name = substr ( _table_name, 1, _i -1 );
else
_view_name=_table_name||'_current';
end if;
else
_array=string_to_array(full_view_name,'.');
if array_length(_array,1)<>2 then
raise exception 'full_view_name must be in the format _SCHEMA_._VIEW_NAME_, given: <%>', full_view_name;
end if;
_view_schema=_array[1];
_view_name=_array[2];
end if;
full_view_name=format('%I.%I', _view_schema, _view_name);
_trigger_name='trg_'|| _view_name;
for _colName in
SELECT s.column_name
FROM information_schema.columns as s
WHERE s.table_schema = _table_schema
AND s.table_name = _table_name
and s.column_name <> 'bt_info'
order by s.ordinal_position
loop
_ret=_ret || format( E'\ts.%I\n\t,', _colName ) ;
end loop;
_ret=format($$
--drop view %1$s;
create or replace view %1$s as
select%2$s false AS is_closed
, NULL::text AS modify_user_id
, NULL::timestamp with time zone AS modify_ts
, NULL::jsonb AS action_hints
from only %3$I.%4$I as s;
CREATE OR REPLACE TRIGGER %5$I
INSTEAD OF INSERT OR DELETE OR UPDATE
ON %1$s
FOR EACH ROW
EXECUTE FUNCTION vrsn.trigger_handler();$$
, full_view_name
, _ret
, _table_schema
, _table_name
, _trigger_name);
return _ret;
end;$_$;
--
-- Name: FUNCTION ddl_get__bitemporal_view(table_schema text, table_name text, full_view_name text); Type: COMMENT; Schema: srvc; Owner: -
--
COMMENT ON FUNCTION srvc.ddl_get__bitemporal_view(table_schema text, table_name text, full_view_name text) IS 'Get the standard defintion of view ready for manage bitemporal storage.';
--
-- Name: ddl_get__history_table(text, text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.ddl_get__history_table(table_schema text, table_name text, full_history_table_name text DEFAULT NULL::text) RETURNS text
LANGUAGE plpgsql
AS $_$declare
/*
IN table_schema text
, IN table_name text
, IN full_history_table_name text DEFAULT null
*/
_table_schema alias for table_schema;
_table_name alias for table_name;
_full_current_table_name text = _table_schema || '.' ||_table_name;
_history_table_name text;
_history_table_schema text;
_pkey_name text;
_pkey_def text;
_ret text=$retValue$
CREATE TABLE %1$I.%2$I (
CONSTRAINT %3$s %4$s
) INHERITS (%5$I.%6$I);
$retValue$;
_array text[];
_i integer;
begin
-- se il nome non è passato
if full_history_table_name is null then
_history_table_schema=_table_schema;
-- cerco il suffiso _current per rimuoverlo
_i= strpos ( _table_name, '_current' );
if _i >0 then
_history_table_name = substr ( _table_name, 1, _i -1 );
else
_history_table_name=_table_name;
end if;
_history_table_name=_history_table_name ||'_history';
else
_array=string_to_array(full_history_table_name,'.');
_i=array_length(_array,1);
if _i= 1 then
_history_table_schema=_table_schema;
_history_table_name= full_history_table_name;
elseif _i=2 then
_history_table_schema=_array[1];
_history_table_name=_array[2];
else
raise exception 'full_history_table_name must be in the format [_SCHEMA_NAME_.]_TABLE_NAME_, given: <%>', full_history_table_name;
end if;
end if;
-- ricompatto il nome
--full_history_table_name=format('%I.%I', _history_table_schema, _history_table_name);
-- recupero primary key e definizione
SELECT conname, pg_get_constraintdef(oid) as def_text into _pkey_name,_pkey_def
FROM pg_constraint
WHERE contype = 'p' -- p = primary key constraint
AND conrelid = to_regclass(_full_current_table_name); -- regclass will type the name of the object to its internal oid
_pkey_name = replace(_pkey_name, _table_name, _history_table_name);
_pkey_def = replace(_pkey_def, ')', ',bt_info)');
_ret=format(_ret
, _history_table_schema
, _history_table_name
, _pkey_name
, _pkey_def
, _table_schema
, _table_name
);
return _ret;
end;$_$;
--
-- Name: find_table_dependencies(text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.find_table_dependencies(p_schema_name text, p_table_name text) RETURNS TABLE(function_name name, function_schema name, parameters text, return_type text, found_in text)
LANGUAGE sql STABLE
AS $$
WITH target_table AS (
SELECT
p_schema_name AS schema_name,
p_table_name AS table_name
),
search_patterns AS (
SELECT
t.schema_name,
t.table_name,
t.schema_name || '.' || t.table_name AS qualified_name,
-- Array di pattern diversi
ARRAY[
t.schema_name || '\.' || t.table_name, -- schema.tabella
t.table_name, -- solo tabella
t.table_name || '%ROWTYPE', -- per tipi %ROWTYPE
'SETOF ' || t.schema_name || '\.' || t.table_name, -- SETOF schema.tabella
'SETOF ' || t.table_name -- SETOF tabella
] AS patterns
FROM target_table t
)
SELECT DISTINCT
p.proname AS function_name,
n.nspname AS function_schema,
pg_get_function_identity_arguments(p.oid) AS parameters,
pg_get_function_result(p.oid) AS return_type,
STRING_AGG(
CASE
WHEN pg_get_function_identity_arguments(p.oid) ~* pattern THEN 'Parameter'
WHEN pg_get_function_result(p.oid) ~* pattern THEN 'Return Type'
WHEN p.prosrc ~* pattern THEN 'Function Body'
END, ', '
) AS found_in
FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
CROSS JOIN search_patterns sp
CROSS JOIN UNNEST(sp.patterns) AS pattern
WHERE
pg_get_function_identity_arguments(p.oid) ~* pattern
OR pg_get_function_result(p.oid) ~* pattern
OR p.prosrc ~* pattern
GROUP BY p.proname, n.nspname, pg_get_function_identity_arguments(p.oid), pg_get_function_result(p.oid)
ORDER BY p.proname;
$$;
--
-- Name: generate_coalesce_update(text, text, text, text); Type: FUNCTION; Schema: srvc; Owner: -
--
CREATE FUNCTION srvc.generate_coalesce_update(p_schema_name text, p_table_name text, p_primary_key text DEFAULT 'id'::text, p_target_type text DEFAULT 'table'::text) RETURNS text
LANGUAGE plpgsql
AS $_$
DECLARE
column_info RECORD;
param_declarations TEXT[] := ARRAY[]::TEXT[];
set_clauses TEXT[] := ARRAY[]::TEXT[];
function_name TEXT;
function_sql TEXT;
target_exists BOOLEAN := FALSE;
BEGIN
function_name := format('update_%s_coalesce', p_table_name);
-- Verifica che il target esista (tabella o vista)
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = p_schema_name
AND table_name = p_table_name
AND table_type IN ('BASE TABLE', 'VIEW')
) INTO target_exists;