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