]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/999.functions.global.sql
4850d6c2c51b99e6793835d8d25c6714395e4bcc
[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.provider_note SET creator = dest_usr WHERE creator = src_usr;
251     UPDATE acq.provider_note SET editor = dest_usr WHERE editor = src_usr;
252     UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
253     UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
254     UPDATE acq.lineitem_usr_attr_definition SET usr = dest_usr WHERE usr = src_usr;
255
256     -- asset.*
257     UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
258     UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
259     UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
260     UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
261     UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
262     UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
263
264     -- serial.*
265     UPDATE serial.record_entry SET creator = dest_usr WHERE creator = src_usr;
266     UPDATE serial.record_entry SET editor = dest_usr WHERE editor = src_usr;
267
268     -- reporter.*
269     -- It's not uncommon to define the reporter schema in a replica 
270     -- DB only, so don't assume these tables exist in the write DB.
271     BEGIN
272         UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
273     EXCEPTION WHEN undefined_table THEN
274         -- do nothing
275     END;
276     BEGIN
277         UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
278     EXCEPTION WHEN undefined_table THEN
279         -- do nothing
280     END;
281     BEGIN
282         UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
283     EXCEPTION WHEN undefined_table THEN
284         -- do nothing
285     END;
286     BEGIN
287                 -- transfer folders the same way we transfer buckets (see above)
288                 FOR folder_row in
289                         SELECT id, name
290                         FROM   reporter.template_folder
291                         WHERE  owner = src_usr
292                 LOOP
293                         suffix := ' (' || src_usr || ')';
294                         LOOP
295                                 BEGIN
296                                         UPDATE  reporter.template_folder
297                                         SET     owner = dest_usr, name = name || suffix
298                                         WHERE   id = folder_row.id;
299                                 EXCEPTION WHEN unique_violation THEN
300                                         suffix := suffix || ' ';
301                                         CONTINUE;
302                                 END;
303                                 EXIT;
304                         END LOOP;
305                 END LOOP;
306     EXCEPTION WHEN undefined_table THEN
307         -- do nothing
308     END;
309     BEGIN
310                 -- transfer folders the same way we transfer buckets (see above)
311                 FOR folder_row in
312                         SELECT id, name
313                         FROM   reporter.report_folder
314                         WHERE  owner = src_usr
315                 LOOP
316                         suffix := ' (' || src_usr || ')';
317                         LOOP
318                                 BEGIN
319                                         UPDATE  reporter.report_folder
320                                         SET     owner = dest_usr, name = name || suffix
321                                         WHERE   id = folder_row.id;
322                                 EXCEPTION WHEN unique_violation THEN
323                                         suffix := suffix || ' ';
324                                         CONTINUE;
325                                 END;
326                                 EXIT;
327                         END LOOP;
328                 END LOOP;
329     EXCEPTION WHEN undefined_table THEN
330         -- do nothing
331     END;
332     BEGIN
333                 -- transfer folders the same way we transfer buckets (see above)
334                 FOR folder_row in
335                         SELECT id, name
336                         FROM   reporter.output_folder
337                         WHERE  owner = src_usr
338                 LOOP
339                         suffix := ' (' || src_usr || ')';
340                         LOOP
341                                 BEGIN
342                                         UPDATE  reporter.output_folder
343                                         SET     owner = dest_usr, name = name || suffix
344                                         WHERE   id = folder_row.id;
345                                 EXCEPTION WHEN unique_violation THEN
346                                         suffix := suffix || ' ';
347                                         CONTINUE;
348                                 END;
349                                 EXIT;
350                         END LOOP;
351                 END LOOP;
352     EXCEPTION WHEN undefined_table THEN
353         -- do nothing
354     END;
355
356     -- Finally, delete the source user
357     DELETE FROM actor.usr WHERE id = src_usr;
358
359 END;
360 $$ LANGUAGE plpgsql;
361
362 COMMENT ON FUNCTION actor.usr_merge(INT, INT, BOOLEAN, BOOLEAN, BOOLEAN) IS $$
363 /**
364  * Merges all user date from src_usr to dest_usr.  When collisions occur, 
365  * keep dest_usr's data and delete src_usr's data.
366  */
367 $$;
368
369
370 CREATE OR REPLACE FUNCTION actor.usr_purge_data(
371         src_usr  IN INTEGER,
372         dest_usr IN INTEGER
373 ) RETURNS VOID AS $$
374 DECLARE
375         suffix TEXT;
376         renamable_row RECORD;
377 BEGIN
378
379         UPDATE actor.usr SET
380                 active = FALSE,
381                 card = NULL,
382                 mailing_address = NULL,
383                 billing_address = NULL
384         WHERE id = src_usr;
385
386         -- acq.*
387         UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = 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         UPDATE acq.claim_event SET creator = dest_usr WHERE creator = src_usr;
423
424         -- action.*
425         DELETE FROM action.circulation WHERE usr = src_usr;
426         UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
427         UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
428         UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
429         UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
430         UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
431         DELETE FROM action.hold_request WHERE usr = src_usr;
432         UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
433         UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
434         DELETE FROM action.non_cataloged_circulation WHERE patron = src_usr;
435         UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
436         DELETE FROM action.survey_response WHERE usr = src_usr;
437         UPDATE action.fieldset SET owner = dest_usr WHERE owner = src_usr;
438
439         -- actor.*
440         DELETE FROM actor.card WHERE usr = src_usr;
441         DELETE FROM actor.stat_cat_entry_usr_map WHERE target_usr = src_usr;
442
443         -- The following update is intended to avoid transient violations of a foreign
444         -- key constraint, whereby actor.usr_address references itself.  It may not be
445         -- necessary, but it does no harm.
446         UPDATE actor.usr_address SET replaces = NULL
447                 WHERE usr = src_usr AND replaces IS NOT NULL;
448         DELETE FROM actor.usr_address WHERE usr = src_usr;
449         DELETE FROM actor.usr_note WHERE usr = src_usr;
450         UPDATE actor.usr_note SET creator = dest_usr WHERE creator = src_usr;
451         DELETE FROM actor.usr_org_unit_opt_in WHERE usr = src_usr;
452         UPDATE actor.usr_org_unit_opt_in SET staff = dest_usr WHERE staff = src_usr;
453         DELETE FROM actor.usr_setting WHERE usr = src_usr;
454         DELETE FROM actor.usr_standing_penalty WHERE usr = src_usr;
455         UPDATE actor.usr_standing_penalty SET staff = dest_usr WHERE staff = src_usr;
456
457         -- asset.*
458         UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
459         UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
460         UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
461         UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
462         UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
463         UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
464
465         -- auditor.*
466         DELETE FROM auditor.actor_usr_address_history WHERE id = src_usr;
467         DELETE FROM auditor.actor_usr_history WHERE id = src_usr;
468         UPDATE auditor.asset_call_number_history SET creator = dest_usr WHERE creator = src_usr;
469         UPDATE auditor.asset_call_number_history SET editor  = dest_usr WHERE editor  = src_usr;
470         UPDATE auditor.asset_copy_history SET creator = dest_usr WHERE creator = src_usr;
471         UPDATE auditor.asset_copy_history SET editor  = dest_usr WHERE editor  = src_usr;
472         UPDATE auditor.biblio_record_entry_history SET creator = dest_usr WHERE creator = src_usr;
473         UPDATE auditor.biblio_record_entry_history SET editor  = dest_usr WHERE editor  = src_usr;
474
475         -- biblio.*
476         UPDATE biblio.record_entry SET creator = dest_usr WHERE creator = src_usr;
477         UPDATE biblio.record_entry SET editor = dest_usr WHERE editor = src_usr;
478         UPDATE biblio.record_note SET creator = dest_usr WHERE creator = src_usr;
479         UPDATE biblio.record_note SET editor = dest_usr WHERE editor = src_usr;
480
481         -- container.*
482         -- Update buckets with a rename to avoid collisions
483         FOR renamable_row in
484                 SELECT id, name
485                 FROM   container.biblio_record_entry_bucket
486                 WHERE  owner = src_usr
487         LOOP
488                 suffix := ' (' || src_usr || ')';
489                 LOOP
490                         BEGIN
491                                 UPDATE  container.biblio_record_entry_bucket
492                                 SET     owner = dest_usr, name = name || suffix
493                                 WHERE   id = renamable_row.id;
494                         EXCEPTION WHEN unique_violation THEN
495                                 suffix := suffix || ' ';
496                                 CONTINUE;
497                         END;
498                         EXIT;
499                 END LOOP;
500         END LOOP;
501
502         FOR renamable_row in
503                 SELECT id, name
504                 FROM   container.call_number_bucket
505                 WHERE  owner = src_usr
506         LOOP
507                 suffix := ' (' || src_usr || ')';
508                 LOOP
509                         BEGIN
510                                 UPDATE  container.call_number_bucket
511                                 SET     owner = dest_usr, name = name || suffix
512                                 WHERE   id = renamable_row.id;
513                         EXCEPTION WHEN unique_violation THEN
514                                 suffix := suffix || ' ';
515                                 CONTINUE;
516                         END;
517                         EXIT;
518                 END LOOP;
519         END LOOP;
520
521         FOR renamable_row in
522                 SELECT id, name
523                 FROM   container.copy_bucket
524                 WHERE  owner = src_usr
525         LOOP
526                 suffix := ' (' || src_usr || ')';
527                 LOOP
528                         BEGIN
529                                 UPDATE  container.copy_bucket
530                                 SET     owner = dest_usr, name = name || suffix
531                                 WHERE   id = renamable_row.id;
532                         EXCEPTION WHEN unique_violation THEN
533                                 suffix := suffix || ' ';
534                                 CONTINUE;
535                         END;
536                         EXIT;
537                 END LOOP;
538         END LOOP;
539
540         FOR renamable_row in
541                 SELECT id, name
542                 FROM   container.user_bucket
543                 WHERE  owner = src_usr
544         LOOP
545                 suffix := ' (' || src_usr || ')';
546                 LOOP
547                         BEGIN
548                                 UPDATE  container.user_bucket
549                                 SET     owner = dest_usr, name = name || suffix
550                                 WHERE   id = renamable_row.id;
551                         EXCEPTION WHEN unique_violation THEN
552                                 suffix := suffix || ' ';
553                                 CONTINUE;
554                         END;
555                         EXIT;
556                 END LOOP;
557         END LOOP;
558
559         DELETE FROM container.user_bucket_item WHERE target_user = src_usr;
560
561         -- money.*
562         DELETE FROM money.billable_xact WHERE usr = src_usr;
563         DELETE FROM money.collections_tracker WHERE usr = src_usr;
564         UPDATE money.collections_tracker SET collector = dest_usr WHERE collector = src_usr;
565
566         -- permission.*
567         DELETE FROM permission.usr_grp_map WHERE usr = src_usr;
568         DELETE FROM permission.usr_object_perm_map WHERE usr = src_usr;
569         DELETE FROM permission.usr_perm_map WHERE usr = src_usr;
570         DELETE FROM permission.usr_work_ou_map WHERE usr = src_usr;
571
572         -- reporter.*
573         -- Update with a rename to avoid collisions
574         BEGIN
575                 FOR renamable_row in
576                         SELECT id, name
577                         FROM   reporter.output_folder
578                         WHERE  owner = src_usr
579                 LOOP
580                         suffix := ' (' || src_usr || ')';
581                         LOOP
582                                 BEGIN
583                                         UPDATE  reporter.output_folder
584                                         SET     owner = dest_usr, name = name || suffix
585                                         WHERE   id = renamable_row.id;
586                                 EXCEPTION WHEN unique_violation THEN
587                                         suffix := suffix || ' ';
588                                         CONTINUE;
589                                 END;
590                                 EXIT;
591                         END LOOP;
592                 END LOOP;
593         EXCEPTION WHEN undefined_table THEN
594                 -- do nothing
595         END;
596
597         BEGIN
598                 UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
599         EXCEPTION WHEN undefined_table THEN
600                 -- do nothing
601         END;
602
603         -- Update with a rename to avoid collisions
604         BEGIN
605                 FOR renamable_row in
606                         SELECT id, name
607                         FROM   reporter.report_folder
608                         WHERE  owner = src_usr
609                 LOOP
610                         suffix := ' (' || src_usr || ')';
611                         LOOP
612                                 BEGIN
613                                         UPDATE  reporter.report_folder
614                                         SET     owner = dest_usr, name = name || suffix
615                                         WHERE   id = renamable_row.id;
616                                 EXCEPTION WHEN unique_violation THEN
617                                         suffix := suffix || ' ';
618                                         CONTINUE;
619                                 END;
620                                 EXIT;
621                         END LOOP;
622                 END LOOP;
623         EXCEPTION WHEN undefined_table THEN
624                 -- do nothing
625         END;
626
627         BEGIN
628                 UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
629         EXCEPTION WHEN undefined_table THEN
630                 -- do nothing
631         END;
632
633         BEGIN
634                 UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
635         EXCEPTION WHEN undefined_table THEN
636                 -- do nothing
637         END;
638
639         -- Update with a rename to avoid collisions
640         BEGIN
641                 FOR renamable_row in
642                         SELECT id, name
643                         FROM   reporter.template_folder
644                         WHERE  owner = src_usr
645                 LOOP
646                         suffix := ' (' || src_usr || ')';
647                         LOOP
648                                 BEGIN
649                                         UPDATE  reporter.template_folder
650                                         SET     owner = dest_usr, name = name || suffix
651                                         WHERE   id = renamable_row.id;
652                                 EXCEPTION WHEN unique_violation THEN
653                                         suffix := suffix || ' ';
654                                         CONTINUE;
655                                 END;
656                                 EXIT;
657                         END LOOP;
658                 END LOOP;
659         EXCEPTION WHEN undefined_table THEN
660         -- do nothing
661         END;
662
663         -- vandelay.*
664         -- Update with a rename to avoid collisions
665         FOR renamable_row in
666                 SELECT id, name
667                 FROM   vandelay.queue
668                 WHERE  owner = src_usr
669         LOOP
670                 suffix := ' (' || src_usr || ')';
671                 LOOP
672                         BEGIN
673                                 UPDATE  vandelay.queue
674                                 SET     owner = dest_usr, name = name || suffix
675                                 WHERE   id = renamable_row.id;
676                         EXCEPTION WHEN unique_violation THEN
677                                 suffix := suffix || ' ';
678                                 CONTINUE;
679                         END;
680                         EXIT;
681                 END LOOP;
682         END LOOP;
683
684 END;
685 $$ LANGUAGE plpgsql;
686
687 COMMENT ON FUNCTION actor.usr_purge_data(INT, INT) IS $$
688 /**
689  * Finds rows dependent on a given row in actor.usr and either deletes them
690  * or reassigns them to a different user.
691  */
692 $$;
693
694
695
696 CREATE OR REPLACE FUNCTION actor.usr_delete(
697         src_usr  IN INTEGER,
698         dest_usr IN INTEGER
699 ) RETURNS VOID AS $$
700 DECLARE
701         old_profile actor.usr.profile%type;
702         old_home_ou actor.usr.home_ou%type;
703         new_profile actor.usr.profile%type;
704         new_home_ou actor.usr.home_ou%type;
705         new_name    text;
706         new_dob     actor.usr.dob%type;
707 BEGIN
708         SELECT
709                 id || '-PURGED-' || now(),
710                 profile,
711                 home_ou,
712                 dob
713         INTO
714                 new_name,
715                 old_profile,
716                 old_home_ou,
717                 new_dob
718         FROM
719                 actor.usr
720         WHERE
721                 id = src_usr;
722         --
723         -- Quit if no such user
724         --
725         IF old_profile IS NULL THEN
726                 RETURN;
727         END IF;
728         --
729         perform actor.usr_purge_data( src_usr, dest_usr );
730         --
731         -- Find the root grp_tree and the root org_unit.  This would be simpler if we 
732         -- could assume that there is only one root.  Theoretically, someday, maybe,
733         -- there could be multiple roots, so we take extra trouble to get the right ones.
734         --
735         SELECT
736                 id
737         INTO
738                 new_profile
739         FROM
740                 permission.grp_ancestors( old_profile )
741         WHERE
742                 parent is null;
743         --
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         --
753         -- Truncate date of birth
754         --
755         IF new_dob IS NOT NULL THEN
756                 new_dob := date_trunc( 'year', new_dob );
757         END IF;
758         --
759         UPDATE
760                 actor.usr
761                 SET
762                         card = NULL,
763                         profile = new_profile,
764                         usrname = new_name,
765                         email = NULL,
766                         passwd = random()::text,
767                         standing = DEFAULT,
768                         ident_type = 
769                         (
770                                 SELECT MIN( id )
771                                 FROM config.identification_type
772                         ),
773                         ident_value = NULL,
774                         ident_type2 = NULL,
775                         ident_value2 = NULL,
776                         net_access_level = DEFAULT,
777                         photo_url = NULL,
778                         prefix = NULL,
779                         first_given_name = new_name,
780                         second_given_name = NULL,
781                         family_name = new_name,
782                         suffix = NULL,
783                         alias = NULL,
784                         day_phone = NULL,
785                         evening_phone = NULL,
786                         other_phone = NULL,
787                         mailing_address = NULL,
788                         billing_address = NULL,
789                         home_ou = new_home_ou,
790                         dob = new_dob,
791                         active = FALSE,
792                         master_account = DEFAULT, 
793                         super_user = DEFAULT,
794                         barred = FALSE,
795                         deleted = TRUE,
796                         juvenile = DEFAULT,
797                         usrgroup = 0,
798                         claims_returned_count = DEFAULT,
799                         credit_forward_balance = DEFAULT,
800                         last_xact_id = DEFAULT,
801                         alert_message = NULL,
802                         create_date = now(),
803                         expire_date = now()
804         WHERE
805                 id = src_usr;
806 END;
807 $$ LANGUAGE plpgsql;
808
809 COMMENT ON FUNCTION actor.usr_delete(INT, INT) IS $$
810 /**
811  * Logically deletes a user.  Removes personally identifiable information,
812  * and purges associated data in other tables.
813  */
814 $$;
815
816
817
818 CREATE OR REPLACE FUNCTION actor.approve_pending_address(pending_id INT) RETURNS BIGINT AS $$
819 DECLARE
820     old_id INT;
821 BEGIN
822     SELECT INTO old_id replaces FROM actor.usr_address where id = pending_id;
823     IF old_id IS NULL THEN
824         UPDATE actor.usr_address SET pending = 'f' WHERE id = pending_id;
825         RETURN pending_id;
826     END IF;
827     -- address replaces an existing address
828     DELETE FROM actor.usr_address WHERE id = -old_id;
829     UPDATE actor.usr_address SET id = -id WHERE id = old_id;
830     UPDATE actor.usr_address SET replaces = NULL, id = old_id, pending = 'f' WHERE id = pending_id;
831     RETURN old_id;
832 END
833 $$ LANGUAGE plpgsql;
834
835 COMMENT ON FUNCTION actor.approve_pending_address(INT) IS $$
836 /**
837  * Replaces an address with a pending address.  This is done by giving the pending 
838  * address the ID of the old address.  The replaced address is retained with -id.
839  */
840 $$;
841
842 CREATE OR REPLACE FUNCTION container.clear_expired_circ_history_items( 
843          ac_usr IN INTEGER
844 ) RETURNS VOID AS $$
845 --
846 -- Delete old circulation bucket items for a specified user.
847 -- "Old" means older than the interval specified by a
848 -- user-level setting, if it is so specified.
849 --
850 DECLARE
851     threshold TIMESTAMP WITH TIME ZONE;
852 BEGIN
853         -- Sanity check
854         IF ac_usr IS NULL THEN
855                 RETURN;
856         END IF;
857         -- Determine the threshold date that defines "old".  Subtract the
858         -- interval from the system date, then truncate to midnight.
859         SELECT
860                 date_trunc( 
861                         'day',
862                         now() - CAST( translate( value, '"', '' ) AS INTERVAL )
863                 )
864         INTO
865                 threshold
866         FROM
867                 actor.usr_setting
868         WHERE
869                 usr = ac_usr
870                 AND name = 'patron.max_reading_list_interval';
871         --
872         IF threshold is null THEN
873                 -- No interval defined; don't delete anything
874                 -- RAISE NOTICE 'No interval defined for user %', ac_usr;
875                 return;
876         END IF;
877         --
878         -- RAISE NOTICE 'Date threshold: %', threshold;
879         --
880         -- Threshold found; do the delete
881         delete from container.copy_bucket_item
882         where
883                 bucket in
884                 (
885                         select
886                                 id
887                         from
888                                 container.copy_bucket
889                         where
890                                 owner = ac_usr
891                                 and btype = 'circ_history'
892                 )
893                 and create_time < threshold;
894         --
895         RETURN;
896 END;
897 $$ LANGUAGE plpgsql;
898
899 COMMENT ON FUNCTION container.clear_expired_circ_history_items( INTEGER ) IS $$
900 /*
901  * Delete old circulation bucket items for a specified user.
902  * "Old" means older than the interval specified by a
903  * user-level setting, if it is so specified.
904 */
905 $$;
906
907 CREATE OR REPLACE FUNCTION container.clear_all_expired_circ_history_items( )
908 RETURNS VOID AS $$
909 --
910 -- Delete expired circulation bucket items for all users that have
911 -- a setting for patron.max_reading_list_interval.
912 --
913 DECLARE
914     today        TIMESTAMP WITH TIME ZONE;
915     threshold    TIMESTAMP WITH TIME ZONE;
916         usr_setting  RECORD;
917 BEGIN
918         SELECT date_trunc( 'day', now() ) INTO today;
919         --
920         FOR usr_setting in
921                 SELECT
922                         usr,
923                         value
924                 FROM
925                         actor.usr_setting
926                 WHERE
927                         name = 'patron.max_reading_list_interval'
928         LOOP
929                 --
930                 -- Make sure the setting is a valid interval
931                 --
932                 BEGIN
933                         threshold := today - CAST( translate( usr_setting.value, '"', '' ) AS INTERVAL );
934                 EXCEPTION
935                         WHEN OTHERS THEN
936                                 RAISE NOTICE 'Invalid setting patron.max_reading_list_interval for user %: ''%''',
937                                         usr_setting.usr, usr_setting.value;
938                                 CONTINUE;
939                 END;
940                 --
941                 --RAISE NOTICE 'User % threshold %', usr_setting.usr, threshold;
942                 --
943         DELETE FROM container.copy_bucket_item
944         WHERE
945                 bucket IN
946                 (
947                     SELECT
948                         id
949                     FROM
950                         container.copy_bucket
951                     WHERE
952                         owner = usr_setting.usr
953                         AND btype = 'circ_history'
954                 )
955                 AND create_time < threshold;
956         END LOOP;
957         --
958 END;
959 $$ LANGUAGE plpgsql;
960
961 COMMENT ON FUNCTION container.clear_all_expired_circ_history_items( ) IS $$
962 /*
963  * Delete expired circulation bucket items for all users that have
964  * a setting for patron.max_reading_list_interval.
965 */
966 $$;
967
968 CREATE OR REPLACE FUNCTION asset.merge_record_assets( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
969 DECLARE
970     moved_objects INT := 0;
971     source_cn     asset.call_number%ROWTYPE;
972     target_cn     asset.call_number%ROWTYPE;
973     metarec       metabib.metarecord%ROWTYPE;
974     hold          action.hold_request%ROWTYPE;
975     ser_rec       serial.record_entry%ROWTYPE;
976     uri_count     INT := 0;
977     counter       INT := 0;
978     uri_datafield TEXT;
979     uri_text      TEXT := '';
980 BEGIN
981
982     -- move any 856 entries on records that have at least one MARC-mapped URI entry
983     SELECT  INTO uri_count COUNT(*)
984       FROM  asset.uri_call_number_map m
985             JOIN asset.call_number cn ON (m.call_number = cn.id)
986       WHERE cn.record = source_record;
987
988     IF uri_count > 0 THEN
989         
990         SELECT  COUNT(*) INTO counter
991           FROM  oils_xpath_table(
992                     'id',
993                     'marc',
994                     'biblio.record_entry',
995                     '//*[@tag="856"]',
996                     'id=' || source_record
997                 ) as t(i int,c text);
998     
999         FOR i IN 1 .. counter LOOP
1000             SELECT  '<datafield xmlns="http://www.loc.gov/MARC21/slim" tag="856">' ||
1001                         array_to_string(
1002                             array_accum(
1003                                 '<subfield code="' || subfield || '">' ||
1004                                 regexp_replace(
1005                                     regexp_replace(
1006                                         regexp_replace(data,'&','&amp;','g'),
1007                                         '>', '&gt;', 'g'
1008                                     ),
1009                                     '<', '&lt;', 'g'
1010                                 ) || '</subfield>'
1011                             ), ''
1012                         ) || '</datafield>' INTO uri_datafield
1013               FROM  oils_xpath_table(
1014                         'id',
1015                         'marc',
1016                         'biblio.record_entry',
1017                         '//*[@tag="856"][position()=' || i || ']/*/@code|' ||
1018                         '//*[@tag="856"][position()=' || i || ']/*[@code]',
1019                         'id=' || source_record
1020                     ) as t(id int,subfield text,data text);
1021
1022             uri_text := uri_text || uri_datafield;
1023         END LOOP;
1024
1025         IF uri_text <> '' THEN
1026             UPDATE  biblio.record_entry
1027               SET   marc = regexp_replace(marc,'(</[^>]*record>)', uri_text || E'\\1')
1028               WHERE id = target_record;
1029         END IF;
1030
1031     END IF;
1032
1033         -- Find and move metarecords to the target record
1034         SELECT  INTO metarec *
1035           FROM  metabib.metarecord
1036           WHERE master_record = source_record;
1037
1038         IF FOUND THEN
1039                 UPDATE  metabib.metarecord
1040                   SET   master_record = target_record,
1041                         mods = NULL
1042                   WHERE id = metarec.id;
1043
1044                 moved_objects := moved_objects + 1;
1045         END IF;
1046
1047         -- Find call numbers attached to the source ...
1048         FOR source_cn IN SELECT * FROM asset.call_number WHERE record = source_record LOOP
1049
1050                 SELECT  INTO target_cn *
1051                   FROM  asset.call_number
1052                   WHERE label = source_cn.label
1053                         AND owning_lib = source_cn.owning_lib
1054                         AND record = target_record;
1055
1056                 -- ... and if there's a conflicting one on the target ...
1057                 IF FOUND THEN
1058
1059                         -- ... move the copies to that, and ...
1060                         UPDATE  asset.copy
1061                           SET   call_number = target_cn.id
1062                           WHERE call_number = source_cn.id;
1063
1064                         -- ... move V holds to the move-target call number
1065                         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_cn.id AND hold_type = 'V' LOOP
1066                 
1067                                 UPDATE  action.hold_request
1068                                   SET   target = target_cn.id
1069                                   WHERE id = hold.id;
1070                 
1071                                 moved_objects := moved_objects + 1;
1072                         END LOOP;
1073
1074                 -- ... if not ...
1075                 ELSE
1076                         -- ... just move the call number to the target record
1077                         UPDATE  asset.call_number
1078                           SET   record = target_record
1079                           WHERE id = source_cn.id;
1080                 END IF;
1081
1082                 moved_objects := moved_objects + 1;
1083         END LOOP;
1084
1085         -- Find T holds targeting the source record ...
1086         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_record AND hold_type = 'T' LOOP
1087
1088                 -- ... and move them to the target record
1089                 UPDATE  action.hold_request
1090                   SET   target = target_record
1091                   WHERE id = hold.id;
1092
1093                 moved_objects := moved_objects + 1;
1094         END LOOP;
1095
1096         -- Find serial records targeting the source record ...
1097         FOR ser_rec IN SELECT * FROM serial.record_entry WHERE record = source_record LOOP
1098                 -- ... and move them to the target record
1099                 UPDATE  serial.record_entry
1100                   SET   record = target_record
1101                   WHERE id = ser_rec.id;
1102
1103                 moved_objects := moved_objects + 1;
1104         END LOOP;
1105
1106     -- Finally, "delete" the source record
1107     DELETE FROM biblio.record_entry WHERE id = source_record;
1108
1109         -- That's all, folks!
1110         RETURN moved_objects;
1111 END;
1112 $func$ LANGUAGE plpgsql;
1113
1114 -- copy OPAC visibility materialized view
1115 CREATE OR REPLACE FUNCTION asset.refresh_opac_visible_copies_mat_view () RETURNS VOID AS $$
1116
1117     TRUNCATE TABLE asset.opac_visible_copies;
1118
1119     INSERT INTO asset.opac_visible_copies (id, circ_lib, record)
1120     SELECT  cp.id, cp.circ_lib, cn.record
1121     FROM  asset.copy cp
1122         JOIN asset.call_number cn ON (cn.id = cp.call_number)
1123         JOIN actor.org_unit a ON (cp.circ_lib = a.id)
1124         JOIN asset.copy_location cl ON (cp.location = cl.id)
1125         JOIN config.copy_status cs ON (cp.status = cs.id)
1126         JOIN biblio.record_entry b ON (cn.record = b.id)
1127     WHERE NOT cp.deleted
1128         AND NOT cn.deleted
1129         AND NOT b.deleted
1130         AND cs.opac_visible
1131         AND cl.opac_visible
1132         AND cp.opac_visible
1133         AND a.opac_visible;
1134
1135 $$ LANGUAGE SQL;
1136 COMMENT ON FUNCTION asset.refresh_opac_visible_copies_mat_view() IS $$
1137 Rebuild the copy OPAC visibility cache.  Useful during migrations.
1138 $$;
1139
1140 CREATE OR REPLACE FUNCTION asset.cache_copy_visibility () RETURNS TRIGGER as $func$
1141 DECLARE
1142     add_query       TEXT;
1143     remove_query    TEXT;
1144     do_add          BOOLEAN := false;
1145     do_remove       BOOLEAN := false;
1146 BEGIN
1147     add_query := $$
1148             INSERT INTO asset.opac_visible_copies (id, circ_lib, record)
1149                 SELECT  cp.id, cp.circ_lib, cn.record
1150                   FROM  asset.copy cp
1151                         JOIN asset.call_number cn ON (cn.id = cp.call_number)
1152                         JOIN actor.org_unit a ON (cp.circ_lib = a.id)
1153                         JOIN asset.copy_location cl ON (cp.location = cl.id)
1154                         JOIN config.copy_status cs ON (cp.status = cs.id)
1155                         JOIN biblio.record_entry b ON (cn.record = b.id)
1156                   WHERE NOT cp.deleted
1157                         AND NOT cn.deleted
1158                         AND NOT b.deleted
1159                         AND cs.opac_visible
1160                         AND cl.opac_visible
1161                         AND cp.opac_visible
1162                         AND a.opac_visible
1163     $$;
1164  
1165     remove_query := $$ DELETE FROM asset.opac_visible_copies WHERE id IN ( SELECT id FROM asset.copy WHERE $$;
1166
1167     IF TG_OP = 'INSERT' THEN
1168
1169         IF TG_TABLE_NAME IN ('copy', 'unit') THEN
1170             add_query := add_query || 'AND cp.id = ' || NEW.id || ';';
1171             EXECUTE add_query;
1172         END IF;
1173
1174         RETURN NEW;
1175
1176     END IF;
1177
1178     -- handle items first, since with circulation activity
1179     -- their statuses change frequently
1180     IF TG_TABLE_NAME IN ('copy', 'unit') THEN
1181
1182         IF OLD.location    <> NEW.location OR
1183            OLD.call_number <> NEW.call_number OR
1184            OLD.status      <> NEW.status OR
1185            OLD.circ_lib    <> NEW.circ_lib THEN
1186             -- any of these could change visibility, but
1187             -- we'll save some queries and not try to calculate
1188             -- the change directly
1189             do_remove := true;
1190             do_add := true;
1191         ELSE
1192
1193             IF OLD.deleted <> NEW.deleted THEN
1194                 IF NEW.deleted THEN
1195                     do_remove := true;
1196                 ELSE
1197                     do_add := true;
1198                 END IF;
1199             END IF;
1200
1201             IF OLD.opac_visible <> NEW.opac_visible THEN
1202                 IF OLD.opac_visible THEN
1203                     do_remove := true;
1204                 ELSIF NOT do_remove THEN -- handle edge case where deleted item
1205                                         -- is also marked opac_visible
1206                     do_add := true;
1207                 END IF;
1208             END IF;
1209
1210         END IF;
1211
1212         IF do_remove THEN
1213             DELETE FROM asset.opac_visible_copies WHERE id = NEW.id;
1214         END IF;
1215         IF do_add THEN
1216             add_query := add_query || 'AND cp.id = ' || NEW.id || ';';
1217             EXECUTE add_query;
1218         END IF;
1219
1220         RETURN NEW;
1221
1222     END IF;
1223
1224     IF TG_TABLE_NAME IN ('call_number', 'record_entry') THEN -- these have a 'deleted' column
1225  
1226         IF OLD.deleted AND NEW.deleted THEN -- do nothing
1227
1228             RETURN NEW;
1229  
1230         ELSIF NEW.deleted THEN -- remove rows
1231  
1232             IF TG_TABLE_NAME = 'call_number' THEN
1233                 DELETE FROM asset.opac_visible_copies WHERE id IN (SELECT id FROM asset.copy WHERE call_number = NEW.id);
1234             ELSIF TG_TABLE_NAME = 'record_entry' THEN
1235                 DELETE FROM asset.opac_visible_copies WHERE record = NEW.id;
1236             END IF;
1237  
1238             RETURN NEW;
1239  
1240         ELSIF OLD.deleted THEN -- add rows
1241  
1242             IF TG_TABLE_NAME IN ('copy','unit') THEN
1243                 add_query := add_query || 'AND cp.id = ' || NEW.id || ';';
1244             ELSIF TG_TABLE_NAME = 'call_number' THEN
1245                 add_query := add_query || 'AND cp.call_number = ' || NEW.id || ';';
1246             ELSIF TG_TABLE_NAME = 'record_entry' THEN
1247                 add_query := add_query || 'AND cn.record = ' || NEW.id || ';';
1248             END IF;
1249  
1250             EXECUTE add_query;
1251             RETURN NEW;
1252  
1253         END IF;
1254  
1255     END IF;
1256
1257     IF TG_TABLE_NAME = 'call_number' THEN
1258
1259         IF OLD.record <> NEW.record THEN
1260             -- call number is linked to different bib
1261             remove_query := remove_query || 'call_number = ' || NEW.id || ');';
1262             EXECUTE remove_query;
1263             add_query := add_query || 'AND cp.call_number = ' || NEW.id || ';';
1264             EXECUTE add_query;
1265         END IF;
1266
1267         RETURN NEW;
1268
1269     END IF;
1270
1271     IF TG_TABLE_NAME IN ('record_entry') THEN
1272         RETURN NEW; -- don't have 'opac_visible'
1273     END IF;
1274
1275     -- actor.org_unit, asset.copy_location, asset.copy_status
1276     IF NEW.opac_visible = OLD.opac_visible THEN -- do nothing
1277
1278         RETURN NEW;
1279
1280     ELSIF NEW.opac_visible THEN -- add rows
1281
1282         IF TG_TABLE_NAME = 'org_unit' THEN
1283             add_query := add_query || 'AND cp.circ_lib = ' || NEW.id || ';';
1284         ELSIF TG_TABLE_NAME = 'copy_location' THEN
1285             add_query := add_query || 'AND cp.location = ' || NEW.id || ';';
1286         ELSIF TG_TABLE_NAME = 'copy_status' THEN
1287             add_query := add_query || 'AND cp.status = ' || NEW.id || ';';
1288         END IF;
1289  
1290         EXECUTE add_query;
1291  
1292     ELSE -- delete rows
1293
1294         IF TG_TABLE_NAME = 'org_unit' THEN
1295             remove_query := 'DELETE FROM asset.opac_visible_copies WHERE circ_lib = ' || NEW.id || ';';
1296         ELSIF TG_TABLE_NAME = 'copy_location' THEN
1297             remove_query := remove_query || 'location = ' || NEW.id || ');';
1298         ELSIF TG_TABLE_NAME = 'copy_status' THEN
1299             remove_query := remove_query || 'status = ' || NEW.id || ');';
1300         END IF;
1301  
1302         EXECUTE remove_query;
1303  
1304     END IF;
1305  
1306     RETURN NEW;
1307 END;
1308 $func$ LANGUAGE PLPGSQL;
1309 COMMENT ON FUNCTION asset.cache_copy_visibility() IS $$
1310 Trigger function to update the copy OPAC visiblity cache.
1311 $$;
1312 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1313 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON asset.copy FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1314 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON asset.call_number FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1315 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON asset.copy_location FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1316 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON serial.unit FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1317 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON config.copy_status FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1318 CREATE TRIGGER a_opac_vis_mat_view_tgr AFTER INSERT OR UPDATE ON actor.org_unit FOR EACH ROW EXECUTE PROCEDURE asset.cache_copy_visibility();
1319
1320 -- Authority ingest routines
1321 CREATE OR REPLACE FUNCTION authority.propagate_changes (aid BIGINT, bid BIGINT) RETURNS BIGINT AS $func$
1322     UPDATE  biblio.record_entry
1323       SET   marc = vandelay.merge_record_xml( marc, authority.generate_overlay_template( $1 ) )
1324       WHERE id = $2;
1325     SELECT $1;
1326 $func$ LANGUAGE SQL;
1327
1328 CREATE OR REPLACE FUNCTION authority.propagate_changes (aid BIGINT) RETURNS SETOF BIGINT AS $func$
1329     SELECT authority.propagate_changes( authority, bib ) FROM authority.bib_linking WHERE authority = $1;
1330 $func$ LANGUAGE SQL;
1331
1332 CREATE OR REPLACE FUNCTION authority.flatten_marc ( TEXT ) RETURNS SETOF authority.full_rec AS $func$
1333
1334 use MARC::Record;
1335 use MARC::File::XML (BinaryEncoding => 'UTF-8');
1336
1337 my $xml = shift;
1338 my $r = MARC::Record->new_from_xml( $xml );
1339
1340 return_next( { tag => 'LDR', value => $r->leader } );
1341
1342 for my $f ( $r->fields ) {
1343     if ($f->is_control_field) {
1344         return_next({ tag => $f->tag, value => $f->data });
1345     } else {
1346         for my $s ($f->subfields) {
1347             return_next({
1348                 tag      => $f->tag,
1349                 ind1     => $f->indicator(1),
1350                 ind2     => $f->indicator(2),
1351                 subfield => $s->[0],
1352                 value    => $s->[1]
1353             });
1354
1355         }
1356     }
1357 }
1358
1359 return undef;
1360
1361 $func$ LANGUAGE PLPERLU;
1362
1363 CREATE OR REPLACE FUNCTION authority.flatten_marc ( rid BIGINT ) RETURNS SETOF authority.full_rec AS $func$
1364 DECLARE
1365     auth    authority.record_entry%ROWTYPE;
1366     output    authority.full_rec%ROWTYPE;
1367     field    RECORD;
1368 BEGIN
1369     SELECT INTO auth * FROM authority.record_entry WHERE id = rid;
1370
1371     FOR field IN SELECT * FROM authority.flatten_marc( auth.marc ) LOOP
1372         output.record := rid;
1373         output.ind1 := field.ind1;
1374         output.ind2 := field.ind2;
1375         output.tag := field.tag;
1376         output.subfield := field.subfield;
1377         IF field.subfield IS NOT NULL THEN
1378             output.value := naco_normalize(field.value, field.subfield);
1379         ELSE
1380             output.value := field.value;
1381         END IF;
1382
1383         CONTINUE WHEN output.value IS NULL;
1384
1385         RETURN NEXT output;
1386     END LOOP;
1387 END;
1388 $func$ LANGUAGE PLPGSQL;
1389
1390 -- authority.rec_descriptor appears to be unused currently
1391 CREATE OR REPLACE FUNCTION authority.reingest_authority_rec_descriptor( auth_id BIGINT ) RETURNS VOID AS $func$
1392 BEGIN
1393     DELETE FROM authority.rec_descriptor WHERE record = auth_id;
1394 --    INSERT INTO authority.rec_descriptor (record, record_status, char_encoding)
1395 --        SELECT  auth_id, ;
1396
1397     RETURN;
1398 END;
1399 $func$ LANGUAGE PLPGSQL;
1400
1401 CREATE OR REPLACE FUNCTION authority.reingest_authority_full_rec( auth_id BIGINT ) RETURNS VOID AS $func$
1402 BEGIN
1403     DELETE FROM authority.full_rec WHERE record = auth_id;
1404     INSERT INTO authority.full_rec (record, tag, ind1, ind2, subfield, value)
1405         SELECT record, tag, ind1, ind2, subfield, value FROM authority.flatten_marc( auth_id );
1406
1407     RETURN;
1408 END;
1409 $func$ LANGUAGE PLPGSQL;
1410
1411 -- AFTER UPDATE OR INSERT trigger for authority.record_entry
1412 CREATE OR REPLACE FUNCTION authority.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
1413 BEGIN
1414
1415     IF NEW.deleted IS TRUE THEN -- If this authority is deleted
1416         DELETE FROM authority.bib_linking WHERE authority = NEW.id; -- Avoid updating fields in bibs that are no longer visible
1417           -- Should remove matching $0 from controlled fields at the same time?
1418         RETURN NEW; -- and we're done
1419     END IF;
1420
1421     IF TG_OP = 'UPDATE' THEN -- re-ingest?
1422         PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
1423
1424         IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
1425             RETURN NEW;
1426         END IF;
1427     END IF;
1428
1429     -- Flatten and insert the afr data
1430     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_full_rec' AND enabled;
1431     IF NOT FOUND THEN
1432         PERFORM authority.reingest_authority_full_rec(NEW.id);
1433 -- authority.rec_descriptor is not currently used
1434 --        PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_rec_descriptor' AND enabled;
1435 --        IF NOT FOUND THEN
1436 --            PERFORM authority.reingest_authority_rec_descriptor(NEW.id);
1437 --        END IF;
1438     END IF;
1439
1440     RETURN NEW;
1441 END;
1442 $func$ LANGUAGE PLPGSQL;
1443
1444 -- Ingest triggers
1445 CREATE TRIGGER fingerprint_tgr BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.fingerprint_trigger ('eng','BKS');
1446 CREATE TRIGGER aaa_indexing_ingest_or_delete AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.indexing_ingest_or_delete ();
1447 CREATE TRIGGER bbb_simple_rec_trigger AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE reporter.simple_rec_trigger ();
1448
1449 CREATE TRIGGER aaa_auth_ingest_or_delete AFTER INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE authority.indexing_ingest_or_delete ();
1450
1451 -- Utility routines, callable via cstore
1452
1453 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_val INTERVAL )
1454 RETURNS INTEGER AS $$
1455 BEGIN
1456         RETURN EXTRACT( EPOCH FROM interval_val );
1457 END;
1458 $$ LANGUAGE plpgsql;
1459
1460 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_string TEXT )
1461 RETURNS INTEGER AS $$
1462 BEGIN
1463         RETURN config.interval_to_seconds( interval_string::INTERVAL );
1464 END;
1465 $$ LANGUAGE plpgsql;