]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/sql/Pg/999.functions.global.sql
LP#1776020 Patron preferred name & name keywords
[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 Attempts to move each row of the specified table from src_user to dest_user.  
41 Where conflicts exist, the conflicting "source" row is deleted.
42 $$;
43
44
45 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 $$
46 DECLARE
47         suffix TEXT;
48         bucket_row RECORD;
49         picklist_row RECORD;
50         queue_row RECORD;
51         folder_row RECORD;
52 BEGIN
53
54     -- do some initial cleanup 
55     UPDATE actor.usr SET card = NULL WHERE id = src_usr;
56     UPDATE actor.usr SET mailing_address = NULL WHERE id = src_usr;
57     UPDATE actor.usr SET billing_address = NULL WHERE id = src_usr;
58
59     -- actor.*
60     IF del_cards THEN
61         DELETE FROM actor.card where usr = src_usr;
62     ELSE
63         IF deactivate_cards THEN
64             UPDATE actor.card SET active = 'f' WHERE usr = src_usr;
65         END IF;
66         UPDATE actor.card SET usr = dest_usr WHERE usr = src_usr;
67     END IF;
68
69
70     IF del_addrs THEN
71         DELETE FROM actor.usr_address WHERE usr = src_usr;
72     ELSE
73         UPDATE actor.usr_address SET usr = dest_usr WHERE usr = src_usr;
74     END IF;
75
76     UPDATE actor.usr_note SET usr = dest_usr WHERE usr = src_usr;
77     -- dupes are technically OK in actor.usr_standing_penalty, should manually delete them...
78     UPDATE actor.usr_standing_penalty SET usr = dest_usr WHERE usr = src_usr;
79     PERFORM actor.usr_merge_rows('actor.usr_org_unit_opt_in', 'usr', src_usr, dest_usr);
80     PERFORM actor.usr_merge_rows('actor.usr_setting', 'usr', src_usr, dest_usr);
81
82     -- permission.*
83     PERFORM actor.usr_merge_rows('permission.usr_perm_map', 'usr', src_usr, dest_usr);
84     PERFORM actor.usr_merge_rows('permission.usr_object_perm_map', 'usr', src_usr, dest_usr);
85     PERFORM actor.usr_merge_rows('permission.usr_grp_map', 'usr', src_usr, dest_usr);
86     PERFORM actor.usr_merge_rows('permission.usr_work_ou_map', 'usr', src_usr, dest_usr);
87
88
89     -- container.*
90         
91         -- For each *_bucket table: transfer every bucket belonging to src_usr
92         -- into the custody of dest_usr.
93         --
94         -- In order to avoid colliding with an existing bucket owned by
95         -- the destination user, append the source user's id (in parenthesese)
96         -- to the name.  If you still get a collision, add successive
97         -- spaces to the name and keep trying until you succeed.
98         --
99         FOR bucket_row in
100                 SELECT id, name
101                 FROM   container.biblio_record_entry_bucket
102                 WHERE  owner = src_usr
103         LOOP
104                 suffix := ' (' || src_usr || ')';
105                 LOOP
106                         BEGIN
107                                 UPDATE  container.biblio_record_entry_bucket
108                                 SET     owner = dest_usr, name = name || suffix
109                                 WHERE   id = bucket_row.id;
110                         EXCEPTION WHEN unique_violation THEN
111                                 suffix := suffix || ' ';
112                                 CONTINUE;
113                         END;
114                         EXIT;
115                 END LOOP;
116         END LOOP;
117
118         FOR bucket_row in
119                 SELECT id, name
120                 FROM   container.call_number_bucket
121                 WHERE  owner = src_usr
122         LOOP
123                 suffix := ' (' || src_usr || ')';
124                 LOOP
125                         BEGIN
126                                 UPDATE  container.call_number_bucket
127                                 SET     owner = dest_usr, name = name || suffix
128                                 WHERE   id = bucket_row.id;
129                         EXCEPTION WHEN unique_violation THEN
130                                 suffix := suffix || ' ';
131                                 CONTINUE;
132                         END;
133                         EXIT;
134                 END LOOP;
135         END LOOP;
136
137         FOR bucket_row in
138                 SELECT id, name
139                 FROM   container.copy_bucket
140                 WHERE  owner = src_usr
141         LOOP
142                 suffix := ' (' || src_usr || ')';
143                 LOOP
144                         BEGIN
145                                 UPDATE  container.copy_bucket
146                                 SET     owner = dest_usr, name = name || suffix
147                                 WHERE   id = bucket_row.id;
148                         EXCEPTION WHEN unique_violation THEN
149                                 suffix := suffix || ' ';
150                                 CONTINUE;
151                         END;
152                         EXIT;
153                 END LOOP;
154         END LOOP;
155
156         FOR bucket_row in
157                 SELECT id, name
158                 FROM   container.user_bucket
159                 WHERE  owner = src_usr
160         LOOP
161                 suffix := ' (' || src_usr || ')';
162                 LOOP
163                         BEGIN
164                                 UPDATE  container.user_bucket
165                                 SET     owner = dest_usr, name = name || suffix
166                                 WHERE   id = bucket_row.id;
167                         EXCEPTION WHEN unique_violation THEN
168                                 suffix := suffix || ' ';
169                                 CONTINUE;
170                         END;
171                         EXIT;
172                 END LOOP;
173         END LOOP;
174
175         UPDATE container.user_bucket_item SET target_user = dest_usr WHERE target_user = src_usr;
176
177     -- vandelay.*
178         -- transfer queues the same way we transfer buckets (see above)
179         FOR queue_row in
180                 SELECT id, name
181                 FROM   vandelay.queue
182                 WHERE  owner = src_usr
183         LOOP
184                 suffix := ' (' || src_usr || ')';
185                 LOOP
186                         BEGIN
187                                 UPDATE  vandelay.queue
188                                 SET     owner = dest_usr, name = name || suffix
189                                 WHERE   id = queue_row.id;
190                         EXCEPTION WHEN unique_violation THEN
191                                 suffix := suffix || ' ';
192                                 CONTINUE;
193                         END;
194                         EXIT;
195                 END LOOP;
196         END LOOP;
197
198     -- money.*
199     PERFORM actor.usr_merge_rows('money.collections_tracker', 'usr', src_usr, dest_usr);
200     PERFORM actor.usr_merge_rows('money.collections_tracker', 'collector', src_usr, dest_usr);
201     UPDATE money.billable_xact SET usr = dest_usr WHERE usr = src_usr;
202     UPDATE money.billing SET voider = dest_usr WHERE voider = src_usr;
203     UPDATE money.bnm_payment SET accepting_usr = dest_usr WHERE accepting_usr = src_usr;
204
205     -- action.*
206     UPDATE action.circulation SET usr = dest_usr WHERE usr = src_usr;
207     UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
208     UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
209     UPDATE action.usr_circ_history SET usr = dest_usr WHERE usr = src_usr;
210
211     UPDATE action.hold_request SET usr = dest_usr WHERE usr = src_usr;
212     UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
213     UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
214     UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
215
216     UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
217     UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
218     UPDATE action.non_cataloged_circulation SET patron = dest_usr WHERE patron = src_usr;
219     UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
220     UPDATE action.survey_response SET usr = dest_usr WHERE usr = src_usr;
221
222     -- acq.*
223     UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
224         UPDATE acq.fund_transfer SET transfer_user = dest_usr WHERE transfer_user = src_usr;
225
226         -- transfer picklists the same way we transfer buckets (see above)
227         FOR picklist_row in
228                 SELECT id, name
229                 FROM   acq.picklist
230                 WHERE  owner = src_usr
231         LOOP
232                 suffix := ' (' || src_usr || ')';
233                 LOOP
234                         BEGIN
235                                 UPDATE  acq.picklist
236                                 SET     owner = dest_usr, name = name || suffix
237                                 WHERE   id = picklist_row.id;
238                         EXCEPTION WHEN unique_violation THEN
239                                 suffix := suffix || ' ';
240                                 CONTINUE;
241                         END;
242                         EXIT;
243                 END LOOP;
244         END LOOP;
245
246     UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
247     UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
248     UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
249     UPDATE acq.provider_note SET creator = dest_usr WHERE creator = src_usr;
250     UPDATE acq.provider_note SET editor = dest_usr WHERE editor = src_usr;
251     UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
252     UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
253     UPDATE acq.lineitem_usr_attr_definition SET usr = dest_usr WHERE usr = src_usr;
254
255     -- asset.*
256     UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
257     UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
258     UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
259     UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
260     UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
261     UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
262
263     -- serial.*
264     UPDATE serial.record_entry SET creator = dest_usr WHERE creator = src_usr;
265     UPDATE serial.record_entry SET editor = dest_usr WHERE editor = src_usr;
266
267     -- reporter.*
268     -- It's not uncommon to define the reporter schema in a replica 
269     -- DB only, so don't assume these tables exist in the write DB.
270     BEGIN
271         UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
272     EXCEPTION WHEN undefined_table THEN
273         -- do nothing
274     END;
275     BEGIN
276         UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
277     EXCEPTION WHEN undefined_table THEN
278         -- do nothing
279     END;
280     BEGIN
281         UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
282     EXCEPTION WHEN undefined_table THEN
283         -- do nothing
284     END;
285     BEGIN
286                 -- transfer folders the same way we transfer buckets (see above)
287                 FOR folder_row in
288                         SELECT id, name
289                         FROM   reporter.template_folder
290                         WHERE  owner = src_usr
291                 LOOP
292                         suffix := ' (' || src_usr || ')';
293                         LOOP
294                                 BEGIN
295                                         UPDATE  reporter.template_folder
296                                         SET     owner = dest_usr, name = name || suffix
297                                         WHERE   id = folder_row.id;
298                                 EXCEPTION WHEN unique_violation THEN
299                                         suffix := suffix || ' ';
300                                         CONTINUE;
301                                 END;
302                                 EXIT;
303                         END LOOP;
304                 END LOOP;
305     EXCEPTION WHEN undefined_table THEN
306         -- do nothing
307     END;
308     BEGIN
309                 -- transfer folders the same way we transfer buckets (see above)
310                 FOR folder_row in
311                         SELECT id, name
312                         FROM   reporter.report_folder
313                         WHERE  owner = src_usr
314                 LOOP
315                         suffix := ' (' || src_usr || ')';
316                         LOOP
317                                 BEGIN
318                                         UPDATE  reporter.report_folder
319                                         SET     owner = dest_usr, name = name || suffix
320                                         WHERE   id = folder_row.id;
321                                 EXCEPTION WHEN unique_violation THEN
322                                         suffix := suffix || ' ';
323                                         CONTINUE;
324                                 END;
325                                 EXIT;
326                         END LOOP;
327                 END LOOP;
328     EXCEPTION WHEN undefined_table THEN
329         -- do nothing
330     END;
331     BEGIN
332                 -- transfer folders the same way we transfer buckets (see above)
333                 FOR folder_row in
334                         SELECT id, name
335                         FROM   reporter.output_folder
336                         WHERE  owner = src_usr
337                 LOOP
338                         suffix := ' (' || src_usr || ')';
339                         LOOP
340                                 BEGIN
341                                         UPDATE  reporter.output_folder
342                                         SET     owner = dest_usr, name = name || suffix
343                                         WHERE   id = folder_row.id;
344                                 EXCEPTION WHEN unique_violation THEN
345                                         suffix := suffix || ' ';
346                                         CONTINUE;
347                                 END;
348                                 EXIT;
349                         END LOOP;
350                 END LOOP;
351     EXCEPTION WHEN undefined_table THEN
352         -- do nothing
353     END;
354
355     -- propagate preferred name values from the source user to the
356     -- destination user, but only when values are not being replaced.
357     WITH susr AS (SELECT * FROM actor.usr WHERE id = src_usr)
358     UPDATE actor.usr SET 
359         pref_prefix = 
360             COALESCE(pref_prefix, (SELECT pref_prefix FROM susr)),
361         pref_first_given_name = 
362             COALESCE(pref_first_given_name, (SELECT pref_first_given_name FROM susr)),
363         pref_second_given_name = 
364             COALESCE(pref_second_given_name, (SELECT pref_second_given_name FROM susr)),
365         pref_family_name = 
366             COALESCE(pref_family_name, (SELECT pref_family_name FROM susr)),
367         pref_suffix = 
368             COALESCE(pref_suffix, (SELECT pref_suffix FROM susr)),
369         name_keywords =
370             COALESCE(name_keywords, '') || ' ' ||
371                 COALESCE((SELECT name_keywords FROM susr), '')
372     WHERE id = dest_usr;
373
374     -- Finally, delete the source user
375     DELETE FROM actor.usr WHERE id = src_usr;
376
377 END;
378 $$ LANGUAGE plpgsql;
379
380
381
382 COMMENT ON FUNCTION actor.usr_merge(INT, INT, BOOLEAN, BOOLEAN, BOOLEAN) IS $$
383 Merges all user date from src_usr to dest_usr.  When collisions occur, 
384 keep dest_usr's data and delete src_usr's data.
385 $$;
386
387
388 CREATE OR REPLACE FUNCTION actor.usr_purge_data(
389         src_usr  IN INTEGER,
390         specified_dest_usr IN INTEGER
391 ) RETURNS VOID AS $$
392 DECLARE
393         suffix TEXT;
394         renamable_row RECORD;
395         dest_usr INTEGER;
396 BEGIN
397
398         IF specified_dest_usr IS NULL THEN
399                 dest_usr := 1; -- Admin user on stock installs
400         ELSE
401                 dest_usr := specified_dest_usr;
402         END IF;
403
404         -- acq.*
405         UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
406         UPDATE acq.lineitem SET creator = dest_usr WHERE creator = src_usr;
407         UPDATE acq.lineitem SET editor = dest_usr WHERE editor = src_usr;
408         UPDATE acq.lineitem SET selector = dest_usr WHERE selector = src_usr;
409         UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
410         UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
411         DELETE FROM acq.lineitem_usr_attr_definition WHERE usr = src_usr;
412
413         -- Update with a rename to avoid collisions
414         FOR renamable_row in
415                 SELECT id, name
416                 FROM   acq.picklist
417                 WHERE  owner = src_usr
418         LOOP
419                 suffix := ' (' || src_usr || ')';
420                 LOOP
421                         BEGIN
422                                 UPDATE  acq.picklist
423                                 SET     owner = dest_usr, name = name || suffix
424                                 WHERE   id = renamable_row.id;
425                         EXCEPTION WHEN unique_violation THEN
426                                 suffix := suffix || ' ';
427                                 CONTINUE;
428                         END;
429                         EXIT;
430                 END LOOP;
431         END LOOP;
432
433         UPDATE acq.picklist SET creator = dest_usr WHERE creator = src_usr;
434         UPDATE acq.picklist SET editor = dest_usr WHERE editor = src_usr;
435         UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
436         UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
437         UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
438         UPDATE acq.purchase_order SET creator = dest_usr WHERE creator = src_usr;
439         UPDATE acq.purchase_order SET editor = dest_usr WHERE editor = src_usr;
440         UPDATE acq.claim_event SET creator = dest_usr WHERE creator = src_usr;
441
442         -- action.*
443         DELETE FROM action.circulation WHERE usr = src_usr;
444         UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
445         UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
446         UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
447         UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
448         UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
449         DELETE FROM action.hold_request WHERE usr = src_usr;
450         UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
451         UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
452         DELETE FROM action.non_cataloged_circulation WHERE patron = src_usr;
453         UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
454         DELETE FROM action.survey_response WHERE usr = src_usr;
455         UPDATE action.fieldset SET owner = dest_usr WHERE owner = src_usr;
456         DELETE FROM action.usr_circ_history WHERE usr = src_usr;
457
458         -- actor.*
459         DELETE FROM actor.card WHERE usr = src_usr;
460         DELETE FROM actor.stat_cat_entry_usr_map WHERE target_usr = src_usr;
461
462         -- The following update is intended to avoid transient violations of a foreign
463         -- key constraint, whereby actor.usr_address references itself.  It may not be
464         -- necessary, but it does no harm.
465         UPDATE actor.usr_address SET replaces = NULL
466                 WHERE usr = src_usr AND replaces IS NOT NULL;
467         DELETE FROM actor.usr_address WHERE usr = src_usr;
468         DELETE FROM actor.usr_note WHERE usr = src_usr;
469         UPDATE actor.usr_note SET creator = dest_usr WHERE creator = src_usr;
470         DELETE FROM actor.usr_org_unit_opt_in WHERE usr = src_usr;
471         UPDATE actor.usr_org_unit_opt_in SET staff = dest_usr WHERE staff = src_usr;
472         DELETE FROM actor.usr_setting WHERE usr = src_usr;
473         DELETE FROM actor.usr_standing_penalty WHERE usr = src_usr;
474         UPDATE actor.usr_standing_penalty SET staff = dest_usr WHERE staff = src_usr;
475
476         -- asset.*
477         UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
478         UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
479         UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
480         UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
481         UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
482         UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
483
484         -- auditor.*
485         DELETE FROM auditor.actor_usr_address_history WHERE id = src_usr;
486         DELETE FROM auditor.actor_usr_history WHERE id = src_usr;
487         UPDATE auditor.asset_call_number_history SET creator = dest_usr WHERE creator = src_usr;
488         UPDATE auditor.asset_call_number_history SET editor  = dest_usr WHERE editor  = src_usr;
489         UPDATE auditor.asset_copy_history SET creator = dest_usr WHERE creator = src_usr;
490         UPDATE auditor.asset_copy_history SET editor  = dest_usr WHERE editor  = src_usr;
491         UPDATE auditor.biblio_record_entry_history SET creator = dest_usr WHERE creator = src_usr;
492         UPDATE auditor.biblio_record_entry_history SET editor  = dest_usr WHERE editor  = src_usr;
493
494         -- biblio.*
495         UPDATE biblio.record_entry SET creator = dest_usr WHERE creator = src_usr;
496         UPDATE biblio.record_entry SET editor = dest_usr WHERE editor = src_usr;
497         UPDATE biblio.record_note SET creator = dest_usr WHERE creator = src_usr;
498         UPDATE biblio.record_note SET editor = dest_usr WHERE editor = src_usr;
499
500         -- container.*
501         -- Update buckets with a rename to avoid collisions
502         FOR renamable_row in
503                 SELECT id, name
504                 FROM   container.biblio_record_entry_bucket
505                 WHERE  owner = src_usr
506         LOOP
507                 suffix := ' (' || src_usr || ')';
508                 LOOP
509                         BEGIN
510                                 UPDATE  container.biblio_record_entry_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.call_number_bucket
524                 WHERE  owner = src_usr
525         LOOP
526                 suffix := ' (' || src_usr || ')';
527                 LOOP
528                         BEGIN
529                                 UPDATE  container.call_number_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.copy_bucket
543                 WHERE  owner = src_usr
544         LOOP
545                 suffix := ' (' || src_usr || ')';
546                 LOOP
547                         BEGIN
548                                 UPDATE  container.copy_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         FOR renamable_row in
560                 SELECT id, name
561                 FROM   container.user_bucket
562                 WHERE  owner = src_usr
563         LOOP
564                 suffix := ' (' || src_usr || ')';
565                 LOOP
566                         BEGIN
567                                 UPDATE  container.user_bucket
568                                 SET     owner = dest_usr, name = name || suffix
569                                 WHERE   id = renamable_row.id;
570                         EXCEPTION WHEN unique_violation THEN
571                                 suffix := suffix || ' ';
572                                 CONTINUE;
573                         END;
574                         EXIT;
575                 END LOOP;
576         END LOOP;
577
578         DELETE FROM container.user_bucket_item WHERE target_user = src_usr;
579
580         -- money.*
581         DELETE FROM money.billable_xact WHERE usr = src_usr;
582         DELETE FROM money.collections_tracker WHERE usr = src_usr;
583         UPDATE money.collections_tracker SET collector = dest_usr WHERE collector = src_usr;
584
585         -- permission.*
586         DELETE FROM permission.usr_grp_map WHERE usr = src_usr;
587         DELETE FROM permission.usr_object_perm_map WHERE usr = src_usr;
588         DELETE FROM permission.usr_perm_map WHERE usr = src_usr;
589         DELETE FROM permission.usr_work_ou_map WHERE usr = src_usr;
590
591         -- reporter.*
592         -- Update with a rename to avoid collisions
593         BEGIN
594                 FOR renamable_row in
595                         SELECT id, name
596                         FROM   reporter.output_folder
597                         WHERE  owner = src_usr
598                 LOOP
599                         suffix := ' (' || src_usr || ')';
600                         LOOP
601                                 BEGIN
602                                         UPDATE  reporter.output_folder
603                                         SET     owner = dest_usr, name = name || suffix
604                                         WHERE   id = renamable_row.id;
605                                 EXCEPTION WHEN unique_violation THEN
606                                         suffix := suffix || ' ';
607                                         CONTINUE;
608                                 END;
609                                 EXIT;
610                         END LOOP;
611                 END LOOP;
612         EXCEPTION WHEN undefined_table THEN
613                 -- do nothing
614         END;
615
616         BEGIN
617                 UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
618         EXCEPTION WHEN undefined_table THEN
619                 -- do nothing
620         END;
621
622         -- Update with a rename to avoid collisions
623         BEGIN
624                 FOR renamable_row in
625                         SELECT id, name
626                         FROM   reporter.report_folder
627                         WHERE  owner = src_usr
628                 LOOP
629                         suffix := ' (' || src_usr || ')';
630                         LOOP
631                                 BEGIN
632                                         UPDATE  reporter.report_folder
633                                         SET     owner = dest_usr, name = name || suffix
634                                         WHERE   id = renamable_row.id;
635                                 EXCEPTION WHEN unique_violation THEN
636                                         suffix := suffix || ' ';
637                                         CONTINUE;
638                                 END;
639                                 EXIT;
640                         END LOOP;
641                 END LOOP;
642         EXCEPTION WHEN undefined_table THEN
643                 -- do nothing
644         END;
645
646         BEGIN
647                 UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
648         EXCEPTION WHEN undefined_table THEN
649                 -- do nothing
650         END;
651
652         BEGIN
653                 UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
654         EXCEPTION WHEN undefined_table THEN
655                 -- do nothing
656         END;
657
658         -- Update with a rename to avoid collisions
659         BEGIN
660                 FOR renamable_row in
661                         SELECT id, name
662                         FROM   reporter.template_folder
663                         WHERE  owner = src_usr
664                 LOOP
665                         suffix := ' (' || src_usr || ')';
666                         LOOP
667                                 BEGIN
668                                         UPDATE  reporter.template_folder
669                                         SET     owner = dest_usr, name = name || suffix
670                                         WHERE   id = renamable_row.id;
671                                 EXCEPTION WHEN unique_violation THEN
672                                         suffix := suffix || ' ';
673                                         CONTINUE;
674                                 END;
675                                 EXIT;
676                         END LOOP;
677                 END LOOP;
678         EXCEPTION WHEN undefined_table THEN
679         -- do nothing
680         END;
681
682         -- vandelay.*
683         -- Update with a rename to avoid collisions
684         FOR renamable_row in
685                 SELECT id, name
686                 FROM   vandelay.queue
687                 WHERE  owner = src_usr
688         LOOP
689                 suffix := ' (' || src_usr || ')';
690                 LOOP
691                         BEGIN
692                                 UPDATE  vandelay.queue
693                                 SET     owner = dest_usr, name = name || suffix
694                                 WHERE   id = renamable_row.id;
695                         EXCEPTION WHEN unique_violation THEN
696                                 suffix := suffix || ' ';
697                                 CONTINUE;
698                         END;
699                         EXIT;
700                 END LOOP;
701         END LOOP;
702
703     -- NULL-ify addresses last so other cleanup (e.g. circ anonymization)
704     -- can access the information before deletion.
705         UPDATE actor.usr SET
706                 active = FALSE,
707                 card = NULL,
708                 mailing_address = NULL,
709                 billing_address = NULL
710         WHERE id = src_usr;
711
712 END;
713 $$ LANGUAGE plpgsql;
714
715 COMMENT ON FUNCTION actor.usr_purge_data(INT, INT) IS $$
716 Finds rows dependent on a given row in actor.usr and either deletes them
717 or reassigns them to a different user.
718 $$;
719
720
721
722 CREATE OR REPLACE FUNCTION actor.usr_delete(
723         src_usr  IN INTEGER,
724         dest_usr IN INTEGER
725 ) RETURNS VOID AS $$
726 DECLARE
727         old_profile actor.usr.profile%type;
728         old_home_ou actor.usr.home_ou%type;
729         new_profile actor.usr.profile%type;
730         new_home_ou actor.usr.home_ou%type;
731         new_name    text;
732         new_dob     actor.usr.dob%type;
733 BEGIN
734         SELECT
735                 id || '-PURGED-' || now(),
736                 profile,
737                 home_ou,
738                 dob
739         INTO
740                 new_name,
741                 old_profile,
742                 old_home_ou,
743                 new_dob
744         FROM
745                 actor.usr
746         WHERE
747                 id = src_usr;
748         --
749         -- Quit if no such user
750         --
751         IF old_profile IS NULL THEN
752                 RETURN;
753         END IF;
754         --
755         perform actor.usr_purge_data( src_usr, dest_usr );
756         --
757         -- Find the root grp_tree and the root org_unit.  This would be simpler if we 
758         -- could assume that there is only one root.  Theoretically, someday, maybe,
759         -- there could be multiple roots, so we take extra trouble to get the right ones.
760         --
761         SELECT
762                 id
763         INTO
764                 new_profile
765         FROM
766                 permission.grp_ancestors( old_profile )
767         WHERE
768                 parent is null;
769         --
770         SELECT
771                 id
772         INTO
773                 new_home_ou
774         FROM
775                 actor.org_unit_ancestors( old_home_ou )
776         WHERE
777                 parent_ou is null;
778         --
779         -- Truncate date of birth
780         --
781         IF new_dob IS NOT NULL THEN
782                 new_dob := date_trunc( 'year', new_dob );
783         END IF;
784         --
785         UPDATE
786                 actor.usr
787                 SET
788                         card = NULL,
789                         profile = new_profile,
790                         usrname = new_name,
791                         email = NULL,
792                         passwd = random()::text,
793                         standing = DEFAULT,
794                         ident_type = 
795                         (
796                                 SELECT MIN( id )
797                                 FROM config.identification_type
798                         ),
799                         ident_value = NULL,
800                         ident_type2 = NULL,
801                         ident_value2 = NULL,
802                         net_access_level = DEFAULT,
803                         photo_url = NULL,
804                         prefix = NULL,
805                         first_given_name = new_name,
806                         second_given_name = NULL,
807                         family_name = new_name,
808                         suffix = NULL,
809                         alias = NULL,
810                         day_phone = NULL,
811                         evening_phone = NULL,
812                         other_phone = NULL,
813                         mailing_address = NULL,
814                         billing_address = NULL,
815                         home_ou = new_home_ou,
816                         dob = new_dob,
817                         active = FALSE,
818                         master_account = DEFAULT, 
819                         super_user = DEFAULT,
820                         barred = FALSE,
821                         deleted = TRUE,
822                         juvenile = DEFAULT,
823                         usrgroup = 0,
824                         claims_returned_count = DEFAULT,
825                         credit_forward_balance = DEFAULT,
826                         last_xact_id = DEFAULT,
827                         alert_message = NULL,
828                         create_date = now(),
829                         expire_date = now()
830         WHERE
831                 id = src_usr;
832 END;
833 $$ LANGUAGE plpgsql;
834
835 COMMENT ON FUNCTION actor.usr_delete(INT, INT) IS $$
836 Logically deletes a user.  Removes personally identifiable information,
837 and purges associated data in other tables.
838 $$;
839
840
841
842 CREATE OR REPLACE FUNCTION actor.approve_pending_address(pending_id INT) RETURNS BIGINT AS $$
843 DECLARE
844     old_id INT;
845 BEGIN
846     SELECT INTO old_id replaces FROM actor.usr_address where id = pending_id;
847     IF old_id IS NULL THEN
848         UPDATE actor.usr_address SET pending = 'f' WHERE id = pending_id;
849         RETURN pending_id;
850     END IF;
851     -- address replaces an existing address
852     DELETE FROM actor.usr_address WHERE id = -old_id;
853     UPDATE actor.usr_address SET id = -id WHERE id = old_id;
854     UPDATE actor.usr_address SET replaces = NULL, id = old_id, pending = 'f' WHERE id = pending_id;
855     RETURN old_id;
856 END
857 $$ LANGUAGE plpgsql;
858
859 COMMENT ON FUNCTION actor.approve_pending_address(INT) IS $$
860 Replaces an address with a pending address.  This is done by giving the pending 
861 address the ID of the old address.  The replaced address is retained with -id.
862 $$;
863
864 CREATE OR REPLACE FUNCTION container.clear_expired_circ_history_items( 
865          ac_usr IN INTEGER
866 ) RETURNS VOID AS $$
867 --
868 -- Delete old circulation bucket items for a specified user.
869 -- "Old" means older than the interval specified by a
870 -- user-level setting, if it is so specified.
871 --
872 DECLARE
873     threshold TIMESTAMP WITH TIME ZONE;
874 BEGIN
875         -- Sanity check
876         IF ac_usr IS NULL THEN
877                 RETURN;
878         END IF;
879         -- Determine the threshold date that defines "old".  Subtract the
880         -- interval from the system date, then truncate to midnight.
881         SELECT
882                 date_trunc( 
883                         'day',
884                         now() - CAST( translate( value, '"', '' ) AS INTERVAL )
885                 )
886         INTO
887                 threshold
888         FROM
889                 actor.usr_setting
890         WHERE
891                 usr = ac_usr
892                 AND name = 'patron.max_reading_list_interval';
893         --
894         IF threshold is null THEN
895                 -- No interval defined; don't delete anything
896                 -- RAISE NOTICE 'No interval defined for user %', ac_usr;
897                 return;
898         END IF;
899         --
900         -- RAISE NOTICE 'Date threshold: %', threshold;
901         --
902         -- Threshold found; do the delete
903         delete from container.copy_bucket_item
904         where
905                 bucket in
906                 (
907                         select
908                                 id
909                         from
910                                 container.copy_bucket
911                         where
912                                 owner = ac_usr
913                                 and btype = 'circ_history'
914                 )
915                 and create_time < threshold;
916         --
917         RETURN;
918 END;
919 $$ LANGUAGE plpgsql;
920
921 COMMENT ON FUNCTION container.clear_expired_circ_history_items( INTEGER ) IS $$
922 Delete old circulation bucket items for a specified user.
923 "Old" means older than the interval specified by a
924 user-level setting, if it is so specified.
925 $$;
926
927 CREATE OR REPLACE FUNCTION container.clear_all_expired_circ_history_items( )
928 RETURNS VOID AS $$
929 --
930 -- Delete expired circulation bucket items for all users that have
931 -- a setting for patron.max_reading_list_interval.
932 --
933 DECLARE
934     today        TIMESTAMP WITH TIME ZONE;
935     threshold    TIMESTAMP WITH TIME ZONE;
936         usr_setting  RECORD;
937 BEGIN
938         SELECT date_trunc( 'day', now() ) INTO today;
939         --
940         FOR usr_setting in
941                 SELECT
942                         usr,
943                         value
944                 FROM
945                         actor.usr_setting
946                 WHERE
947                         name = 'patron.max_reading_list_interval'
948         LOOP
949                 --
950                 -- Make sure the setting is a valid interval
951                 --
952                 BEGIN
953                         threshold := today - CAST( translate( usr_setting.value, '"', '' ) AS INTERVAL );
954                 EXCEPTION
955                         WHEN OTHERS THEN
956                                 RAISE NOTICE 'Invalid setting patron.max_reading_list_interval for user %: ''%''',
957                                         usr_setting.usr, usr_setting.value;
958                                 CONTINUE;
959                 END;
960                 --
961                 --RAISE NOTICE 'User % threshold %', usr_setting.usr, threshold;
962                 --
963         DELETE FROM container.copy_bucket_item
964         WHERE
965                 bucket IN
966                 (
967                     SELECT
968                         id
969                     FROM
970                         container.copy_bucket
971                     WHERE
972                         owner = usr_setting.usr
973                         AND btype = 'circ_history'
974                 )
975                 AND create_time < threshold;
976         END LOOP;
977         --
978 END;
979 $$ LANGUAGE plpgsql;
980
981 COMMENT ON FUNCTION container.clear_all_expired_circ_history_items( ) IS $$
982 Delete expired circulation bucket items for all users that have
983 a setting for patron.max_reading_list_interval.
984 $$;
985
986 CREATE OR REPLACE FUNCTION asset.merge_record_assets( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
987 DECLARE
988     moved_objects INT := 0;
989     source_cn     asset.call_number%ROWTYPE;
990     target_cn     asset.call_number%ROWTYPE;
991     metarec       metabib.metarecord%ROWTYPE;
992     hold          action.hold_request%ROWTYPE;
993     ser_rec       serial.record_entry%ROWTYPE;
994     ser_sub       serial.subscription%ROWTYPE;
995     acq_lineitem  acq.lineitem%ROWTYPE;
996     acq_request   acq.user_request%ROWTYPE;
997     booking       booking.resource_type%ROWTYPE;
998     source_part   biblio.monograph_part%ROWTYPE;
999     target_part   biblio.monograph_part%ROWTYPE;
1000     multi_home    biblio.peer_bib_copy_map%ROWTYPE;
1001     uri_count     INT := 0;
1002     counter       INT := 0;
1003     uri_datafield TEXT;
1004     uri_text      TEXT := '';
1005 BEGIN
1006
1007     -- move any 856 entries on records that have at least one MARC-mapped URI entry
1008     SELECT  INTO uri_count COUNT(*)
1009       FROM  asset.uri_call_number_map m
1010             JOIN asset.call_number cn ON (m.call_number = cn.id)
1011       WHERE cn.record = source_record;
1012
1013     IF uri_count > 0 THEN
1014         
1015         -- This returns more nodes than you might expect:
1016         -- 7 instead of 1 for an 856 with $u $y $9
1017         SELECT  COUNT(*) INTO counter
1018           FROM  oils_xpath_table(
1019                     'id',
1020                     'marc',
1021                     'biblio.record_entry',
1022                     '//*[@tag="856"]',
1023                     'id=' || source_record
1024                 ) as t(i int,c text);
1025     
1026         FOR i IN 1 .. counter LOOP
1027             SELECT  '<datafield xmlns="http://www.loc.gov/MARC21/slim"' || 
1028                         ' tag="856"' ||
1029                         ' ind1="' || FIRST(ind1) || '"'  ||
1030                         ' ind2="' || FIRST(ind2) || '">' ||
1031                         STRING_AGG(
1032                             '<subfield code="' || subfield || '">' ||
1033                             regexp_replace(
1034                                 regexp_replace(
1035                                     regexp_replace(data,'&','&amp;','g'),
1036                                     '>', '&gt;', 'g'
1037                                 ),
1038                                 '<', '&lt;', 'g'
1039                             ) || '</subfield>', ''
1040                         ) || '</datafield>' INTO uri_datafield
1041               FROM  oils_xpath_table(
1042                         'id',
1043                         'marc',
1044                         'biblio.record_entry',
1045                         '//*[@tag="856"][position()=' || i || ']/@ind1|' ||
1046                         '//*[@tag="856"][position()=' || i || ']/@ind2|' ||
1047                         '//*[@tag="856"][position()=' || i || ']/*/@code|' ||
1048                         '//*[@tag="856"][position()=' || i || ']/*[@code]',
1049                         'id=' || source_record
1050                     ) as t(id int,ind1 text, ind2 text,subfield text,data text);
1051
1052             -- As most of the results will be NULL, protect against NULLifying
1053             -- the valid content that we do generate
1054             uri_text := uri_text || COALESCE(uri_datafield, '');
1055         END LOOP;
1056
1057         IF uri_text <> '' THEN
1058             UPDATE  biblio.record_entry
1059               SET   marc = regexp_replace(marc,'(</[^>]*record>)', uri_text || E'\\1')
1060               WHERE id = target_record;
1061         END IF;
1062
1063     END IF;
1064
1065         -- Find and move metarecords to the target record
1066         SELECT  INTO metarec *
1067           FROM  metabib.metarecord
1068           WHERE master_record = source_record;
1069
1070         IF FOUND THEN
1071                 UPDATE  metabib.metarecord
1072                   SET   master_record = target_record,
1073                         mods = NULL
1074                   WHERE id = metarec.id;
1075
1076                 moved_objects := moved_objects + 1;
1077         END IF;
1078
1079         -- Find call numbers attached to the source ...
1080         FOR source_cn IN SELECT * FROM asset.call_number WHERE record = source_record LOOP
1081
1082                 SELECT  INTO target_cn *
1083                   FROM  asset.call_number
1084                   WHERE label = source_cn.label
1085             AND prefix = source_cn.prefix
1086             AND suffix = source_cn.suffix
1087                         AND owning_lib = source_cn.owning_lib
1088                         AND record = target_record
1089                         AND NOT deleted;
1090
1091                 -- ... and if there's a conflicting one on the target ...
1092                 IF FOUND THEN
1093
1094                         -- ... move the copies to that, and ...
1095                         UPDATE  asset.copy
1096                           SET   call_number = target_cn.id
1097                           WHERE call_number = source_cn.id;
1098
1099                         -- ... move V holds to the move-target call number
1100                         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_cn.id AND hold_type = 'V' LOOP
1101                 
1102                                 UPDATE  action.hold_request
1103                                   SET   target = target_cn.id
1104                                   WHERE id = hold.id;
1105                 
1106                                 moved_objects := moved_objects + 1;
1107                         END LOOP;
1108         
1109             UPDATE asset.call_number SET deleted = TRUE WHERE id = source_cn.id;
1110
1111                 -- ... if not ...
1112                 ELSE
1113                         -- ... just move the call number to the target record
1114                         UPDATE  asset.call_number
1115                           SET   record = target_record
1116                           WHERE id = source_cn.id;
1117                 END IF;
1118
1119                 moved_objects := moved_objects + 1;
1120         END LOOP;
1121
1122         -- Find T holds targeting the source record ...
1123         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_record AND hold_type = 'T' LOOP
1124
1125                 -- ... and move them to the target record
1126                 UPDATE  action.hold_request
1127                   SET   target = target_record
1128                   WHERE id = hold.id;
1129
1130                 moved_objects := moved_objects + 1;
1131         END LOOP;
1132
1133         -- Find serial records targeting the source record ...
1134         FOR ser_rec IN SELECT * FROM serial.record_entry WHERE record = source_record LOOP
1135                 -- ... and move them to the target record
1136                 UPDATE  serial.record_entry
1137                   SET   record = target_record
1138                   WHERE id = ser_rec.id;
1139
1140                 moved_objects := moved_objects + 1;
1141         END LOOP;
1142
1143         -- Find serial subscriptions targeting the source record ...
1144         FOR ser_sub IN SELECT * FROM serial.subscription WHERE record_entry = source_record LOOP
1145                 -- ... and move them to the target record
1146                 UPDATE  serial.subscription
1147                   SET   record_entry = target_record
1148                   WHERE id = ser_sub.id;
1149
1150                 moved_objects := moved_objects + 1;
1151         END LOOP;
1152
1153         -- Find booking resource types targeting the source record ...
1154         FOR booking IN SELECT * FROM booking.resource_type WHERE record = source_record LOOP
1155                 -- ... and move them to the target record
1156                 UPDATE  booking.resource_type
1157                   SET   record = target_record
1158                   WHERE id = booking.id;
1159
1160                 moved_objects := moved_objects + 1;
1161         END LOOP;
1162
1163         -- Find acq lineitems targeting the source record ...
1164         FOR acq_lineitem IN SELECT * FROM acq.lineitem WHERE eg_bib_id = source_record LOOP
1165                 -- ... and move them to the target record
1166                 UPDATE  acq.lineitem
1167                   SET   eg_bib_id = target_record
1168                   WHERE id = acq_lineitem.id;
1169
1170                 moved_objects := moved_objects + 1;
1171         END LOOP;
1172
1173         -- Find acq user purchase requests targeting the source record ...
1174         FOR acq_request IN SELECT * FROM acq.user_request WHERE eg_bib = source_record LOOP
1175                 -- ... and move them to the target record
1176                 UPDATE  acq.user_request
1177                   SET   eg_bib = target_record
1178                   WHERE id = acq_request.id;
1179
1180                 moved_objects := moved_objects + 1;
1181         END LOOP;
1182
1183         -- Find parts attached to the source ...
1184         FOR source_part IN SELECT * FROM biblio.monograph_part WHERE record = source_record LOOP
1185
1186                 SELECT  INTO target_part *
1187                   FROM  biblio.monograph_part
1188                   WHERE label = source_part.label
1189                         AND record = target_record;
1190
1191                 -- ... and if there's a conflicting one on the target ...
1192                 IF FOUND THEN
1193
1194                         -- ... move the copy-part maps to that, and ...
1195                         UPDATE  asset.copy_part_map
1196                           SET   part = target_part.id
1197                           WHERE part = source_part.id;
1198
1199                         -- ... move P holds to the move-target part
1200                         FOR hold IN SELECT * FROM action.hold_request WHERE target = source_part.id AND hold_type = 'P' LOOP
1201                 
1202                                 UPDATE  action.hold_request
1203                                   SET   target = target_part.id
1204                                   WHERE id = hold.id;
1205                 
1206                                 moved_objects := moved_objects + 1;
1207                         END LOOP;
1208
1209                 -- ... if not ...
1210                 ELSE
1211                         -- ... just move the part to the target record
1212                         UPDATE  biblio.monograph_part
1213                           SET   record = target_record
1214                           WHERE id = source_part.id;
1215                 END IF;
1216
1217                 moved_objects := moved_objects + 1;
1218         END LOOP;
1219
1220         -- Find multi_home items attached to the source ...
1221         FOR multi_home IN SELECT * FROM biblio.peer_bib_copy_map WHERE peer_record = source_record LOOP
1222                 -- ... and move them to the target record
1223                 UPDATE  biblio.peer_bib_copy_map
1224                   SET   peer_record = target_record
1225                   WHERE id = multi_home.id;
1226
1227                 moved_objects := moved_objects + 1;
1228         END LOOP;
1229
1230         -- And delete mappings where the item's home bib was merged with the peer bib
1231         DELETE FROM biblio.peer_bib_copy_map WHERE peer_record = (
1232                 SELECT (SELECT record FROM asset.call_number WHERE id = call_number)
1233                 FROM asset.copy WHERE id = target_copy
1234         );
1235
1236     -- Apply merge tracking
1237     UPDATE biblio.record_entry 
1238         SET merge_date = NOW() WHERE id = target_record;
1239
1240     UPDATE biblio.record_entry
1241         SET merge_date = NOW(), merged_to = target_record
1242         WHERE id = source_record;
1243
1244     -- replace book bag entries of source_record with target_record
1245     UPDATE container.biblio_record_entry_bucket_item
1246         SET target_biblio_record_entry = target_record
1247         WHERE bucket IN (SELECT id FROM container.biblio_record_entry_bucket WHERE btype = 'bookbag')
1248         AND target_biblio_record_entry = source_record;
1249
1250     -- Finally, "delete" the source record
1251     DELETE FROM biblio.record_entry WHERE id = source_record;
1252
1253         -- That's all, folks!
1254         RETURN moved_objects;
1255 END;
1256 $func$ LANGUAGE plpgsql;
1257
1258 -- Authority ingest routines
1259 CREATE OR REPLACE FUNCTION authority.propagate_changes 
1260     (aid BIGINT, bid BIGINT) RETURNS BIGINT AS $func$
1261 DECLARE
1262     bib_rec biblio.record_entry%ROWTYPE;
1263     new_marc TEXT;
1264 BEGIN
1265
1266     SELECT INTO bib_rec * FROM biblio.record_entry WHERE id = bid;
1267
1268     new_marc := vandelay.merge_record_xml(
1269         bib_rec.marc, authority.generate_overlay_template(aid));
1270
1271     IF new_marc = bib_rec.marc THEN
1272         -- Authority record change had no impact on this bib record.
1273         -- Nothing left to do.
1274         RETURN aid;
1275     END IF;
1276
1277     PERFORM 1 FROM config.global_flag 
1278         WHERE name = 'ingest.disable_authority_auto_update_bib_meta' 
1279             AND enabled;
1280
1281     IF NOT FOUND THEN 
1282         -- update the bib record editor and edit_date
1283         bib_rec.editor := (
1284             SELECT editor FROM authority.record_entry WHERE id = aid);
1285         bib_rec.edit_date = NOW();
1286     END IF;
1287
1288     UPDATE biblio.record_entry SET
1289         marc = new_marc,
1290         editor = bib_rec.editor,
1291         edit_date = bib_rec.edit_date
1292     WHERE id = bid;
1293
1294     RETURN aid;
1295
1296 END;
1297 $func$ LANGUAGE PLPGSQL;
1298
1299 CREATE OR REPLACE FUNCTION authority.propagate_changes (aid BIGINT) RETURNS SETOF BIGINT AS $func$
1300     SELECT authority.propagate_changes( authority, bib ) FROM authority.bib_linking WHERE authority = $1;
1301 $func$ LANGUAGE SQL;
1302
1303 CREATE OR REPLACE FUNCTION authority.map_thesaurus_to_control_set () RETURNS TRIGGER AS $func$
1304 BEGIN
1305     IF NEW.control_set IS NULL THEN
1306         SELECT  control_set INTO NEW.control_set
1307           FROM  authority.thesaurus
1308           WHERE authority.extract_thesaurus(NEW.marc) = code;
1309     END IF;
1310
1311     RETURN NEW;
1312 END;
1313 $func$ LANGUAGE PLPGSQL;
1314
1315 CREATE OR REPLACE FUNCTION authority.reingest_authority_rec_descriptor( auth_id BIGINT ) RETURNS VOID AS $func$
1316 BEGIN
1317     DELETE FROM authority.rec_descriptor WHERE record = auth_id;
1318     INSERT INTO authority.rec_descriptor (record, record_status, encoding_level, thesaurus)
1319         SELECT  auth_id,
1320                 vandelay.marc21_extract_fixed_field(marc,'RecStat'),
1321                 vandelay.marc21_extract_fixed_field(marc,'ELvl'),
1322                 authority.extract_thesaurus(marc)
1323           FROM  authority.record_entry
1324           WHERE id = auth_id;
1325     RETURN;
1326 END;
1327 $func$ LANGUAGE PLPGSQL;
1328
1329 CREATE OR REPLACE FUNCTION authority.reingest_authority_full_rec( auth_id BIGINT ) RETURNS VOID AS $func$
1330 BEGIN
1331     DELETE FROM authority.full_rec WHERE record = auth_id;
1332     INSERT INTO authority.full_rec (record, tag, ind1, ind2, subfield, value)
1333         SELECT record, tag, ind1, ind2, subfield, value FROM authority.flatten_marc( auth_id );
1334
1335     RETURN;
1336 END;
1337 $func$ LANGUAGE PLPGSQL;
1338
1339 -- Given an authority record's ID, control set ID (if known), and marc::XML,
1340 -- return all links to other authority records in the form of rows that
1341 -- can be inserted into authority.authority_linking.
1342 CREATE OR REPLACE FUNCTION authority.calculate_authority_linking(
1343     rec_id BIGINT, rec_control_set INT, rec_marc_xml XML
1344 ) RETURNS SETOF authority.authority_linking AS $func$
1345 DECLARE
1346     acsaf       authority.control_set_authority_field%ROWTYPE;
1347     link        TEXT;
1348     aal         authority.authority_linking%ROWTYPE;
1349 BEGIN
1350     IF rec_control_set IS NULL THEN
1351         -- No control_set on record?  Guess at one
1352         SELECT control_set INTO rec_control_set
1353             FROM authority.control_set_authority_field
1354             WHERE tag IN (
1355                 SELECT UNNEST(
1356                     XPATH('//*[starts-with(@tag,"1")]/@tag',rec_marc_xml)::TEXT[]
1357                 )
1358             ) LIMIT 1;
1359
1360         IF NOT FOUND THEN
1361             RAISE WARNING 'Could not even guess at control set for authority record %', rec_id;
1362             RETURN;
1363         END IF;
1364     END IF;
1365
1366     aal.source := rec_id;
1367
1368     FOR acsaf IN
1369         SELECT * FROM authority.control_set_authority_field
1370         WHERE control_set = rec_control_set
1371             AND linking_subfield IS NOT NULL
1372             AND main_entry IS NOT NULL
1373     LOOP
1374         -- Loop over the trailing-number contents of all linking subfields
1375         FOR link IN
1376             SELECT  SUBSTRING( x::TEXT, '\d+$' )
1377               FROM  UNNEST(
1378                         XPATH(
1379                             '//*[@tag="'
1380                                 || acsaf.tag
1381                                 || '"]/*[@code="'
1382                                 || acsaf.linking_subfield
1383                                 || '"]/text()',
1384                             rec_marc_xml
1385                         )
1386                     ) x
1387         LOOP
1388
1389             -- Ignore links that are null, malformed, circular, or point to
1390             -- non-existent authority records.
1391             IF link IS NOT NULL AND link::BIGINT <> rec_id THEN
1392                 PERFORM * FROM authority.record_entry WHERE id = link::BIGINT;
1393                 IF FOUND THEN
1394                     aal.target := link::BIGINT;
1395                     aal.field := acsaf.id;
1396                     RETURN NEXT aal;
1397                 END IF;
1398             END IF;
1399         END LOOP;
1400     END LOOP;
1401 END;
1402 $func$ LANGUAGE PLPGSQL;
1403
1404 -- AFTER UPDATE OR INSERT trigger for authority.record_entry
1405 CREATE OR REPLACE FUNCTION authority.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
1406 DECLARE
1407     ashs    authority.simple_heading%ROWTYPE;
1408     mbe_row metabib.browse_entry%ROWTYPE;
1409     mbe_id  BIGINT;
1410     ash_id  BIGINT;
1411 BEGIN
1412
1413     IF NEW.deleted IS TRUE THEN -- If this authority is deleted
1414         DELETE FROM authority.bib_linking WHERE authority = NEW.id; -- Avoid updating fields in bibs that are no longer visible
1415         DELETE FROM authority.full_rec WHERE record = NEW.id; -- Avoid validating fields against deleted authority records
1416         DELETE FROM authority.simple_heading WHERE record = NEW.id;
1417           -- Should remove matching $0 from controlled fields at the same time?
1418
1419         -- XXX What do we about the actual linking subfields present in
1420         -- authority records that target this one when this happens?
1421         DELETE FROM authority.authority_linking
1422             WHERE source = NEW.id OR target = NEW.id;
1423
1424         RETURN NEW; -- and we're done
1425     END IF;
1426
1427     IF TG_OP = 'UPDATE' THEN -- re-ingest?
1428         PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
1429
1430         IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
1431             RETURN NEW;
1432         END IF;
1433
1434         -- Unless there's a setting stopping us, propagate these updates to any linked bib records when the heading changes
1435         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_auto_update' AND enabled;
1436
1437         IF NOT FOUND AND NEW.heading <> OLD.heading THEN
1438             PERFORM authority.propagate_changes(NEW.id);
1439         END IF;
1440         
1441         DELETE FROM authority.simple_heading WHERE record = NEW.id;
1442         DELETE FROM authority.authority_linking WHERE source = NEW.id;
1443     END IF;
1444
1445     INSERT INTO authority.authority_linking (source, target, field)
1446         SELECT source, target, field FROM authority.calculate_authority_linking(
1447             NEW.id, NEW.control_set, NEW.marc::XML
1448         );
1449
1450     FOR ashs IN SELECT * FROM authority.simple_heading_set(NEW.marc) LOOP
1451
1452         INSERT INTO authority.simple_heading (record,atag,value,sort_value,thesaurus)
1453             VALUES (ashs.record, ashs.atag, ashs.value, ashs.sort_value, ashs.thesaurus);
1454             ash_id := CURRVAL('authority.simple_heading_id_seq'::REGCLASS);
1455
1456         SELECT INTO mbe_row * FROM metabib.browse_entry
1457             WHERE value = ashs.value AND sort_value = ashs.sort_value;
1458
1459         IF FOUND THEN
1460             mbe_id := mbe_row.id;
1461         ELSE
1462             INSERT INTO metabib.browse_entry
1463                 ( value, sort_value ) VALUES
1464                 ( ashs.value, ashs.sort_value );
1465
1466             mbe_id := CURRVAL('metabib.browse_entry_id_seq'::REGCLASS);
1467         END IF;
1468
1469         INSERT INTO metabib.browse_entry_simple_heading_map (entry,simple_heading) VALUES (mbe_id,ash_id);
1470
1471     END LOOP;
1472
1473     -- Flatten and insert the afr data
1474     PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_full_rec' AND enabled;
1475     IF NOT FOUND THEN
1476         PERFORM authority.reingest_authority_full_rec(NEW.id);
1477         PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_rec_descriptor' AND enabled;
1478         IF NOT FOUND THEN
1479             PERFORM authority.reingest_authority_rec_descriptor(NEW.id);
1480         END IF;
1481     END IF;
1482
1483     RETURN NEW;
1484 END;
1485 $func$ LANGUAGE PLPGSQL;
1486
1487 -- Ingest triggers
1488 CREATE TRIGGER fingerprint_tgr BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.fingerprint_trigger ('eng','BKS');
1489 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 ();
1490 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 ();
1491
1492 CREATE TRIGGER map_thesaurus_to_control_set BEFORE INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE authority.map_thesaurus_to_control_set ();
1493 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 ();
1494
1495 -- Utility routines, callable via cstore
1496
1497 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_val INTERVAL )
1498 RETURNS INTEGER AS $$
1499 BEGIN
1500         RETURN EXTRACT( EPOCH FROM interval_val );
1501 END;
1502 $$ LANGUAGE plpgsql;
1503
1504 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_string TEXT )
1505 RETURNS INTEGER AS $$
1506 BEGIN
1507         RETURN config.interval_to_seconds( interval_string::INTERVAL );
1508 END;
1509 $$ LANGUAGE plpgsql;
1510
1511 CREATE OR REPLACE FUNCTION vandelay.ingest_items ( import_id BIGINT, attr_def_id BIGINT ) RETURNS SETOF vandelay.import_item AS $$
1512 DECLARE
1513
1514     owning_lib      TEXT;
1515     circ_lib        TEXT;
1516     call_number     TEXT;
1517     copy_number     TEXT;
1518     status          TEXT;
1519     location        TEXT;
1520     circulate       TEXT;
1521     deposit         TEXT;
1522     deposit_amount  TEXT;
1523     ref             TEXT;
1524     holdable        TEXT;
1525     price           TEXT;
1526     barcode         TEXT;
1527     circ_modifier   TEXT;
1528     circ_as_type    TEXT;
1529     alert_message   TEXT;
1530     opac_visible    TEXT;
1531     pub_note        TEXT;
1532     priv_note       TEXT;
1533     internal_id     TEXT;
1534     stat_cat_data   TEXT;
1535     parts_data      TEXT;
1536
1537     attr_def        RECORD;
1538     tmp_attr_set    RECORD;
1539     attr_set        vandelay.import_item%ROWTYPE;
1540
1541     xpaths          TEXT[];
1542     tmp_str         TEXT;
1543
1544 BEGIN
1545
1546     SELECT * INTO attr_def FROM vandelay.import_item_attr_definition WHERE id = attr_def_id;
1547
1548     IF FOUND THEN
1549
1550         attr_set.definition := attr_def.id;
1551
1552         -- Build the combined XPath
1553
1554         owning_lib :=
1555             CASE
1556                 WHEN attr_def.owning_lib IS NULL THEN 'null()'
1557                 WHEN LENGTH( attr_def.owning_lib ) = 1 THEN '*[@code="' || attr_def.owning_lib || '"]'
1558                 ELSE '*' || attr_def.owning_lib
1559             END;
1560
1561         circ_lib :=
1562             CASE
1563                 WHEN attr_def.circ_lib IS NULL THEN 'null()'
1564                 WHEN LENGTH( attr_def.circ_lib ) = 1 THEN '*[@code="' || attr_def.circ_lib || '"]'
1565                 ELSE '*' || attr_def.circ_lib
1566             END;
1567
1568         call_number :=
1569             CASE
1570                 WHEN attr_def.call_number IS NULL THEN 'null()'
1571                 WHEN LENGTH( attr_def.call_number ) = 1 THEN '*[@code="' || attr_def.call_number || '"]'
1572                 ELSE '*' || attr_def.call_number
1573             END;
1574
1575         copy_number :=
1576             CASE
1577                 WHEN attr_def.copy_number IS NULL THEN 'null()'
1578                 WHEN LENGTH( attr_def.copy_number ) = 1 THEN '*[@code="' || attr_def.copy_number || '"]'
1579                 ELSE '*' || attr_def.copy_number
1580             END;
1581
1582         status :=
1583             CASE
1584                 WHEN attr_def.status IS NULL THEN 'null()'
1585                 WHEN LENGTH( attr_def.status ) = 1 THEN '*[@code="' || attr_def.status || '"]'
1586                 ELSE '*' || attr_def.status
1587             END;
1588
1589         location :=
1590             CASE
1591                 WHEN attr_def.location IS NULL THEN 'null()'
1592                 WHEN LENGTH( attr_def.location ) = 1 THEN '*[@code="' || attr_def.location || '"]'
1593                 ELSE '*' || attr_def.location
1594             END;
1595
1596         circulate :=
1597             CASE
1598                 WHEN attr_def.circulate IS NULL THEN 'null()'
1599                 WHEN LENGTH( attr_def.circulate ) = 1 THEN '*[@code="' || attr_def.circulate || '"]'
1600                 ELSE '*' || attr_def.circulate
1601             END;
1602
1603         deposit :=
1604             CASE
1605                 WHEN attr_def.deposit IS NULL THEN 'null()'
1606                 WHEN LENGTH( attr_def.deposit ) = 1 THEN '*[@code="' || attr_def.deposit || '"]'
1607                 ELSE '*' || attr_def.deposit
1608             END;
1609
1610         deposit_amount :=
1611             CASE
1612                 WHEN attr_def.deposit_amount IS NULL THEN 'null()'
1613                 WHEN LENGTH( attr_def.deposit_amount ) = 1 THEN '*[@code="' || attr_def.deposit_amount || '"]'
1614                 ELSE '*' || attr_def.deposit_amount
1615             END;
1616
1617         ref :=
1618             CASE
1619                 WHEN attr_def.ref IS NULL THEN 'null()'
1620                 WHEN LENGTH( attr_def.ref ) = 1 THEN '*[@code="' || attr_def.ref || '"]'
1621                 ELSE '*' || attr_def.ref
1622             END;
1623
1624         holdable :=
1625             CASE
1626                 WHEN attr_def.holdable IS NULL THEN 'null()'
1627                 WHEN LENGTH( attr_def.holdable ) = 1 THEN '*[@code="' || attr_def.holdable || '"]'
1628                 ELSE '*' || attr_def.holdable
1629             END;
1630
1631         price :=
1632             CASE
1633                 WHEN attr_def.price IS NULL THEN 'null()'
1634                 WHEN LENGTH( attr_def.price ) = 1 THEN '*[@code="' || attr_def.price || '"]'
1635                 ELSE '*' || attr_def.price
1636             END;
1637
1638         barcode :=
1639             CASE
1640                 WHEN attr_def.barcode IS NULL THEN 'null()'
1641                 WHEN LENGTH( attr_def.barcode ) = 1 THEN '*[@code="' || attr_def.barcode || '"]'
1642                 ELSE '*' || attr_def.barcode
1643             END;
1644
1645         circ_modifier :=
1646             CASE
1647                 WHEN attr_def.circ_modifier IS NULL THEN 'null()'
1648                 WHEN LENGTH( attr_def.circ_modifier ) = 1 THEN '*[@code="' || attr_def.circ_modifier || '"]'
1649                 ELSE '*' || attr_def.circ_modifier
1650             END;
1651
1652         circ_as_type :=
1653             CASE
1654                 WHEN attr_def.circ_as_type IS NULL THEN 'null()'
1655                 WHEN LENGTH( attr_def.circ_as_type ) = 1 THEN '*[@code="' || attr_def.circ_as_type || '"]'
1656                 ELSE '*' || attr_def.circ_as_type
1657             END;
1658
1659         alert_message :=
1660             CASE
1661                 WHEN attr_def.alert_message IS NULL THEN 'null()'
1662                 WHEN LENGTH( attr_def.alert_message ) = 1 THEN '*[@code="' || attr_def.alert_message || '"]'
1663                 ELSE '*' || attr_def.alert_message
1664             END;
1665
1666         opac_visible :=
1667             CASE
1668                 WHEN attr_def.opac_visible IS NULL THEN 'null()'
1669                 WHEN LENGTH( attr_def.opac_visible ) = 1 THEN '*[@code="' || attr_def.opac_visible || '"]'
1670                 ELSE '*' || attr_def.opac_visible
1671             END;
1672
1673         pub_note :=
1674             CASE
1675                 WHEN attr_def.pub_note IS NULL THEN 'null()'
1676                 WHEN LENGTH( attr_def.pub_note ) = 1 THEN '*[@code="' || attr_def.pub_note || '"]'
1677                 ELSE '*' || attr_def.pub_note
1678             END;
1679         priv_note :=
1680             CASE
1681                 WHEN attr_def.priv_note IS NULL THEN 'null()'
1682                 WHEN LENGTH( attr_def.priv_note ) = 1 THEN '*[@code="' || attr_def.priv_note || '"]'
1683                 ELSE '*' || attr_def.priv_note
1684             END;
1685
1686         internal_id :=
1687             CASE
1688                 WHEN attr_def.internal_id IS NULL THEN 'null()'
1689                 WHEN LENGTH( attr_def.internal_id ) = 1 THEN '*[@code="' || attr_def.internal_id || '"]'
1690                 ELSE '*' || attr_def.internal_id
1691             END;
1692
1693         stat_cat_data :=
1694             CASE
1695                 WHEN attr_def.stat_cat_data IS NULL THEN 'null()'
1696                 WHEN LENGTH( attr_def.stat_cat_data ) = 1 THEN '*[@code="' || attr_def.stat_cat_data || '"]'
1697                 ELSE '*' || attr_def.stat_cat_data
1698             END;
1699
1700         parts_data :=
1701             CASE
1702                 WHEN attr_def.parts_data IS NULL THEN 'null()'
1703                 WHEN LENGTH( attr_def.parts_data ) = 1 THEN '*[@code="' || attr_def.parts_data || '"]'
1704                 ELSE '*' || attr_def.parts_data
1705             END;
1706
1707
1708
1709         xpaths := ARRAY[owning_lib, circ_lib, call_number, copy_number, status, location, circulate,
1710                         deposit, deposit_amount, ref, holdable, price, barcode, circ_modifier, circ_as_type,
1711                         alert_message, pub_note, priv_note, internal_id, stat_cat_data, parts_data, opac_visible];
1712
1713         FOR tmp_attr_set IN
1714                 SELECT  *
1715                   FROM  oils_xpath_tag_to_table( (SELECT marc FROM vandelay.queued_bib_record WHERE id = import_id), attr_def.tag, xpaths)
1716                             AS t( ol TEXT, clib TEXT, cn TEXT, cnum TEXT, cs TEXT, cl TEXT, circ TEXT,
1717                                   dep TEXT, dep_amount TEXT, r TEXT, hold TEXT, pr TEXT, bc TEXT, circ_mod TEXT,
1718                                   circ_as TEXT, amessage TEXT, note TEXT, pnote TEXT, internal_id TEXT,
1719                                   stat_cat_data TEXT, parts_data TEXT, opac_vis TEXT )
1720         LOOP
1721
1722             attr_set.import_error := NULL;
1723             attr_set.error_detail := NULL;
1724             attr_set.deposit_amount := NULL;
1725             attr_set.copy_number := NULL;
1726             attr_set.price := NULL;
1727             attr_set.circ_modifier := NULL;
1728             attr_set.location := NULL;
1729             attr_set.barcode := NULL;
1730             attr_set.call_number := NULL;
1731
1732             IF tmp_attr_set.pr != '' THEN
1733                 tmp_str = REGEXP_REPLACE(tmp_attr_set.pr, E'[^0-9\\.]', '', 'g');
1734                 IF tmp_str = '' THEN 
1735                     attr_set.import_error := 'import.item.invalid.price';
1736                     attr_set.error_detail := tmp_attr_set.pr; -- original value
1737                     RETURN NEXT attr_set; CONTINUE; 
1738                 END IF;
1739                 attr_set.price := tmp_str::NUMERIC(8,2); 
1740             END IF;
1741
1742             IF tmp_attr_set.dep_amount != '' THEN
1743                 tmp_str = REGEXP_REPLACE(tmp_attr_set.dep_amount, E'[^0-9\\.]', '', 'g');
1744                 IF tmp_str = '' THEN 
1745                     attr_set.import_error := 'import.item.invalid.deposit_amount';
1746                     attr_set.error_detail := tmp_attr_set.dep_amount; 
1747                     RETURN NEXT attr_set; CONTINUE; 
1748                 END IF;
1749                 attr_set.deposit_amount := tmp_str::NUMERIC(8,2); 
1750             END IF;
1751
1752             IF tmp_attr_set.cnum != '' THEN
1753                 tmp_str = REGEXP_REPLACE(tmp_attr_set.cnum, E'[^0-9]', '', 'g');
1754                 IF tmp_str = '' THEN 
1755                     attr_set.import_error := 'import.item.invalid.copy_number';
1756                     attr_set.error_detail := tmp_attr_set.cnum; 
1757                     RETURN NEXT attr_set; CONTINUE; 
1758                 END IF;
1759                 attr_set.copy_number := tmp_str::INT; 
1760             END IF;
1761
1762             IF tmp_attr_set.ol != '' THEN
1763                 SELECT id INTO attr_set.owning_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.ol); -- INT
1764                 IF NOT FOUND THEN
1765                     attr_set.import_error := 'import.item.invalid.owning_lib';
1766                     attr_set.error_detail := tmp_attr_set.ol;
1767                     RETURN NEXT attr_set; CONTINUE; 
1768                 END IF;
1769             END IF;
1770
1771             IF tmp_attr_set.clib != '' THEN
1772                 SELECT id INTO attr_set.circ_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.clib); -- INT
1773                 IF NOT FOUND THEN
1774                     attr_set.import_error := 'import.item.invalid.circ_lib';
1775                     attr_set.error_detail := tmp_attr_set.clib;
1776                     RETURN NEXT attr_set; CONTINUE; 
1777                 END IF;
1778             END IF;
1779
1780             IF tmp_attr_set.cs != '' THEN
1781                 SELECT id INTO attr_set.status FROM config.copy_status WHERE LOWER(name) = LOWER(tmp_attr_set.cs); -- INT
1782                 IF NOT FOUND THEN
1783                     attr_set.import_error := 'import.item.invalid.status';
1784                     attr_set.error_detail := tmp_attr_set.cs;
1785                     RETURN NEXT attr_set; CONTINUE; 
1786                 END IF;
1787             END IF;
1788
1789             IF COALESCE(tmp_attr_set.circ_mod, '') = '' THEN
1790
1791                 -- no circ mod defined, see if we should apply a default
1792                 SELECT INTO attr_set.circ_modifier TRIM(BOTH '"' FROM value) 
1793                     FROM actor.org_unit_ancestor_setting(
1794                         'vandelay.item.circ_modifier.default', 
1795                         attr_set.owning_lib
1796                     );
1797
1798                 -- make sure the value from the org setting is still valid
1799                 PERFORM 1 FROM config.circ_modifier WHERE code = attr_set.circ_modifier;
1800                 IF NOT FOUND THEN
1801                     attr_set.import_error := 'import.item.invalid.circ_modifier';
1802                     attr_set.error_detail := tmp_attr_set.circ_mod;
1803                     RETURN NEXT attr_set; CONTINUE; 
1804                 END IF;
1805
1806             ELSE 
1807
1808                 SELECT code INTO attr_set.circ_modifier FROM config.circ_modifier WHERE code = tmp_attr_set.circ_mod;
1809                 IF NOT FOUND THEN
1810                     attr_set.import_error := 'import.item.invalid.circ_modifier';
1811                     attr_set.error_detail := tmp_attr_set.circ_mod;
1812                     RETURN NEXT attr_set; CONTINUE; 
1813                 END IF;
1814             END IF;
1815
1816             IF tmp_attr_set.circ_as != '' THEN
1817                 SELECT code INTO attr_set.circ_as_type FROM config.coded_value_map WHERE ctype = 'item_type' AND code = tmp_attr_set.circ_as;
1818                 IF NOT FOUND THEN
1819                     attr_set.import_error := 'import.item.invalid.circ_as_type';
1820                     attr_set.error_detail := tmp_attr_set.circ_as;
1821                     RETURN NEXT attr_set; CONTINUE; 
1822                 END IF;
1823             END IF;
1824
1825             IF COALESCE(tmp_attr_set.cl, '') = '' THEN
1826                 -- no location specified, see if we should apply a default
1827
1828                 SELECT INTO attr_set.location TRIM(BOTH '"' FROM value) 
1829                     FROM actor.org_unit_ancestor_setting(
1830                         'vandelay.item.copy_location.default', 
1831                         attr_set.owning_lib
1832                     );
1833
1834                 -- make sure the value from the org setting is still valid
1835                 PERFORM 1 FROM asset.copy_location 
1836                     WHERE id = attr_set.location AND NOT deleted;
1837                 IF NOT FOUND THEN
1838                     attr_set.import_error := 'import.item.invalid.location';
1839                     attr_set.error_detail := tmp_attr_set.cs;
1840                     RETURN NEXT attr_set; CONTINUE; 
1841                 END IF;
1842             ELSE
1843
1844                 -- search up the org unit tree for a matching copy location
1845                 WITH RECURSIVE anscestor_depth AS (
1846                     SELECT  ou.id,
1847                         out.depth AS depth,
1848                         ou.parent_ou
1849                     FROM  actor.org_unit ou
1850                         JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
1851                     WHERE ou.id = COALESCE(attr_set.owning_lib, attr_set.circ_lib)
1852                         UNION ALL
1853                     SELECT  ou.id,
1854                         out.depth,
1855                         ou.parent_ou
1856                     FROM  actor.org_unit ou
1857                         JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
1858                         JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
1859                 ) SELECT  cpl.id INTO attr_set.location
1860                     FROM  anscestor_depth a
1861                         JOIN asset.copy_location cpl ON (cpl.owning_lib = a.id)
1862                     WHERE LOWER(cpl.name) = LOWER(tmp_attr_set.cl) 
1863                         AND NOT cpl.deleted
1864                     ORDER BY a.depth DESC
1865                     LIMIT 1; 
1866
1867                 IF NOT FOUND THEN
1868                     attr_set.import_error := 'import.item.invalid.location';
1869                     attr_set.error_detail := tmp_attr_set.cs;
1870                     RETURN NEXT attr_set; CONTINUE; 
1871                 END IF;
1872             END IF;
1873
1874             attr_set.circulate      :=
1875                 LOWER( SUBSTRING( tmp_attr_set.circ, 1, 1)) IN ('t','y','1')
1876                 OR LOWER(tmp_attr_set.circ) = 'circulating'; -- BOOL
1877
1878             attr_set.deposit        :=
1879                 LOWER( SUBSTRING( tmp_attr_set.dep, 1, 1 ) ) IN ('t','y','1')
1880                 OR LOWER(tmp_attr_set.dep) = 'deposit'; -- BOOL
1881
1882             attr_set.holdable       :=
1883                 LOWER( SUBSTRING( tmp_attr_set.hold, 1, 1 ) ) IN ('t','y','1')
1884                 OR LOWER(tmp_attr_set.hold) = 'holdable'; -- BOOL
1885
1886             attr_set.opac_visible   :=
1887                 LOWER( SUBSTRING( tmp_attr_set.opac_vis, 1, 1 ) ) IN ('t','y','1')
1888                 OR LOWER(tmp_attr_set.opac_vis) = 'visible'; -- BOOL
1889
1890             attr_set.ref            :=
1891                 LOWER( SUBSTRING( tmp_attr_set.r, 1, 1 ) ) IN ('t','y','1')
1892                 OR LOWER(tmp_attr_set.r) = 'reference'; -- BOOL
1893
1894             attr_set.call_number    := tmp_attr_set.cn; -- TEXT
1895             attr_set.barcode        := tmp_attr_set.bc; -- TEXT,
1896             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
1897             attr_set.pub_note       := tmp_attr_set.note; -- TEXT,
1898             attr_set.priv_note      := tmp_attr_set.pnote; -- TEXT,
1899             attr_set.alert_message  := tmp_attr_set.amessage; -- TEXT,
1900             attr_set.internal_id    := tmp_attr_set.internal_id::BIGINT;
1901             attr_set.stat_cat_data  := tmp_attr_set.stat_cat_data; -- TEXT,
1902             attr_set.parts_data     := tmp_attr_set.parts_data; -- TEXT,
1903
1904             RETURN NEXT attr_set;
1905
1906         END LOOP;
1907
1908     END IF;
1909
1910     RETURN;
1911
1912 END;
1913 $$ LANGUAGE PLPGSQL;
1914
1915
1916
1917
1918 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_items ( ) RETURNS TRIGGER AS $func$
1919 DECLARE
1920     attr_def    BIGINT;
1921     item_data   vandelay.import_item%ROWTYPE;
1922 BEGIN
1923
1924     IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1925         RETURN NEW;
1926     END IF;
1927
1928     SELECT item_attr_def INTO attr_def FROM vandelay.bib_queue WHERE id = NEW.queue;
1929
1930     FOR item_data IN SELECT * FROM vandelay.ingest_items( NEW.id::BIGINT, attr_def ) LOOP
1931         INSERT INTO vandelay.import_item (
1932             record,
1933             definition,
1934             owning_lib,
1935             circ_lib,
1936             call_number,
1937             copy_number,
1938             status,
1939             location,
1940             circulate,
1941             deposit,
1942             deposit_amount,
1943             ref,
1944             holdable,
1945             price,
1946             barcode,
1947             circ_modifier,
1948             circ_as_type,
1949             alert_message,
1950             pub_note,
1951             priv_note,
1952             internal_id,
1953             opac_visible,
1954             stat_cat_data,
1955             parts_data,
1956             import_error,
1957             error_detail
1958         ) VALUES (
1959             NEW.id,
1960             item_data.definition,
1961             item_data.owning_lib,
1962             item_data.circ_lib,
1963             item_data.call_number,
1964             item_data.copy_number,
1965             item_data.status,
1966             item_data.location,
1967             item_data.circulate,
1968             item_data.deposit,
1969             item_data.deposit_amount,
1970             item_data.ref,
1971             item_data.holdable,
1972             item_data.price,
1973             item_data.barcode,
1974             item_data.circ_modifier,
1975             item_data.circ_as_type,
1976             item_data.alert_message,
1977             item_data.pub_note,
1978             item_data.priv_note,
1979             item_data.internal_id,
1980             item_data.opac_visible,
1981             item_data.stat_cat_data,
1982             item_data.parts_data,
1983             item_data.import_error,
1984             item_data.error_detail
1985         );
1986     END LOOP;
1987
1988     RETURN NULL;
1989 END;
1990 $func$ LANGUAGE PLPGSQL;
1991
1992 CREATE TRIGGER ingest_item_trigger
1993     AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1994     FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_items();
1995
1996
1997 -- evergreen.generic_map_normalizer 
1998
1999 CREATE OR REPLACE FUNCTION evergreen.generic_map_normalizer ( TEXT, TEXT ) RETURNS TEXT AS $f$
2000 my $string = shift;
2001 my %map;
2002
2003 my $default = $string;
2004
2005 $_ = shift;
2006 while (/^\s*?(.*?)\s*?=>\s*?(\S+)\s*/) {
2007     if ($1 eq '') {
2008         $default = $2;
2009     } else {
2010         $map{$2} = [split(/\s*,\s*/, $1)];
2011     }
2012     $_ = $';
2013 }
2014
2015 for my $key ( keys %map ) {
2016     return $key if (grep { $_ eq $string } @{ $map{$key} });
2017 }
2018
2019 return $default;
2020
2021 $f$ LANGUAGE PLPERLU;
2022
2023 CREATE OR REPLACE FUNCTION actor.address_alert_matches (
2024         org_unit INT, 
2025         street1 TEXT, 
2026         street2 TEXT, 
2027         city TEXT, 
2028         county TEXT, 
2029         state TEXT, 
2030         country TEXT, 
2031         post_code TEXT,
2032         mailing_address BOOL DEFAULT FALSE,
2033         billing_address BOOL DEFAULT FALSE
2034     ) RETURNS SETOF actor.address_alert AS $$
2035
2036 SELECT *
2037 FROM actor.address_alert
2038 WHERE
2039     active
2040     AND owner IN (SELECT id FROM actor.org_unit_ancestors($1)) 
2041     AND (
2042         (NOT mailing_address AND NOT billing_address)
2043         OR (mailing_address AND $9)
2044         OR (billing_address AND $10)
2045     )
2046     AND (
2047             (
2048                 match_all
2049                 AND COALESCE($2, '') ~* COALESCE(street1,   '.*')
2050                 AND COALESCE($3, '') ~* COALESCE(street2,   '.*')
2051                 AND COALESCE($4, '') ~* COALESCE(city,      '.*')
2052                 AND COALESCE($5, '') ~* COALESCE(county,    '.*')
2053                 AND COALESCE($6, '') ~* COALESCE(state,     '.*')
2054                 AND COALESCE($7, '') ~* COALESCE(country,   '.*')
2055                 AND COALESCE($8, '') ~* COALESCE(post_code, '.*')
2056             ) OR (
2057                 NOT match_all 
2058                 AND (  
2059                        $2 ~* street1
2060                     OR $3 ~* street2
2061                     OR $4 ~* city
2062                     OR $5 ~* county
2063                     OR $6 ~* state
2064                     OR $7 ~* country
2065                     OR $8 ~* post_code
2066                 )
2067             )
2068         )
2069     ORDER BY actor.org_unit_proximity(owner, $1)
2070 $$ LANGUAGE SQL;
2071
2072 CREATE OR REPLACE FUNCTION evergreen.coded_value_map_normalizer( input TEXT, ctype TEXT ) 
2073     RETURNS TEXT AS $F$
2074         SELECT COALESCE(value,$1) 
2075             FROM config.coded_value_map 
2076             WHERE ctype = $2 AND code = $1;
2077 $F$ LANGUAGE SQL;
2078
2079 -- user activity functions --
2080
2081 -- remove transient activity entries on insert of new entries
2082 CREATE OR REPLACE FUNCTION actor.usr_activity_transient_trg () RETURNS TRIGGER AS $$
2083 BEGIN
2084     DELETE FROM actor.usr_activity act USING config.usr_activity_type atype
2085         WHERE atype.transient AND 
2086             NEW.etype = atype.id AND
2087             act.etype = atype.id AND
2088             act.usr = NEW.usr;
2089     RETURN NEW;
2090 END;
2091 $$ LANGUAGE PLPGSQL;
2092
2093 CREATE TRIGGER remove_transient_usr_activity
2094     BEFORE INSERT ON actor.usr_activity
2095     FOR EACH ROW EXECUTE PROCEDURE actor.usr_activity_transient_trg();
2096
2097 -- given a set of activity criteria, find the most approprate activity type
2098 CREATE OR REPLACE FUNCTION actor.usr_activity_get_type (
2099         ewho TEXT, 
2100         ewhat TEXT, 
2101         ehow TEXT
2102     ) RETURNS SETOF config.usr_activity_type AS $$
2103 SELECT * FROM config.usr_activity_type 
2104     WHERE 
2105         enabled AND 
2106         (ewho  IS NULL OR ewho  = $1) AND
2107         (ewhat IS NULL OR ewhat = $2) AND
2108         (ehow  IS NULL OR ehow  = $3) 
2109     ORDER BY 
2110         -- BOOL comparisons sort false to true
2111         COALESCE(ewho, '')  != COALESCE($1, ''),
2112         COALESCE(ewhat,'')  != COALESCE($2, ''),
2113         COALESCE(ehow, '')  != COALESCE($3, '') 
2114     LIMIT 1;
2115 $$ LANGUAGE SQL;
2116
2117 -- given a set of activity criteria, finds the best
2118 -- activity type and inserts the activity entry
2119 CREATE OR REPLACE FUNCTION actor.insert_usr_activity (
2120         usr INT,
2121         ewho TEXT, 
2122         ewhat TEXT, 
2123         ehow TEXT
2124     ) RETURNS SETOF actor.usr_activity AS $$
2125 DECLARE
2126     new_row actor.usr_activity%ROWTYPE;
2127 BEGIN
2128     SELECT id INTO new_row.etype FROM actor.usr_activity_get_type(ewho, ewhat, ehow);
2129     IF FOUND THEN
2130         new_row.usr := usr;
2131         INSERT INTO actor.usr_activity (usr, etype) 
2132             VALUES (usr, new_row.etype)
2133             RETURNING * INTO new_row;
2134         RETURN NEXT new_row;
2135     END IF;
2136 END;
2137 $$ LANGUAGE plpgsql;
2138
2139 CREATE OR REPLACE FUNCTION evergreen.rel_bump(terms TEXT[], value TEXT, bumps TEXT[], mults NUMERIC[]) RETURNS NUMERIC AS
2140 $BODY$
2141 use strict;
2142 my ($terms,$value,$bumps,$mults) = @_;
2143
2144 my $retval = 1;
2145
2146 for (my $id = 0; $id < @$bumps; $id++) {
2147         if ($bumps->[$id] eq 'first_word') {
2148                 $retval *= $mults->[$id] if ($value =~ /^$terms->[0]/);
2149         } elsif ($bumps->[$id] eq 'full_match') {
2150                 my $fullmatch = join(' ', @$terms);
2151                 $retval *= $mults->[$id] if ($value =~ /^$fullmatch$/);
2152         } elsif ($bumps->[$id] eq 'word_order') {
2153                 my $wordorder = join('.*', @$terms);
2154                 $retval *= $mults->[$id] if ($value =~ /$wordorder/);
2155         }
2156 }
2157 return $retval;
2158 $BODY$ LANGUAGE plperlu IMMUTABLE STRICT COST 100;
2159
2160 -- user activity functions --
2161
2162
2163 -- find the most relevant set of credentials for the Z source and org
2164 CREATE OR REPLACE FUNCTION config.z3950_source_credentials_lookup
2165         (source TEXT, owner INTEGER) 
2166         RETURNS config.z3950_source_credentials AS $$
2167
2168     SELECT creds.* 
2169     FROM config.z3950_source_credentials creds
2170         JOIN actor.org_unit aou ON (aou.id = creds.owner)
2171         JOIN actor.org_unit_type aout ON (aout.id = aou.ou_type)
2172     WHERE creds.source = $1 AND creds.owner IN ( 
2173         SELECT id FROM actor.org_unit_ancestors($2) 
2174     )
2175     ORDER BY aout.depth DESC LIMIT 1;
2176
2177 $$ LANGUAGE SQL STABLE;
2178
2179 -- since we are not exposing config.z3950_source_credentials
2180 -- via the IDL, providing a stored proc gives us a way to
2181 -- set values in the table via cstore
2182 CREATE OR REPLACE FUNCTION config.z3950_source_credentials_apply
2183         (src TEXT, org INTEGER, uname TEXT, passwd TEXT) 
2184         RETURNS VOID AS $$
2185 BEGIN
2186     PERFORM 1 FROM config.z3950_source_credentials
2187         WHERE owner = org AND source = src;
2188
2189     IF FOUND THEN
2190         IF COALESCE(uname, '') = '' AND COALESCE(passwd, '') = '' THEN
2191             DELETE FROM config.z3950_source_credentials 
2192                 WHERE owner = org AND source = src;
2193         ELSE 
2194             UPDATE config.z3950_source_credentials 
2195                 SET username = uname, password = passwd
2196                 WHERE owner = org AND source = src;
2197         END IF;
2198     ELSE
2199         IF COALESCE(uname, '') <> '' OR COALESCE(passwd, '') <> '' THEN
2200             INSERT INTO config.z3950_source_credentials
2201                 (source, owner, username, password) 
2202                 VALUES (src, org, uname, passwd);
2203         END IF;
2204     END IF;
2205 END;
2206 $$ LANGUAGE PLPGSQL;
2207
2208 -- Handy function for transforming marc to a variant available on config.xml_transform
2209 CREATE OR REPLACE FUNCTION evergreen.marc_to (marc text, xfrm text) RETURNS TEXT AS $$
2210     SELECT evergreen.xml_pretty_print(xslt_process($1,xslt)::XML)::TEXT FROM config.xml_transform WHERE name = $2;
2211 $$ LANGUAGE SQL;
2212