-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsicob_create_id_column.sql
More file actions
339 lines (303 loc) · 12 KB
/
Copy pathsicob_create_id_column.sql
File metadata and controls
339 lines (303 loc) · 12 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
SET CLIENT_ENCODING TO 'utf8';
CREATE OR REPLACE FUNCTION public.sicob_create_id_column(reloid regclass)
RETURNS void
LANGUAGE plpgsql
AS $function$
/*
DECLARE
sql TEXT;
rec RECORD;
rec2 RECORD;
had_column BOOLEAN;
i INTEGER;
new_name TEXT;
sicob_id_name TEXT;*/
BEGIN
--ADICIONA A LA TABLA UN CAMPO DE IDENTIFICACION UNICO LLAMADO "sicob_id"
--------------------------------------------------------------------------
PERFORM sicob_create_id_column(reloid,'sicob_id');
/*
<< sicob_id_setup >>
LOOP --{
had_column := FALSE;
BEGIN
sql := Format('ALTER TABLE %s ADD sicob_id SERIAL NOT NULL UNIQUE', reloid::text);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
sicob_id_name := 'sicob_id';
EXIT sicob_id_setup;
EXCEPTION
WHEN duplicate_column THEN
RAISE NOTICE 'Column sicob_id already exists';
had_column := TRUE;
WHEN others THEN
RAISE EXCEPTION 'sicobfying % (sicob_id): % (%)', reloid, SQLERRM, SQLSTATE;
END;
IF had_column THEN
SELECT pg_catalog.pg_get_serial_sequence(reloid::text, 'sicob_id')
AS seq INTO rec2;
-- Check data type is an integer
SELECT
pg_catalog.pg_get_serial_sequence(reloid::text, 'sicob_id') as seq,
t.typname, t.oid, a.attnotnull FROM pg_type t, pg_attribute a
WHERE a.atttypid = t.oid AND a.attrelid = reloid AND NOT a.attisdropped AND a.attname = 'sicob_id'
INTO STRICT rec;
-- 20=int2, 21=int4, 23=int8
IF rec.oid NOT IN (20,21,23) THEN -- {
RAISE NOTICE 'Existing sicob_id field is of invalid type % (need int2, int4 or int8), renaming', rec.typname;
ELSIF rec.seq IS NULL THEN -- }{
RAISE NOTICE 'Existing sicob_id field does not have an associated sequence, renaming';
ELSE -- }{
sql := Format('ALTER TABLE %s ALTER COLUMN sicob_id SET NOT NULL', reloid::text);
IF NOT EXISTS ( SELECT c.conname FROM pg_constraint c, pg_attribute a
WHERE c.conkey = ARRAY[a.attnum] AND c.conrelid = reloid
AND a.attrelid = reloid
AND NOT a.attisdropped
AND a.attname = 'sicob_id'
AND c.contype IN ( 'u', 'p' ) ) -- unique or pkey
THEN
sql := sql || ', ADD unique(sicob_id)';
END IF;
BEGIN
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
sicob_id_name := 'sicob_id';
EXIT sicob_id_setup;
EXCEPTION
WHEN unique_violation OR not_null_violation THEN
RAISE NOTICE '%, renaming', SQLERRM;
WHEN others THEN
RAISE EXCEPTION 'sicobfying % (sicob_id): % (%)', reloid, SQLERRM, SQLSTATE;
END;
END IF; -- }
-- invalid column, need rename and re-create it
i := 0;
<< rename_column >>
BEGIN
sql := Format('ALTER TABLE %s DROP COLUMN sicob_id', reloid::text);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXCEPTION
WHEN others THEN
RAISE NOTICE 'Could not rename/delete sicob_id with existing values: % (%)',
SQLERRM, SQLSTATE;
CONTINUE sicob_id_setup;
END;
END IF;
END LOOP; -- }
-- Try to copy data from new name if possible
IF new_name IS NOT NULL THEN
RAISE NOTICE 'Trying to recover data from % column', new_name;
BEGIN
-- Copy existing values to new field
-- NOTE: using ALTER is a workaround to a PostgreSQL bug and is also known to be faster for tables with many rows
-- See http://www.postgresql.org/message-id/20140530143150.GA11051@localhost
sql := Format('ALTER TABLE %s ALTER sicob_id TYPE int USING %I::integer', reloid::text, new_name);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
-- Find max value
sql := Format('SELECT coalesce(max(sicob_id), 0) as max FROM %s', reloid::text);
RAISE DEBUG 'Running %', sql;
EXECUTE sql INTO rec;
-- Find sequence name
SELECT pg_catalog.pg_get_serial_sequence(reloid::text, 'sicob_id')
AS seq INTO rec2;
-- Reset sequence name
sql := Format('ALTER SEQUENCE %s RESTART WITH %s', rec2.seq::text, rec.max + 1);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
-- Drop old column (all went fine if we got here)
sql := Format('ALTER TABLE %s DROP %I', reloid::text, new_name);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXCEPTION
WHEN others THEN
RAISE NOTICE 'Could not initialize sicob_id with existing values: % (%)',
SQLERRM, SQLSTATE;
END;
END IF;
-- Set primary key of the table if not already present (e.g. tables created from SQL API)
IF sicob_id_name IS NULL THEN
RAISE EXCEPTION 'sicobfying % (Didnt get sicob_id field name)', reloid;
END IF;
BEGIN
-- Is there already a primary key on this table for
-- a column other than our chosen primary key?
SELECT ci.relname AS pkey
INTO rec
FROM pg_class c
JOIN pg_attribute a ON a.attrelid = c.oid
LEFT JOIN pg_index idx ON c.oid = idx.indexrelid AND a.attnum = ANY(idx.indkey)
JOIN pg_class ci ON idx.indexrelid = ci.oid
WHERE c.oid = reloid::regclass
AND NOT a.attisdropped
AND a.attname != 'sicob_id'
AND idx.indisprimary;
-- Yes? Then drop it, we're adding our own PK to the column
-- we prefer.
IF FOUND THEN
RAISE DEBUG 'sicob_create_id_column: dropping unwanted primary key ''%''', rec.pkey;
sql := Format('ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s', reloid::text, rec.pkey);
EXECUTE sql;
END IF;
sql := Format('ALTER TABLE %s ADD PRIMARY KEY (sicob_id)', reloid::text);
EXECUTE sql;
EXCEPTION
WHEN others THEN
RAISE DEBUG 'Table % Can´t add PRIMARY KEY', reloid;
END;
*/
END;
$function$
;CREATE OR REPLACE FUNCTION public.sicob_create_id_column(reloid regclass, _sicob_id_name text)
RETURNS void
LANGUAGE plpgsql
AS $function$
DECLARE
sql TEXT;
rec RECORD;
rec2 RECORD;
had_column BOOLEAN;
i INTEGER;
new_name TEXT;
sicob_id_name TEXT;
BEGIN
-- reloid := 'temp._test_muni';
--ADICIONA A LA TABLA UN CAMPO DE IDENTIFICACION UNICO LLAMADO "sicob_id"
--------------------------------------------------------------------------
IF _sicob_id_name IS NOT NULL AND _sicob_id_name <> '' THEN
sicob_id_name := _sicob_id_name;
ELSE
sicob_id_name := 'sicob_id';
END IF;
<< sicob_id_setup >>
LOOP --{
had_column := FALSE;
BEGIN
sql := Format('ALTER TABLE %s ADD COLUMN %s SERIAL', reloid::text, sicob_id_name);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXIT sicob_id_setup;
EXCEPTION
WHEN duplicate_column THEN
RAISE NOTICE 'Column sicob_id already exists';
had_column := TRUE;
WHEN others THEN
IF SQLSTATE::text = '42701' THEN
RAISE NOTICE 'Column sicob_id already exists';
had_column := TRUE;
ELSE
RAISE EXCEPTION 'sicobfying % (sicob_create_id_column): % (%)', reloid, SQLERRM, SQLSTATE;
END IF;
END;
IF had_column THEN
SELECT pg_catalog.pg_get_serial_sequence(reloid::text, sicob_id_name)
AS seq INTO rec2;
-- Check data type is an integer
SELECT
pg_catalog.pg_get_serial_sequence(reloid::text, sicob_id_name) as seq,
t.typname, t.oid, a.attnotnull FROM pg_type t, pg_attribute a
WHERE a.atttypid = t.oid AND a.attrelid = reloid::regclass AND NOT a.attisdropped AND a.attname = sicob_id_name
INTO STRICT rec;
-- 20=int2, 21=int4, 23=int8
IF rec.oid NOT IN (20,21,23) THEN -- {
RAISE NOTICE 'Existing % field is of invalid type % (need int2, int4 or int8), renaming', sicob_id_name, rec.typname;
ELSIF rec.seq IS NULL THEN -- }{
RAISE NOTICE 'Existing sicob_id field does not have an associated sequence, renaming';
ELSE -- }{
sql := Format('ALTER TABLE %s ALTER COLUMN %s SET NOT NULL', reloid::text, sicob_id_name);
IF NOT EXISTS ( SELECT c.conname FROM pg_constraint c, pg_attribute a
WHERE c.conkey = ARRAY[a.attnum] AND c.conrelid = reloid
AND a.attrelid = reloid
AND NOT a.attisdropped
AND a.attname = sicob_id_name
AND c.contype IN ( 'u', 'p' ) ) -- unique or pkey
THEN
sql := sql || ', ADD unique(' || sicob_id_name || ')';
END IF;
BEGIN
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
--sicob_id_name := 'sicob_id';
EXIT sicob_id_setup;
EXCEPTION
WHEN unique_violation OR not_null_violation THEN
RAISE NOTICE '%, renaming', SQLERRM;
WHEN others THEN
RAISE EXCEPTION 'sicobfying % (sicob_id): % (%)', reloid, SQLERRM, SQLSTATE;
END;
END IF; -- }
-- invalid column, need rename and re-create it
i := 0;
<< rename_column >>
BEGIN
sql := Format('ALTER TABLE %s DROP COLUMN %s', reloid::text,sicob_id_name);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXCEPTION
WHEN others THEN
RAISE NOTICE 'Could not rename/delete sicob_id with existing values: % (%)',
SQLERRM, SQLSTATE;
CONTINUE sicob_id_setup;
END;
END IF;
END LOOP; -- }
-- Try to copy data from new name if possible
IF new_name IS NOT NULL THEN
RAISE NOTICE 'Trying to recover data from % column', new_name;
BEGIN
-- Copy existing values to new field
-- NOTE: using ALTER is a workaround to a PostgreSQL bug and is also known to be faster for tables with many rows
-- See http://www.postgresql.org/message-id/20140530143150.GA11051@localhost
sql := Format('ALTER TABLE %s ALTER %s TYPE int USING %I::integer', reloid::text,sicob_id_name, new_name);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
-- Find max value
sql := Format('SELECT coalesce(max(%s), 0) as max FROM %s',sicob_id_name, reloid::text);
RAISE DEBUG 'Running %', sql;
EXECUTE sql INTO rec;
-- Find sequence name
SELECT pg_catalog.pg_get_serial_sequence(reloid::text, sicob_id_name)
AS seq INTO rec2;
-- Reset sequence name
sql := Format('ALTER SEQUENCE %s RESTART WITH %s', rec2.seq::text, rec.max + 1);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
-- Drop old column (all went fine if we got here)
sql := Format('ALTER TABLE %s DROP %I', reloid::text, new_name);
RAISE DEBUG 'Running %', sql;
EXECUTE sql;
EXCEPTION
WHEN others THEN
RAISE NOTICE 'Could not initialize sicob_id with existing values: % (%)',
SQLERRM, SQLSTATE;
END;
END IF;
-- Set primary key of the table if not already present (e.g. tables created from SQL API)
IF sicob_id_name IS NULL THEN
RAISE EXCEPTION 'sicobfying % (Didnt get % field name)', reloid, sicob_id_name;
END IF;
BEGIN
-- Is there already a primary key on this table for
-- a column other than our chosen primary key?
SELECT c.conname as pkey into rec FROM pg_constraint c, pg_attribute a
WHERE c.conkey = ARRAY[a.attnum] AND c.conrelid = reloid::regclass
AND a.attrelid = reloid::regclass
AND NOT a.attisdropped
AND c.contype IN ( 'p' );
-- Yes? Then drop it, we're adding our own PK to the column
-- we prefer.
IF FOUND THEN
RAISE DEBUG 'sicob_create_id_column: dropping unwanted primary key ''%''', rec.pkey;
sql := Format('ALTER TABLE %s DROP CONSTRAINT IF EXISTS %s', reloid::text, rec.pkey);
EXECUTE sql;
END IF;
sql := Format('ALTER TABLE %s ADD PRIMARY KEY (%s)', reloid::text,sicob_id_name);
EXECUTE sql;
EXCEPTION
WHEN others THEN
RAISE DEBUG 'Table % Can´t add PRIMARY KEY', reloid;
END;
END;
$function$