]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/999.functions.global.sql
moving the record-merge stored proc to the end of the schema load, to avoid cross...
[working/Evergreen.git] / Open-ILS / src / sql / Pg / 999.functions.global.sql
1 /*
2  * Copyright (C) 2008 Equinox Software, Inc.
3  * Bill Erickson <erickson@esilibrary.com>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  */
16
17 CREATE OR REPLACE FUNCTION actor.usr_merge_rows( table_name TEXT, col_name TEXT, src_usr INT, dest_usr INT ) RETURNS VOID AS $$
18 DECLARE
19     sel TEXT;
20     upd TEXT;
21     del TEXT;
22     cur_row RECORD;
23 BEGIN
24     sel := 'SELECT id::BIGINT FROM ' || table_name || ' WHERE ' || quote_ident(col_name) || ' = ' || quote_literal(src_usr);
25     upd := 'UPDATE ' || table_name || ' SET ' || quote_ident(col_name) || ' = ' || quote_literal(dest_usr) || ' WHERE id = ';
26     del := 'DELETE FROM ' || table_name || ' WHERE id = ';
27     FOR cur_row IN EXECUTE sel LOOP
28         BEGIN
29             --RAISE NOTICE 'Attempting to merge % %', table_name, cur_row.id;
30             EXECUTE upd || cur_row.id;
31         EXCEPTION WHEN unique_violation THEN
32             --RAISE NOTICE 'Deleting conflicting % %', table_name, cur_row.id;
33             EXECUTE del || cur_row.id;
34         END;
35     END LOOP;
36 END;
37 $$ LANGUAGE plpgsql;
38
39 COMMENT ON FUNCTION actor.usr_merge_rows(TEXT, TEXT, INT, INT) IS $$
40 /**
41  * Attempts to move each row of the specified table from src_user to dest_user.  
42  * Where conflicts exist, the conflicting "source" row is deleted.
43  */
44 $$;
45
46
47 CREATE OR REPLACE FUNCTION actor.usr_merge( src_usr INT, dest_usr INT, del_addrs BOOLEAN, del_cards BOOLEAN, deactivate_cards BOOLEAN ) RETURNS VOID AS $$
48 BEGIN
49
50     -- do some initial cleanup 
51     UPDATE actor.usr SET card = NULL WHERE id = src_usr;
52     UPDATE actor.usr SET mailing_address = NULL WHERE id = src_usr;
53     UPDATE actor.usr SET billing_address = NULL WHERE id = src_usr;
54
55     -- actor.*
56     IF del_cards THEN
57         DELETE FROM actor.card where usr = src_usr;
58     ELSE
59         IF deactivate_cards THEN
60             UPDATE actor.card SET active = 'f' WHERE usr = src_usr;
61         END IF;
62         UPDATE actor.card SET usr = dest_usr WHERE usr = src_usr;
63     END IF;
64
65
66     IF del_addrs THEN
67         DELETE FROM actor.usr_address WHERE usr = src_usr;
68     ELSE
69         UPDATE actor.usr_address SET usr = dest_usr WHERE usr = src_usr;
70     END IF;
71
72     UPDATE actor.usr_note SET usr = dest_usr WHERE usr = src_usr;
73     -- dupes are technically OK in actor.usr_standing_penalty, should manually delete them...
74     UPDATE actor.usr_standing_penalty SET usr = dest_usr WHERE usr = src_usr;
75     PERFORM actor.usr_merge_rows('actor.usr_org_unit_opt_in', 'usr', src_usr, dest_usr);
76     PERFORM actor.usr_merge_rows('actor.usr_setting', 'usr', src_usr, dest_usr);
77
78     -- permission.*
79     PERFORM actor.usr_merge_rows('permission.usr_perm_map', 'usr', src_usr, dest_usr);
80     PERFORM actor.usr_merge_rows('permission.usr_object_perm_map', 'usr', src_usr, dest_usr);
81     PERFORM actor.usr_merge_rows('permission.usr_grp_map', 'usr', src_usr, dest_usr);
82     PERFORM actor.usr_merge_rows('permission.usr_work_ou_map', 'usr', src_usr, dest_usr);
83
84
85     -- container.*
86     PERFORM actor.usr_merge_rows('container.biblio_record_entry_bucket', 'owner', src_usr, dest_usr);
87     PERFORM actor.usr_merge_rows('container.call_number_bucket', 'owner', src_usr, dest_usr);
88     PERFORM actor.usr_merge_rows('container.copy_bucket', 'owner', src_usr, dest_usr);
89     PERFORM actor.usr_merge_rows('container.user_bucket', 'owner', src_usr, dest_usr);
90         UPDATE container.user_bucket_item SET target_user = dest_usr WHERE target_user = src_usr;
91
92     -- vandelay.*
93     PERFORM actor.usr_merge_rows('vandelay.queue', 'owner', src_usr, dest_usr);
94
95     -- money.*
96     PERFORM actor.usr_merge_rows('money.collections_tracker', 'usr', src_usr, dest_usr);
97     PERFORM actor.usr_merge_rows('money.collections_tracker', 'collector', src_usr, dest_usr);
98     UPDATE money.billable_xact SET usr = dest_usr WHERE usr = src_usr;
99     UPDATE money.billing SET voider = dest_usr WHERE voider = src_usr;
100     UPDATE money.bnm_payment SET accepting_usr = dest_usr WHERE accepting_usr = src_usr;
101
102     -- action.*
103     UPDATE action.circulation SET usr = dest_usr WHERE usr = src_usr;
104     UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
105     UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
106
107     UPDATE action.hold_request SET usr = dest_usr WHERE usr = src_usr;
108     UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
109     UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
110     UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
111
112     UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
113     UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
114     UPDATE action.non_cataloged_circulation SET patron = dest_usr WHERE patron = src_usr;
115     UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
116     UPDATE action.survey_response SET usr = dest_usr WHERE usr = src_usr;
117
118     -- acq.*
119     UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
120     PERFORM actor.usr_merge_rows('acq.picklist', 'owner', src_usr, dest_usr);
121     UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
122     UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
123     UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
124     UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
125     UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
126     UPDATE acq.lineitem_usr_attr_definition SET usr = dest_usr WHERE usr = src_usr;
127
128     -- asset.*
129     UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
130     UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
131     UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
132     UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
133     UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
134     UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
135
136     -- serial.*
137     UPDATE serial.record_entry SET creator = dest_usr WHERE creator = src_usr;
138     UPDATE serial.record_entry SET editor = dest_usr WHERE editor = src_usr;
139
140     -- reporter.*
141     -- It's not uncommon to define the reporter schema in a replica 
142     -- DB only, so don't assume these tables exist in the write DB.
143     BEGIN
144         UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
145     EXCEPTION WHEN undefined_table THEN
146         -- do nothing
147     END;
148     BEGIN
149         UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
150     EXCEPTION WHEN undefined_table THEN
151         -- do nothing
152     END;
153     BEGIN
154         UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
155     EXCEPTION WHEN undefined_table THEN
156         -- do nothing
157     END;
158     BEGIN
159         PERFORM actor.usr_merge_rows('reporter.template_folder', 'owner', src_usr, dest_usr);
160     EXCEPTION WHEN undefined_table THEN
161         -- do nothing
162     END;
163     BEGIN
164         PERFORM actor.usr_merge_rows('reporter.report_folder', 'owner', src_usr, dest_usr);
165     EXCEPTION WHEN undefined_table THEN
166         -- do nothing
167     END;
168     BEGIN
169         PERFORM actor.usr_merge_rows('reporter.output_folder', 'owner', src_usr, dest_usr);
170     EXCEPTION WHEN undefined_table THEN
171         -- do nothing
172     END;
173
174     -- Finally, delete the source user
175     DELETE FROM actor.usr WHERE id = src_usr;
176
177 END;
178 $$ LANGUAGE plpgsql;
179
180 COMMENT ON FUNCTION actor.usr_merge(INT, INT, BOOLEAN, BOOLEAN, BOOLEAN) IS $$
181 /**
182  * Merges all user date from src_usr to dest_usr.  When collisions occur, 
183  * keep dest_usr's data and delete src_usr's data.
184  */
185 $$;
186
187
188
189 CREATE OR REPLACE FUNCTION actor.approve_pending_address(pending_id INT) RETURNS BIGINT AS $$
190 DECLARE
191     old_id INT;
192 BEGIN
193     SELECT INTO old_id replaces FROM actor.usr_address where id = pending_id;
194     IF old_id IS NULL THEN
195         UPDATE actor.usr_address SET pending = 'f' WHERE id = pending_id;
196         RETURN pending_id;
197     END IF;
198     -- address replaces an existing address
199     DELETE FROM actor.usr_address WHERE id = -old_id;
200     UPDATE actor.usr_address SET id = -id WHERE id = old_id;
201     UPDATE actor.usr_address SET replaces = NULL, id = old_id, pending = 'f' WHERE id = pending_id;
202     RETURN old_id;
203 END
204 $$ LANGUAGE plpgsql;
205
206 COMMENT ON FUNCTION actor.approve_pending_address(INT) IS $$
207 /**
208  * Replaces an address with a pending address.  This is done by giving the pending 
209  * address the ID of the old address.  The replaced address is retained with -id.
210  */
211 $$;
212
213 CREATE OR REPLACE FUNCTION container.clear_expired_circ_history_items( 
214          ac_usr IN INTEGER
215 ) RETURNS VOID AS $$
216 --
217 -- Delete old circulation bucket items for a specified user.
218 -- "Old" means older than the interval specified by a
219 -- user-level setting, if it is so specified.
220 --
221 DECLARE
222     threshold TIMESTAMP WITH TIME ZONE;
223 BEGIN
224         -- Sanity check
225         IF ac_usr IS NULL THEN
226                 RETURN;
227         END IF;
228         -- Determine the threshold date that defines "old".  Subtract the
229         -- interval from the system date, then truncate to midnight.
230         SELECT
231                 date_trunc( 
232                         'day',
233                         now() - CAST( translate( value, '"', '' ) AS INTERVAL )
234                 )
235         INTO
236                 threshold
237         FROM
238                 actor.usr_setting
239         WHERE
240                 usr = ac_usr
241                 AND name = 'patron.max_reading_list_interval';
242         --
243         IF threshold is null THEN
244                 -- No interval defined; don't delete anything
245                 -- RAISE NOTICE 'No interval defined for user %', ac_usr;
246                 return;
247         END IF;
248         --
249         -- RAISE NOTICE 'Date threshold: %', threshold;
250         --
251         -- Threshold found; do the delete
252         delete from container.copy_bucket_item
253         where
254                 bucket in
255                 (
256                         select
257                                 id
258                         from
259                                 container.copy_bucket
260                         where
261                                 owner = ac_usr
262                                 and btype = 'circ_history'
263                 )
264                 and create_time < threshold;
265         --
266         RETURN;
267 END;
268 $$ LANGUAGE plpgsql;
269
270 COMMENT ON FUNCTION container.clear_expired_circ_history_items( INTEGER ) IS $$
271 /*
272  * Delete old circulation bucket items for a specified user.
273  * "Old" means older than the interval specified by a
274  * user-level setting, if it is so specified.
275 */
276 $$;
277
278 CREATE OR REPLACE FUNCTION container.clear_all_expired_circ_history_items( )
279 RETURNS VOID AS $$
280 --
281 -- Delete expired circulation bucket items for all users that have
282 -- a setting for patron.max_reading_list_interval.
283 --
284 DECLARE
285     today        TIMESTAMP WITH TIME ZONE;
286     threshold    TIMESTAMP WITH TIME ZONE;
287         usr_setting  RECORD;
288 BEGIN
289         SELECT date_trunc( 'day', now() ) INTO today;
290         --
291         FOR usr_setting in
292                 SELECT
293                         usr,
294                         value
295                 FROM
296                         actor.usr_setting
297                 WHERE
298                         name = 'patron.max_reading_list_interval'
299         LOOP
300                 --
301                 -- Make sure the setting is a valid interval
302                 --
303                 BEGIN
304                         threshold := today - CAST( translate( usr_setting.value, '"', '' ) AS INTERVAL );
305                 EXCEPTION
306                         WHEN OTHERS THEN
307                                 RAISE NOTICE 'Invalid setting patron.max_reading_list_interval for user %: ''%''',
308                                         usr_setting.usr, usr_setting.value;
309                                 CONTINUE;
310                 END;
311                 --
312                 --RAISE NOTICE 'User % threshold %', usr_setting.usr, threshold;
313                 --
314         DELETE FROM container.copy_bucket_item
315         WHERE
316                 bucket IN
317                 (
318                     SELECT
319                         id
320                     FROM
321                         container.copy_bucket
322                     WHERE
323                         owner = usr_setting.usr
324                         AND btype = 'circ_history'
325                 )
326                 AND create_time < threshold;
327         END LOOP;
328         --
329 END;
330 $$ LANGUAGE plpgsql;
331
332 COMMENT ON FUNCTION container.clear_all_expired_circ_history_items( ) IS $$
333 /*
334  * Delete expired circulation bucket items for all users that have
335  * a setting for patron.max_reading_list_interval.
336 */
337 $$
338
339
340 CREATE OR REPLACE FUNCTION asset.merge_record_assets( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
341 DECLARE
342         moved_objects INT := 0;
343         source_cn     asset.call_number%ROWTYPE;
344         target_cn     asset.call_number%ROWTYPE;
345         metarec       metabib.metarecord%ROWTYPE;
346         hold          action.hold_request%ROWTYPE;
347         ser_rec       serial.record_entry%ROWTYPE;
348     uri_count     INT := 0;
349     counter       INT := 0;
350     uri_datafield TEXT;
351     uri_text      TEXT := '';
352 BEGIN
353
354     -- move any 856 entries on records that have at least one MARC-mapped URI entry
355     SELECT  INTO uri_count COUNT(*)
356       FROM  asset.uri_call_number_map m
357             JOIN asset.call_number cn ON (m.call_number = cn.id)
358       WHERE cn.record = source_record;
359
360     IF uri_count > 0 THEN
361         
362         SELECT  COUNT(*) INTO counter
363           FROM  xpath_table(
364                     'id',
365                     'marc',
366                     'acq.lineitem',
367                     '//*[@tag="856"]',
368                     'id=' || lineitem
369                 ) as t(i int,c text);
370     
371         FOR i IN 1 .. counter LOOP
372             SELECT  '<datafield xmlns="http://www.loc.gov/MARC21/slim" tag="856">' ||
373                         array_to_string(
374                             array_accum(
375                                 '<subfield code="' || subfield || '">' ||
376                                 regexp_replace(
377                                     regexp_replace(
378                                         regexp_replace(data,'&','&amp;','g'),
379                                         '>', '&gt;', 'g'
380                                     ),
381                                     '<', '&lt;', 'g'
382                                 ) || '</subfield>'
383                             ), ''
384                         ) || '</datafield>' INTO uri_datafield
385               FROM  xpath_table(
386                         'id',
387                         'marc',
388                         'biblio.record_entry',
389                         '//*[@tag="856"][position()=' || i || ']/*/@code|' ||
390                         '//*[@tag="856"][position()=' || i || ']/*[@code]',
391                         'id=' || source_record
392                     ) as t(id int,subfield text,data text);
393
394             uri_text := uri_text || uri_datafield;
395         END LOOP;
396
397         IF uri_text <> '' THEN
398             UPDATE  biblio.record_entry
399               SET   marc = regexp_replace(marc,'(</[^>]*record>)', uri_text || E'\\1')
400               WHERE id = target_record;
401         END IF;
402
403     END IF;
404
405         -- Find and move metarecords to the target record
406         SELECT  INTO metarec *
407           FROM  metabib.metarecord
408           WHERE master_record = source_record;
409
410         IF FOUND THEN
411                 UPDATE  metabib.metarecord
412                   SET   master_record = target_record,
413                         mods = NULL
414                   WHERE id = metarec.id;
415
416                 moved_objects := moved_objects + 1;
417         END IF;
418
419         -- Find call numbers attached to the source ...
420         FOR source_cn IN SELECT * FROM asset.call_number WHERE record = source_record LOOP
421
422                 SELECT  INTO target_cn *
423                   FROM  asset.call_number
424                   WHERE label = source_cn.label
425                         AND owning_lib = source_cn.owning_lib
426                         AND record = target_record;
427
428                 -- ... and if there's a conflicting one on the target ...
429                 IF FOUND THEN
430
431                         -- ... move the copies to that, and ...
432                         UPDATE  asset.copy
433                           SET   call_number = target_cn.id
434                           WHERE call_number = source_cn.id;
435
436                         -- ... move V holds to the move-target call number
437                         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_cn.id AND hold_type = 'V' LOOP
438                 
439                                 UPDATE  action.hold_request
440                                   SET   target = target_cn.id
441                                   WHERE id = hold.id;
442                 
443                                 moved_objects := moved_objects + 1;
444                         END LOOP;
445
446                 -- ... if not ...
447                 ELSE
448                         -- ... just move the call number to the target record
449                         UPDATE  asset.call_number
450                           SET   record = target_record
451                           WHERE id = source_cn.id;
452                 END IF;
453
454                 moved_objects := moved_objects + 1;
455         END LOOP;
456
457         -- Find T holds targeting the source record ...
458         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_record AND hold_type = 'T' LOOP
459
460                 -- ... and move them to the target record
461                 UPDATE  action.hold_request
462                   SET   target = target_record
463                   WHERE id = hold.id;
464
465                 moved_objects := moved_objects + 1;
466         END LOOP;
467
468         -- Find serial records targeting the source record ...
469         FOR ser_rec IN SELECT * FROM serial.record_entry WHERE record = source_record LOOP
470                 -- ... and move them to the target record
471                 UPDATE  serial.record_entry
472                   SET   record = target_record
473                   WHERE id = ser_rec.id;
474
475                 moved_objects := moved_objects + 1;
476         END LOOP;
477
478     -- Finally, "delete" the source record
479     DELETE FROM biblio.record_entry WHERE id = source_record;
480
481         -- That's all, folks!
482         RETURN moved_objects;
483 END;
484 $func$ LANGUAGE plpgsql;
485