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