]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/999.functions.global.sql
1. In the parent router process: wait for all of the immediate
[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 DECLARE
49         suffix TEXT;
50         bucket_row RECORD;
51         picklist_row RECORD;
52         queue_row RECORD;
53         folder_row RECORD;
54 BEGIN
55
56     -- do some initial cleanup 
57     UPDATE actor.usr SET card = NULL WHERE id = src_usr;
58     UPDATE actor.usr SET mailing_address = NULL WHERE id = src_usr;
59     UPDATE actor.usr SET billing_address = NULL WHERE id = src_usr;
60
61     -- actor.*
62     IF del_cards THEN
63         DELETE FROM actor.card where usr = src_usr;
64     ELSE
65         IF deactivate_cards THEN
66             UPDATE actor.card SET active = 'f' WHERE usr = src_usr;
67         END IF;
68         UPDATE actor.card SET usr = dest_usr WHERE usr = src_usr;
69     END IF;
70
71
72     IF del_addrs THEN
73         DELETE FROM actor.usr_address WHERE usr = src_usr;
74     ELSE
75         UPDATE actor.usr_address SET usr = dest_usr WHERE usr = src_usr;
76     END IF;
77
78     UPDATE actor.usr_note SET usr = dest_usr WHERE usr = src_usr;
79     -- dupes are technically OK in actor.usr_standing_penalty, should manually delete them...
80     UPDATE actor.usr_standing_penalty SET usr = dest_usr WHERE usr = src_usr;
81     PERFORM actor.usr_merge_rows('actor.usr_org_unit_opt_in', 'usr', src_usr, dest_usr);
82     PERFORM actor.usr_merge_rows('actor.usr_setting', 'usr', src_usr, dest_usr);
83
84     -- permission.*
85     PERFORM actor.usr_merge_rows('permission.usr_perm_map', 'usr', src_usr, dest_usr);
86     PERFORM actor.usr_merge_rows('permission.usr_object_perm_map', 'usr', src_usr, dest_usr);
87     PERFORM actor.usr_merge_rows('permission.usr_grp_map', 'usr', src_usr, dest_usr);
88     PERFORM actor.usr_merge_rows('permission.usr_work_ou_map', 'usr', src_usr, dest_usr);
89
90
91     -- container.*
92         
93         -- For each *_bucket table: transfer every bucket belonging to src_usr
94         -- into the custody of dest_usr.
95         --
96         -- In order to avoid colliding with an existing bucket owned by
97         -- the destination user, append the source user's id (in parenthesese)
98         -- to the name.  If you still get a collision, add successive
99         -- spaces to the name and keep trying until you succeed.
100         --
101         FOR bucket_row in
102                 SELECT id, name
103                 FROM   container.biblio_record_entry_bucket
104                 WHERE  owner = src_usr
105         LOOP
106                 suffix := ' (' || src_usr || ')';
107                 LOOP
108                         BEGIN
109                                 UPDATE  container.biblio_record_entry_bucket
110                                 SET     owner = dest_usr, name = name || suffix
111                                 WHERE   id = bucket_row.id;
112                         EXCEPTION WHEN unique_violation THEN
113                                 suffix := suffix || ' ';
114                                 CONTINUE;
115                         END;
116                         EXIT;
117                 END LOOP;
118         END LOOP;
119
120         FOR bucket_row in
121                 SELECT id, name
122                 FROM   container.call_number_bucket
123                 WHERE  owner = src_usr
124         LOOP
125                 suffix := ' (' || src_usr || ')';
126                 LOOP
127                         BEGIN
128                                 UPDATE  container.call_number_bucket
129                                 SET     owner = dest_usr, name = name || suffix
130                                 WHERE   id = bucket_row.id;
131                         EXCEPTION WHEN unique_violation THEN
132                                 suffix := suffix || ' ';
133                                 CONTINUE;
134                         END;
135                         EXIT;
136                 END LOOP;
137         END LOOP;
138
139         FOR bucket_row in
140                 SELECT id, name
141                 FROM   container.copy_bucket
142                 WHERE  owner = src_usr
143         LOOP
144                 suffix := ' (' || src_usr || ')';
145                 LOOP
146                         BEGIN
147                                 UPDATE  container.copy_bucket
148                                 SET     owner = dest_usr, name = name || suffix
149                                 WHERE   id = bucket_row.id;
150                         EXCEPTION WHEN unique_violation THEN
151                                 suffix := suffix || ' ';
152                                 CONTINUE;
153                         END;
154                         EXIT;
155                 END LOOP;
156         END LOOP;
157
158         FOR bucket_row in
159                 SELECT id, name
160                 FROM   container.user_bucket
161                 WHERE  owner = src_usr
162         LOOP
163                 suffix := ' (' || src_usr || ')';
164                 LOOP
165                         BEGIN
166                                 UPDATE  container.user_bucket
167                                 SET     owner = dest_usr, name = name || suffix
168                                 WHERE   id = bucket_row.id;
169                         EXCEPTION WHEN unique_violation THEN
170                                 suffix := suffix || ' ';
171                                 CONTINUE;
172                         END;
173                         EXIT;
174                 END LOOP;
175         END LOOP;
176
177         UPDATE container.user_bucket_item SET target_user = dest_usr WHERE target_user = src_usr;
178
179     -- vandelay.*
180         -- transfer queues the same way we transfer buckets (see above)
181         FOR queue_row in
182                 SELECT id, name
183                 FROM   vandelay.queue
184                 WHERE  owner = src_usr
185         LOOP
186                 suffix := ' (' || src_usr || ')';
187                 LOOP
188                         BEGIN
189                                 UPDATE  vandelay.queue
190                                 SET     owner = dest_usr, name = name || suffix
191                                 WHERE   id = queue_row.id;
192                         EXCEPTION WHEN unique_violation THEN
193                                 suffix := suffix || ' ';
194                                 CONTINUE;
195                         END;
196                         EXIT;
197                 END LOOP;
198         END LOOP;
199
200     -- money.*
201     PERFORM actor.usr_merge_rows('money.collections_tracker', 'usr', src_usr, dest_usr);
202     PERFORM actor.usr_merge_rows('money.collections_tracker', 'collector', src_usr, dest_usr);
203     UPDATE money.billable_xact SET usr = dest_usr WHERE usr = src_usr;
204     UPDATE money.billing SET voider = dest_usr WHERE voider = src_usr;
205     UPDATE money.bnm_payment SET accepting_usr = dest_usr WHERE accepting_usr = src_usr;
206
207     -- action.*
208     UPDATE action.circulation SET usr = dest_usr WHERE usr = src_usr;
209     UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
210     UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
211
212     UPDATE action.hold_request SET usr = dest_usr WHERE usr = src_usr;
213     UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
214     UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
215     UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
216
217     UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
218     UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
219     UPDATE action.non_cataloged_circulation SET patron = dest_usr WHERE patron = src_usr;
220     UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
221     UPDATE action.survey_response SET usr = dest_usr WHERE usr = src_usr;
222
223     -- acq.*
224     UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
225     UPDATE acq.fund_transfer SET transfer_user = dest_usr WHERE transfer_user = src_usr;
226
227         -- transfer picklists the same way we transfer buckets (see above)
228         FOR picklist_row in
229                 SELECT id, name
230                 FROM   acq.picklist
231                 WHERE  owner = src_usr
232         LOOP
233                 suffix := ' (' || src_usr || ')';
234                 LOOP
235                         BEGIN
236                                 UPDATE  acq.picklist
237                                 SET     owner = dest_usr, name = name || suffix
238                                 WHERE   id = picklist_row.id;
239                         EXCEPTION WHEN unique_violation THEN
240                                 suffix := suffix || ' ';
241                                 CONTINUE;
242                         END;
243                         EXIT;
244                 END LOOP;
245         END LOOP;
246
247     UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
248     UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
249     UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
250     UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
251     UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
252     UPDATE acq.lineitem_usr_attr_definition SET usr = dest_usr WHERE usr = src_usr;
253
254     -- asset.*
255     UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
256     UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
257     UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
258     UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
259     UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
260     UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
261
262     -- serial.*
263     UPDATE serial.record_entry SET creator = dest_usr WHERE creator = src_usr;
264     UPDATE serial.record_entry SET editor = dest_usr WHERE editor = src_usr;
265
266     -- reporter.*
267     -- It's not uncommon to define the reporter schema in a replica 
268     -- DB only, so don't assume these tables exist in the write DB.
269     BEGIN
270         UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
271     EXCEPTION WHEN undefined_table THEN
272         -- do nothing
273     END;
274     BEGIN
275         UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
276     EXCEPTION WHEN undefined_table THEN
277         -- do nothing
278     END;
279     BEGIN
280         UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
281     EXCEPTION WHEN undefined_table THEN
282         -- do nothing
283     END;
284     BEGIN
285                 -- transfer folders the same way we transfer buckets (see above)
286                 FOR folder_row in
287                         SELECT id, name
288                         FROM   reporter.template_folder
289                         WHERE  owner = src_usr
290                 LOOP
291                         suffix := ' (' || src_usr || ')';
292                         LOOP
293                                 BEGIN
294                                         UPDATE  reporter.template_folder
295                                         SET     owner = dest_usr, name = name || suffix
296                                         WHERE   id = folder_row.id;
297                                 EXCEPTION WHEN unique_violation THEN
298                                         suffix := suffix || ' ';
299                                         CONTINUE;
300                                 END;
301                                 EXIT;
302                         END LOOP;
303                 END LOOP;
304     EXCEPTION WHEN undefined_table THEN
305         -- do nothing
306     END;
307     BEGIN
308                 -- transfer folders the same way we transfer buckets (see above)
309                 FOR folder_row in
310                         SELECT id, name
311                         FROM   reporter.report_folder
312                         WHERE  owner = src_usr
313                 LOOP
314                         suffix := ' (' || src_usr || ')';
315                         LOOP
316                                 BEGIN
317                                         UPDATE  reporter.report_folder
318                                         SET     owner = dest_usr, name = name || suffix
319                                         WHERE   id = folder_row.id;
320                                 EXCEPTION WHEN unique_violation THEN
321                                         suffix := suffix || ' ';
322                                         CONTINUE;
323                                 END;
324                                 EXIT;
325                         END LOOP;
326                 END LOOP;
327     EXCEPTION WHEN undefined_table THEN
328         -- do nothing
329     END;
330     BEGIN
331                 -- transfer folders the same way we transfer buckets (see above)
332                 FOR folder_row in
333                         SELECT id, name
334                         FROM   reporter.output_folder
335                         WHERE  owner = src_usr
336                 LOOP
337                         suffix := ' (' || src_usr || ')';
338                         LOOP
339                                 BEGIN
340                                         UPDATE  reporter.output_folder
341                                         SET     owner = dest_usr, name = name || suffix
342                                         WHERE   id = folder_row.id;
343                                 EXCEPTION WHEN unique_violation THEN
344                                         suffix := suffix || ' ';
345                                         CONTINUE;
346                                 END;
347                                 EXIT;
348                         END LOOP;
349                 END LOOP;
350     EXCEPTION WHEN undefined_table THEN
351         -- do nothing
352     END;
353
354     -- Finally, delete the source user
355     DELETE FROM actor.usr WHERE id = src_usr;
356
357 END;
358 $$ LANGUAGE plpgsql;
359
360 COMMENT ON FUNCTION actor.usr_merge(INT, INT, BOOLEAN, BOOLEAN, BOOLEAN) IS $$
361 /**
362  * Merges all user date from src_usr to dest_usr.  When collisions occur, 
363  * keep dest_usr's data and delete src_usr's data.
364  */
365 $$;
366
367
368
369 CREATE OR REPLACE FUNCTION actor.usr_purge_data(
370         src_usr  IN INTEGER,
371         dest_usr IN INTEGER
372 ) RETURNS VOID AS $$
373 DECLARE
374         suffix TEXT;
375         renamable_row RECORD;
376 BEGIN
377
378         UPDATE actor.usr SET
379                 active = FALSE,
380                 card = NULL,
381                 mailing_address = NULL,
382                 billing_address = NULL
383         WHERE id = src_usr;
384
385         -- acq.*
386         UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
387     UPDATE acq.fund_transfer SET transfer_user = dest_usr WHERE transfer_user = src_usr;
388         UPDATE acq.lineitem SET creator = dest_usr WHERE creator = src_usr;
389         UPDATE acq.lineitem SET editor = dest_usr WHERE editor = src_usr;
390         UPDATE acq.lineitem SET selector = dest_usr WHERE selector = src_usr;
391         UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
392         UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
393         DELETE FROM acq.lineitem_usr_attr_definition WHERE usr = src_usr;
394
395         -- Update with a rename to avoid collisions
396         FOR renamable_row in
397                 SELECT id, name
398                 FROM   acq.picklist
399                 WHERE  owner = src_usr
400         LOOP
401                 suffix := ' (' || src_usr || ')';
402                 LOOP
403                         BEGIN
404                                 UPDATE  acq.picklist
405                                 SET     owner = dest_usr, name = name || suffix
406                                 WHERE   id = renamable_row.id;
407                         EXCEPTION WHEN unique_violation THEN
408                                 suffix := suffix || ' ';
409                                 CONTINUE;
410                         END;
411                         EXIT;
412                 END LOOP;
413         END LOOP;
414
415         UPDATE acq.picklist SET creator = dest_usr WHERE creator = src_usr;
416         UPDATE acq.picklist SET editor = dest_usr WHERE editor = src_usr;
417         UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
418         UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
419         UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
420         UPDATE acq.purchase_order SET creator = dest_usr WHERE creator = src_usr;
421         UPDATE acq.purchase_order SET editor = dest_usr WHERE editor = src_usr;
422
423         -- action.*
424         DELETE FROM action.circulation WHERE usr = src_usr;
425         UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
426         UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
427         UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
428         UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
429         UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
430         DELETE FROM action.hold_request WHERE usr = src_usr;
431         UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
432         UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
433         DELETE FROM action.non_cataloged_circulation WHERE patron = src_usr;
434         UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
435         DELETE FROM action.survey_response WHERE usr = src_usr;
436
437         -- actor.*
438         DELETE FROM actor.card WHERE usr = src_usr;
439         DELETE FROM actor.stat_cat_entry_usr_map WHERE target_usr = src_usr;
440
441         -- The following update is intended to avoid transient violations of a foreign
442         -- key constraint, whereby actor.usr_address references itself.  It may not be
443         -- necessary, but it does no harm.
444         UPDATE actor.usr_address SET replaces = NULL
445                 WHERE usr = src_usr AND replaces IS NOT NULL;
446         DELETE FROM actor.usr_address WHERE usr = src_usr;
447         DELETE FROM actor.usr_note WHERE usr = src_usr;
448         UPDATE actor.usr_note SET creator = dest_usr WHERE creator = src_usr;
449         DELETE FROM actor.usr_org_unit_opt_in WHERE usr = src_usr;
450         UPDATE actor.usr_org_unit_opt_in SET staff = dest_usr WHERE staff = src_usr;
451         DELETE FROM actor.usr_setting WHERE usr = src_usr;
452         DELETE FROM actor.usr_standing_penalty WHERE usr = src_usr;
453         UPDATE actor.usr_standing_penalty SET staff = dest_usr WHERE staff = src_usr;
454
455         -- asset.*
456         UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
457         UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
458         UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
459         UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
460         UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
461         UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
462
463         -- auditor.*
464         DELETE FROM auditor.actor_usr_address_history WHERE id = src_usr;
465         DELETE FROM auditor.actor_usr_history WHERE id = src_usr;
466         UPDATE auditor.asset_call_number_history SET creator = dest_usr WHERE creator = src_usr;
467         UPDATE auditor.asset_call_number_history SET editor  = dest_usr WHERE editor  = src_usr;
468         UPDATE auditor.asset_copy_history SET creator = dest_usr WHERE creator = src_usr;
469         UPDATE auditor.asset_copy_history SET editor  = dest_usr WHERE editor  = src_usr;
470         UPDATE auditor.biblio_record_entry_history SET creator = dest_usr WHERE creator = src_usr;
471         UPDATE auditor.biblio_record_entry_history SET editor  = dest_usr WHERE editor  = src_usr;
472
473         -- biblio.*
474         UPDATE biblio.record_entry SET creator = dest_usr WHERE creator = src_usr;
475         UPDATE biblio.record_entry SET editor = dest_usr WHERE editor = src_usr;
476         UPDATE biblio.record_note SET creator = dest_usr WHERE creator = src_usr;
477         UPDATE biblio.record_note SET editor = dest_usr WHERE editor = src_usr;
478
479         -- container.*
480         -- Update buckets with a rename to avoid collisions
481         FOR renamable_row in
482                 SELECT id, name
483                 FROM   container.biblio_record_entry_bucket
484                 WHERE  owner = src_usr
485         LOOP
486                 suffix := ' (' || src_usr || ')';
487                 LOOP
488                         BEGIN
489                                 UPDATE  container.biblio_record_entry_bucket
490                                 SET     owner = dest_usr, name = name || suffix
491                                 WHERE   id = renamable_row.id;
492                         EXCEPTION WHEN unique_violation THEN
493                                 suffix := suffix || ' ';
494                                 CONTINUE;
495                         END;
496                         EXIT;
497                 END LOOP;
498         END LOOP;
499
500         FOR renamable_row in
501                 SELECT id, name
502                 FROM   container.call_number_bucket
503                 WHERE  owner = src_usr
504         LOOP
505                 suffix := ' (' || src_usr || ')';
506                 LOOP
507                         BEGIN
508                                 UPDATE  container.call_number_bucket
509                                 SET     owner = dest_usr, name = name || suffix
510                                 WHERE   id = renamable_row.id;
511                         EXCEPTION WHEN unique_violation THEN
512                                 suffix := suffix || ' ';
513                                 CONTINUE;
514                         END;
515                         EXIT;
516                 END LOOP;
517         END LOOP;
518
519         FOR renamable_row in
520                 SELECT id, name
521                 FROM   container.copy_bucket
522                 WHERE  owner = src_usr
523         LOOP
524                 suffix := ' (' || src_usr || ')';
525                 LOOP
526                         BEGIN
527                                 UPDATE  container.copy_bucket
528                                 SET     owner = dest_usr, name = name || suffix
529                                 WHERE   id = renamable_row.id;
530                         EXCEPTION WHEN unique_violation THEN
531                                 suffix := suffix || ' ';
532                                 CONTINUE;
533                         END;
534                         EXIT;
535                 END LOOP;
536         END LOOP;
537
538         FOR renamable_row in
539                 SELECT id, name
540                 FROM   container.user_bucket
541                 WHERE  owner = src_usr
542         LOOP
543                 suffix := ' (' || src_usr || ')';
544                 LOOP
545                         BEGIN
546                                 UPDATE  container.user_bucket
547                                 SET     owner = dest_usr, name = name || suffix
548                                 WHERE   id = renamable_row.id;
549                         EXCEPTION WHEN unique_violation THEN
550                                 suffix := suffix || ' ';
551                                 CONTINUE;
552                         END;
553                         EXIT;
554                 END LOOP;
555         END LOOP;
556
557         DELETE FROM container.user_bucket_item WHERE target_user = src_usr;
558
559         -- money.*
560         DELETE FROM money.billable_xact WHERE usr = src_usr;
561         DELETE FROM money.collections_tracker WHERE usr = src_usr;
562         UPDATE money.collections_tracker SET collector = dest_usr WHERE collector = src_usr;
563
564         -- permission.*
565         DELETE FROM permission.usr_grp_map WHERE usr = src_usr;
566         DELETE FROM permission.usr_object_perm_map WHERE usr = src_usr;
567         DELETE FROM permission.usr_perm_map WHERE usr = src_usr;
568         DELETE FROM permission.usr_work_ou_map WHERE usr = src_usr;
569
570         -- reporter.*
571         -- Update with a rename to avoid collisions
572         BEGIN
573                 FOR renamable_row in
574                         SELECT id, name
575                         FROM   reporter.output_folder
576                         WHERE  owner = src_usr
577                 LOOP
578                         suffix := ' (' || src_usr || ')';
579                         LOOP
580                                 BEGIN
581                                         UPDATE  reporter.output_folder
582                                         SET     owner = dest_usr, name = name || suffix
583                                         WHERE   id = renamable_row.id;
584                                 EXCEPTION WHEN unique_violation THEN
585                                         suffix := suffix || ' ';
586                                         CONTINUE;
587                                 END;
588                                 EXIT;
589                         END LOOP;
590                 END LOOP;
591         EXCEPTION WHEN undefined_table THEN
592                 -- do nothing
593         END;
594
595         BEGIN
596                 UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
597         EXCEPTION WHEN undefined_table THEN
598                 -- do nothing
599         END;
600
601         -- Update with a rename to avoid collisions
602         BEGIN
603                 FOR renamable_row in
604                         SELECT id, name
605                         FROM   reporter.report_folder
606                         WHERE  owner = src_usr
607                 LOOP
608                         suffix := ' (' || src_usr || ')';
609                         LOOP
610                                 BEGIN
611                                         UPDATE  reporter.report_folder
612                                         SET     owner = dest_usr, name = name || suffix
613                                         WHERE   id = renamable_row.id;
614                                 EXCEPTION WHEN unique_violation THEN
615                                         suffix := suffix || ' ';
616                                         CONTINUE;
617                                 END;
618                                 EXIT;
619                         END LOOP;
620                 END LOOP;
621         EXCEPTION WHEN undefined_table THEN
622                 -- do nothing
623         END;
624
625         BEGIN
626                 UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
627         EXCEPTION WHEN undefined_table THEN
628                 -- do nothing
629         END;
630
631         BEGIN
632                 UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
633         EXCEPTION WHEN undefined_table THEN
634                 -- do nothing
635         END;
636
637         -- Update with a rename to avoid collisions
638         BEGIN
639                 FOR renamable_row in
640                         SELECT id, name
641                         FROM   reporter.template_folder
642                         WHERE  owner = src_usr
643                 LOOP
644                         suffix := ' (' || src_usr || ')';
645                         LOOP
646                                 BEGIN
647                                         UPDATE  reporter.template_folder
648                                         SET     owner = dest_usr, name = name || suffix
649                                         WHERE   id = renamable_row.id;
650                                 EXCEPTION WHEN unique_violation THEN
651                                         suffix := suffix || ' ';
652                                         CONTINUE;
653                                 END;
654                                 EXIT;
655                         END LOOP;
656                 END LOOP;
657         EXCEPTION WHEN undefined_table THEN
658         -- do nothing
659         END;
660
661         -- vandelay.*
662         -- Update with a rename to avoid collisions
663         FOR renamable_row in
664                 SELECT id, name
665                 FROM   vandelay.queue
666                 WHERE  owner = src_usr
667         LOOP
668                 suffix := ' (' || src_usr || ')';
669                 LOOP
670                         BEGIN
671                                 UPDATE  vandelay.queue
672                                 SET     owner = dest_usr, name = name || suffix
673                                 WHERE   id = renamable_row.id;
674                         EXCEPTION WHEN unique_violation THEN
675                                 suffix := suffix || ' ';
676                                 CONTINUE;
677                         END;
678                         EXIT;
679                 END LOOP;
680         END LOOP;
681
682 END;
683 $$ LANGUAGE plpgsql;
684
685 COMMENT ON FUNCTION actor.usr_purge_data(INT, INT) IS $$
686 /**
687  * Finds rows dependent on a given row in actor.usr and either deletes them
688  * or reassigns them to a different user.
689  */
690 $$;
691
692
693
694 CREATE OR REPLACE FUNCTION actor.usr_delete(
695         src_usr  IN INTEGER,
696         dest_usr IN INTEGER
697 ) RETURNS VOID AS $$
698 DECLARE
699         old_profile actor.usr.profile%type;
700         old_home_ou actor.usr.home_ou%type;
701         new_profile actor.usr.profile%type;
702         new_home_ou actor.usr.home_ou%type;
703         new_name    text;
704         new_dob     actor.usr.dob%type;
705 BEGIN
706         SELECT
707                 id || '-PURGED-' || now(),
708                 profile,
709                 home_ou,
710                 dob
711         INTO
712                 new_name,
713                 old_profile,
714                 old_home_ou,
715                 new_dob
716         FROM
717                 actor.usr
718         WHERE
719                 id = src_usr;
720         --
721         -- Quit if no such user
722         --
723         IF old_profile IS NULL THEN
724                 RETURN;
725         END IF;
726         --
727         perform actor.usr_purge_data( src_usr, dest_usr );
728         --
729         -- Find the root grp_tree and the root org_unit.  This would be simpler if we 
730         -- could assume that there is only one root.  Theoretically, someday, maybe,
731         -- there could be multiple roots, so we take extra trouble to get the right ones.
732         --
733         SELECT
734                 id
735         INTO
736                 new_profile
737         FROM
738                 permission.grp_ancestors( old_profile )
739         WHERE
740                 parent is null;
741         --
742         SELECT
743                 id
744         INTO
745                 new_home_ou
746         FROM
747                 actor.org_unit_ancestors( old_home_ou )
748         WHERE
749                 parent_ou is null;
750         --
751         -- Truncate date of birth
752         --
753         IF new_dob IS NOT NULL THEN
754                 new_dob := date_trunc( 'year', new_dob );
755         END IF;
756         --
757         UPDATE
758                 actor.usr
759                 SET
760                         card = NULL,
761                         profile = new_profile,
762                         usrname = new_name,
763                         email = NULL,
764                         passwd = random()::text,
765                         standing = DEFAULT,
766                         ident_type = 
767                         (
768                                 SELECT MIN( id )
769                                 FROM config.identification_type
770                         ),
771                         ident_value = NULL,
772                         ident_type2 = NULL,
773                         ident_value2 = NULL,
774                         net_access_level = DEFAULT,
775                         photo_url = NULL,
776                         prefix = NULL,
777                         first_given_name = new_name,
778                         second_given_name = NULL,
779                         family_name = new_name,
780                         suffix = NULL,
781                         alias = NULL,
782                         day_phone = NULL,
783                         evening_phone = NULL,
784                         other_phone = NULL,
785                         mailing_address = NULL,
786                         billing_address = NULL,
787                         home_ou = new_home_ou,
788                         dob = new_dob,
789                         active = FALSE,
790                         master_account = DEFAULT, 
791                         super_user = DEFAULT,
792                         barred = FALSE,
793                         deleted = TRUE,
794                         juvenile = DEFAULT,
795                         usrgroup = 0,
796                         claims_returned_count = DEFAULT,
797                         credit_forward_balance = DEFAULT,
798                         last_xact_id = DEFAULT,
799                         alert_message = NULL,
800                         create_date = now(),
801                         expire_date = now()
802         WHERE
803                 id = src_usr;
804 END;
805 $$ LANGUAGE plpgsql;
806
807 COMMENT ON FUNCTION actor.usr_delete(INT, INT) IS $$
808 /**
809  * Logically deletes a user.  Removes personally identifiable information,
810  * and purges associated data in other tables.
811  */
812 $$;
813
814
815
816 CREATE OR REPLACE FUNCTION actor.approve_pending_address(pending_id INT) RETURNS BIGINT AS $$
817 DECLARE
818     old_id INT;
819 BEGIN
820     SELECT INTO old_id replaces FROM actor.usr_address where id = pending_id;
821     IF old_id IS NULL THEN
822         UPDATE actor.usr_address SET pending = 'f' WHERE id = pending_id;
823         RETURN pending_id;
824     END IF;
825     -- address replaces an existing address
826     DELETE FROM actor.usr_address WHERE id = -old_id;
827     UPDATE actor.usr_address SET id = -id WHERE id = old_id;
828     UPDATE actor.usr_address SET replaces = NULL, id = old_id, pending = 'f' WHERE id = pending_id;
829     RETURN old_id;
830 END
831 $$ LANGUAGE plpgsql;
832
833 COMMENT ON FUNCTION actor.approve_pending_address(INT) IS $$
834 /**
835  * Replaces an address with a pending address.  This is done by giving the pending 
836  * address the ID of the old address.  The replaced address is retained with -id.
837  */
838 $$;
839
840 CREATE OR REPLACE FUNCTION container.clear_expired_circ_history_items( 
841          ac_usr IN INTEGER
842 ) RETURNS VOID AS $$
843 --
844 -- Delete old circulation bucket items for a specified user.
845 -- "Old" means older than the interval specified by a
846 -- user-level setting, if it is so specified.
847 --
848 DECLARE
849     threshold TIMESTAMP WITH TIME ZONE;
850 BEGIN
851         -- Sanity check
852         IF ac_usr IS NULL THEN
853                 RETURN;
854         END IF;
855         -- Determine the threshold date that defines "old".  Subtract the
856         -- interval from the system date, then truncate to midnight.
857         SELECT
858                 date_trunc( 
859                         'day',
860                         now() - CAST( translate( value, '"', '' ) AS INTERVAL )
861                 )
862         INTO
863                 threshold
864         FROM
865                 actor.usr_setting
866         WHERE
867                 usr = ac_usr
868                 AND name = 'patron.max_reading_list_interval';
869         --
870         IF threshold is null THEN
871                 -- No interval defined; don't delete anything
872                 -- RAISE NOTICE 'No interval defined for user %', ac_usr;
873                 return;
874         END IF;
875         --
876         -- RAISE NOTICE 'Date threshold: %', threshold;
877         --
878         -- Threshold found; do the delete
879         delete from container.copy_bucket_item
880         where
881                 bucket in
882                 (
883                         select
884                                 id
885                         from
886                                 container.copy_bucket
887                         where
888                                 owner = ac_usr
889                                 and btype = 'circ_history'
890                 )
891                 and create_time < threshold;
892         --
893         RETURN;
894 END;
895 $$ LANGUAGE plpgsql;
896
897 COMMENT ON FUNCTION container.clear_expired_circ_history_items( INTEGER ) IS $$
898 /*
899  * Delete old circulation bucket items for a specified user.
900  * "Old" means older than the interval specified by a
901  * user-level setting, if it is so specified.
902 */
903 $$;
904
905 CREATE OR REPLACE FUNCTION container.clear_all_expired_circ_history_items( )
906 RETURNS VOID AS $$
907 --
908 -- Delete expired circulation bucket items for all users that have
909 -- a setting for patron.max_reading_list_interval.
910 --
911 DECLARE
912     today        TIMESTAMP WITH TIME ZONE;
913     threshold    TIMESTAMP WITH TIME ZONE;
914         usr_setting  RECORD;
915 BEGIN
916         SELECT date_trunc( 'day', now() ) INTO today;
917         --
918         FOR usr_setting in
919                 SELECT
920                         usr,
921                         value
922                 FROM
923                         actor.usr_setting
924                 WHERE
925                         name = 'patron.max_reading_list_interval'
926         LOOP
927                 --
928                 -- Make sure the setting is a valid interval
929                 --
930                 BEGIN
931                         threshold := today - CAST( translate( usr_setting.value, '"', '' ) AS INTERVAL );
932                 EXCEPTION
933                         WHEN OTHERS THEN
934                                 RAISE NOTICE 'Invalid setting patron.max_reading_list_interval for user %: ''%''',
935                                         usr_setting.usr, usr_setting.value;
936                                 CONTINUE;
937                 END;
938                 --
939                 --RAISE NOTICE 'User % threshold %', usr_setting.usr, threshold;
940                 --
941         DELETE FROM container.copy_bucket_item
942         WHERE
943                 bucket IN
944                 (
945                     SELECT
946                         id
947                     FROM
948                         container.copy_bucket
949                     WHERE
950                         owner = usr_setting.usr
951                         AND btype = 'circ_history'
952                 )
953                 AND create_time < threshold;
954         END LOOP;
955         --
956 END;
957 $$ LANGUAGE plpgsql;
958
959 COMMENT ON FUNCTION container.clear_all_expired_circ_history_items( ) IS $$
960 /*
961  * Delete expired circulation bucket items for all users that have
962  * a setting for patron.max_reading_list_interval.
963 */
964 $$;
965
966
967 CREATE OR REPLACE FUNCTION asset.merge_record_assets( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
968 DECLARE
969         moved_objects INT := 0;
970         source_cn     asset.call_number%ROWTYPE;
971         target_cn     asset.call_number%ROWTYPE;
972         metarec       metabib.metarecord%ROWTYPE;
973         hold          action.hold_request%ROWTYPE;
974         ser_rec       serial.record_entry%ROWTYPE;
975     uri_count     INT := 0;
976     counter       INT := 0;
977     uri_datafield TEXT;
978     uri_text      TEXT := '';
979 BEGIN
980
981     -- move any 856 entries on records that have at least one MARC-mapped URI entry
982     SELECT  INTO uri_count COUNT(*)
983       FROM  asset.uri_call_number_map m
984             JOIN asset.call_number cn ON (m.call_number = cn.id)
985       WHERE cn.record = source_record;
986
987     IF uri_count > 0 THEN
988         
989         SELECT  COUNT(*) INTO counter
990           FROM  xpath_table(
991                     'id',
992                     'marc',
993                     'acq.lineitem',
994                     '//*[@tag="856"]',
995                     'id=' || lineitem
996                 ) as t(i int,c text);
997     
998         FOR i IN 1 .. counter LOOP
999             SELECT  '<datafield xmlns="http://www.loc.gov/MARC21/slim" tag="856">' ||
1000                         array_to_string(
1001                             array_accum(
1002                                 '<subfield code="' || subfield || '">' ||
1003                                 regexp_replace(
1004                                     regexp_replace(
1005                                         regexp_replace(data,'&','&amp;','g'),
1006                                         '>', '&gt;', 'g'
1007                                     ),
1008                                     '<', '&lt;', 'g'
1009                                 ) || '</subfield>'
1010                             ), ''
1011                         ) || '</datafield>' INTO uri_datafield
1012               FROM  xpath_table(
1013                         'id',
1014                         'marc',
1015                         'biblio.record_entry',
1016                         '//*[@tag="856"][position()=' || i || ']/*/@code|' ||
1017                         '//*[@tag="856"][position()=' || i || ']/*[@code]',
1018                         'id=' || source_record
1019                     ) as t(id int,subfield text,data text);
1020
1021             uri_text := uri_text || uri_datafield;
1022         END LOOP;
1023
1024         IF uri_text <> '' THEN
1025             UPDATE  biblio.record_entry
1026               SET   marc = regexp_replace(marc,'(</[^>]*record>)', uri_text || E'\\1')
1027               WHERE id = target_record;
1028         END IF;
1029
1030     END IF;
1031
1032         -- Find and move metarecords to the target record
1033         SELECT  INTO metarec *
1034           FROM  metabib.metarecord
1035           WHERE master_record = source_record;
1036
1037         IF FOUND THEN
1038                 UPDATE  metabib.metarecord
1039                   SET   master_record = target_record,
1040                         mods = NULL
1041                   WHERE id = metarec.id;
1042
1043                 moved_objects := moved_objects + 1;
1044         END IF;
1045
1046         -- Find call numbers attached to the source ...
1047         FOR source_cn IN SELECT * FROM asset.call_number WHERE record = source_record LOOP
1048
1049                 SELECT  INTO target_cn *
1050                   FROM  asset.call_number
1051                   WHERE label = source_cn.label
1052                         AND owning_lib = source_cn.owning_lib
1053                         AND record = target_record;
1054
1055                 -- ... and if there's a conflicting one on the target ...
1056                 IF FOUND THEN
1057
1058                         -- ... move the copies to that, and ...
1059                         UPDATE  asset.copy
1060                           SET   call_number = target_cn.id
1061                           WHERE call_number = source_cn.id;
1062
1063                         -- ... move V holds to the move-target call number
1064                         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_cn.id AND hold_type = 'V' LOOP
1065                 
1066                                 UPDATE  action.hold_request
1067                                   SET   target = target_cn.id
1068                                   WHERE id = hold.id;
1069                 
1070                                 moved_objects := moved_objects + 1;
1071                         END LOOP;
1072
1073                 -- ... if not ...
1074                 ELSE
1075                         -- ... just move the call number to the target record
1076                         UPDATE  asset.call_number
1077                           SET   record = target_record
1078                           WHERE id = source_cn.id;
1079                 END IF;
1080
1081                 moved_objects := moved_objects + 1;
1082         END LOOP;
1083
1084         -- Find T holds targeting the source record ...
1085         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_record AND hold_type = 'T' LOOP
1086
1087                 -- ... and move them to the target record
1088                 UPDATE  action.hold_request
1089                   SET   target = target_record
1090                   WHERE id = hold.id;
1091
1092                 moved_objects := moved_objects + 1;
1093         END LOOP;
1094
1095         -- Find serial records targeting the source record ...
1096         FOR ser_rec IN SELECT * FROM serial.record_entry WHERE record = source_record LOOP
1097                 -- ... and move them to the target record
1098                 UPDATE  serial.record_entry
1099                   SET   record = target_record
1100                   WHERE id = ser_rec.id;
1101
1102                 moved_objects := moved_objects + 1;
1103         END LOOP;
1104
1105     -- Finally, "delete" the source record
1106     DELETE FROM biblio.record_entry WHERE id = source_record;
1107
1108         -- That's all, folks!
1109         RETURN moved_objects;
1110 END;
1111 $func$ LANGUAGE plpgsql;
1112