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