2 * Copyright (C) 2008 Equinox Software, Inc.
3 * Bill Erickson <erickson@esilibrary.com>
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.
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.
17 CREATE OR REPLACE FUNCTION actor.usr_merge_rows( table_name TEXT, col_name TEXT, src_usr INT, dest_usr INT ) RETURNS VOID AS $$
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
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;
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.
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 $$
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;
61 DELETE FROM actor.card where usr = src_usr;
63 IF deactivate_cards THEN
64 UPDATE actor.card SET active = 'f' WHERE usr = src_usr;
66 UPDATE actor.card SET usr = dest_usr WHERE usr = src_usr;
71 DELETE FROM actor.usr_address WHERE usr = src_usr;
73 UPDATE actor.usr_address SET usr = dest_usr WHERE usr = src_usr;
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);
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);
91 -- For each *_bucket table: transfer every bucket belonging to src_usr
92 -- into the custody of dest_usr.
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.
101 FROM container.biblio_record_entry_bucket
102 WHERE owner = src_usr
104 suffix := ' (' || src_usr || ')';
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 || ' ';
120 FROM container.call_number_bucket
121 WHERE owner = src_usr
123 suffix := ' (' || src_usr || ')';
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 || ' ';
139 FROM container.copy_bucket
140 WHERE owner = src_usr
142 suffix := ' (' || src_usr || ')';
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 || ' ';
158 FROM container.user_bucket
159 WHERE owner = src_usr
161 suffix := ' (' || src_usr || ')';
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 || ' ';
175 UPDATE container.user_bucket_item SET target_user = dest_usr WHERE target_user = src_usr;
178 -- transfer queues the same way we transfer buckets (see above)
182 WHERE owner = src_usr
184 suffix := ' (' || src_usr || ')';
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 || ' ';
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;
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;
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;
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;
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;
226 -- transfer picklists the same way we transfer buckets (see above)
230 WHERE owner = src_usr
232 suffix := ' (' || src_usr || ')';
236 SET owner = dest_usr, name = name || suffix
237 WHERE id = picklist_row.id;
238 EXCEPTION WHEN unique_violation THEN
239 suffix := suffix || ' ';
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;
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;
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;
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.
271 UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
272 EXCEPTION WHEN undefined_table THEN
276 UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
277 EXCEPTION WHEN undefined_table THEN
281 UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
282 EXCEPTION WHEN undefined_table THEN
286 -- transfer folders the same way we transfer buckets (see above)
289 FROM reporter.template_folder
290 WHERE owner = src_usr
292 suffix := ' (' || src_usr || ')';
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 || ' ';
305 EXCEPTION WHEN undefined_table THEN
309 -- transfer folders the same way we transfer buckets (see above)
312 FROM reporter.report_folder
313 WHERE owner = src_usr
315 suffix := ' (' || src_usr || ')';
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 || ' ';
328 EXCEPTION WHEN undefined_table THEN
332 -- transfer folders the same way we transfer buckets (see above)
335 FROM reporter.output_folder
336 WHERE owner = src_usr
338 suffix := ' (' || src_usr || ')';
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 || ' ';
351 EXCEPTION WHEN undefined_table THEN
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)
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)),
366 COALESCE(pref_family_name, (SELECT pref_family_name FROM susr)),
368 COALESCE(pref_suffix, (SELECT pref_suffix FROM susr)),
370 COALESCE(name_keywords, '') || ' ' ||
371 COALESCE((SELECT name_keywords FROM susr), '')
374 -- Finally, delete the source user
375 DELETE FROM actor.usr WHERE id = src_usr;
382 COMMENT ON FUNCTION actor.usr_merge(INT, INT, BOOLEAN, BOOLEAN, BOOLEAN) IS $$
383 Merges all user date from src_usr to dest_usr. When collisions occur,
384 keep dest_usr's data and delete src_usr's data.
388 CREATE OR REPLACE FUNCTION actor.usr_purge_data(
390 specified_dest_usr IN INTEGER
394 renamable_row RECORD;
398 IF specified_dest_usr IS NULL THEN
399 dest_usr := 1; -- Admin user on stock installs
401 dest_usr := specified_dest_usr;
405 UPDATE acq.fund_allocation SET allocator = dest_usr WHERE allocator = src_usr;
406 UPDATE acq.lineitem SET creator = dest_usr WHERE creator = src_usr;
407 UPDATE acq.lineitem SET editor = dest_usr WHERE editor = src_usr;
408 UPDATE acq.lineitem SET selector = dest_usr WHERE selector = src_usr;
409 UPDATE acq.lineitem_note SET creator = dest_usr WHERE creator = src_usr;
410 UPDATE acq.lineitem_note SET editor = dest_usr WHERE editor = src_usr;
411 DELETE FROM acq.lineitem_usr_attr_definition WHERE usr = src_usr;
413 -- Update with a rename to avoid collisions
417 WHERE owner = src_usr
419 suffix := ' (' || src_usr || ')';
423 SET owner = dest_usr, name = name || suffix
424 WHERE id = renamable_row.id;
425 EXCEPTION WHEN unique_violation THEN
426 suffix := suffix || ' ';
433 UPDATE acq.picklist SET creator = dest_usr WHERE creator = src_usr;
434 UPDATE acq.picklist SET editor = dest_usr WHERE editor = src_usr;
435 UPDATE acq.po_note SET creator = dest_usr WHERE creator = src_usr;
436 UPDATE acq.po_note SET editor = dest_usr WHERE editor = src_usr;
437 UPDATE acq.purchase_order SET owner = dest_usr WHERE owner = src_usr;
438 UPDATE acq.purchase_order SET creator = dest_usr WHERE creator = src_usr;
439 UPDATE acq.purchase_order SET editor = dest_usr WHERE editor = src_usr;
440 UPDATE acq.claim_event SET creator = dest_usr WHERE creator = src_usr;
443 DELETE FROM action.circulation WHERE usr = src_usr;
444 UPDATE action.circulation SET circ_staff = dest_usr WHERE circ_staff = src_usr;
445 UPDATE action.circulation SET checkin_staff = dest_usr WHERE checkin_staff = src_usr;
446 UPDATE action.hold_notification SET notify_staff = dest_usr WHERE notify_staff = src_usr;
447 UPDATE action.hold_request SET fulfillment_staff = dest_usr WHERE fulfillment_staff = src_usr;
448 UPDATE action.hold_request SET requestor = dest_usr WHERE requestor = src_usr;
449 DELETE FROM action.hold_request WHERE usr = src_usr;
450 UPDATE action.in_house_use SET staff = dest_usr WHERE staff = src_usr;
451 UPDATE action.non_cat_in_house_use SET staff = dest_usr WHERE staff = src_usr;
452 DELETE FROM action.non_cataloged_circulation WHERE patron = src_usr;
453 UPDATE action.non_cataloged_circulation SET staff = dest_usr WHERE staff = src_usr;
454 DELETE FROM action.survey_response WHERE usr = src_usr;
455 UPDATE action.fieldset SET owner = dest_usr WHERE owner = src_usr;
456 DELETE FROM action.usr_circ_history WHERE usr = src_usr;
459 DELETE FROM actor.card WHERE usr = src_usr;
460 DELETE FROM actor.stat_cat_entry_usr_map WHERE target_usr = src_usr;
462 -- The following update is intended to avoid transient violations of a foreign
463 -- key constraint, whereby actor.usr_address references itself. It may not be
464 -- necessary, but it does no harm.
465 UPDATE actor.usr_address SET replaces = NULL
466 WHERE usr = src_usr AND replaces IS NOT NULL;
467 DELETE FROM actor.usr_address WHERE usr = src_usr;
468 DELETE FROM actor.usr_note WHERE usr = src_usr;
469 UPDATE actor.usr_note SET creator = dest_usr WHERE creator = src_usr;
470 DELETE FROM actor.usr_org_unit_opt_in WHERE usr = src_usr;
471 UPDATE actor.usr_org_unit_opt_in SET staff = dest_usr WHERE staff = src_usr;
472 DELETE FROM actor.usr_setting WHERE usr = src_usr;
473 DELETE FROM actor.usr_standing_penalty WHERE usr = src_usr;
474 UPDATE actor.usr_standing_penalty SET staff = dest_usr WHERE staff = src_usr;
477 UPDATE asset.call_number SET creator = dest_usr WHERE creator = src_usr;
478 UPDATE asset.call_number SET editor = dest_usr WHERE editor = src_usr;
479 UPDATE asset.call_number_note SET creator = dest_usr WHERE creator = src_usr;
480 UPDATE asset.copy SET creator = dest_usr WHERE creator = src_usr;
481 UPDATE asset.copy SET editor = dest_usr WHERE editor = src_usr;
482 UPDATE asset.copy_note SET creator = dest_usr WHERE creator = src_usr;
485 DELETE FROM auditor.actor_usr_address_history WHERE id = src_usr;
486 DELETE FROM auditor.actor_usr_history WHERE id = src_usr;
487 UPDATE auditor.asset_call_number_history SET creator = dest_usr WHERE creator = src_usr;
488 UPDATE auditor.asset_call_number_history SET editor = dest_usr WHERE editor = src_usr;
489 UPDATE auditor.asset_copy_history SET creator = dest_usr WHERE creator = src_usr;
490 UPDATE auditor.asset_copy_history SET editor = dest_usr WHERE editor = src_usr;
491 UPDATE auditor.biblio_record_entry_history SET creator = dest_usr WHERE creator = src_usr;
492 UPDATE auditor.biblio_record_entry_history SET editor = dest_usr WHERE editor = src_usr;
495 UPDATE biblio.record_entry SET creator = dest_usr WHERE creator = src_usr;
496 UPDATE biblio.record_entry SET editor = dest_usr WHERE editor = src_usr;
497 UPDATE biblio.record_note SET creator = dest_usr WHERE creator = src_usr;
498 UPDATE biblio.record_note SET editor = dest_usr WHERE editor = src_usr;
501 -- Update buckets with a rename to avoid collisions
504 FROM container.biblio_record_entry_bucket
505 WHERE owner = src_usr
507 suffix := ' (' || src_usr || ')';
510 UPDATE container.biblio_record_entry_bucket
511 SET owner = dest_usr, name = name || suffix
512 WHERE id = renamable_row.id;
513 EXCEPTION WHEN unique_violation THEN
514 suffix := suffix || ' ';
523 FROM container.call_number_bucket
524 WHERE owner = src_usr
526 suffix := ' (' || src_usr || ')';
529 UPDATE container.call_number_bucket
530 SET owner = dest_usr, name = name || suffix
531 WHERE id = renamable_row.id;
532 EXCEPTION WHEN unique_violation THEN
533 suffix := suffix || ' ';
542 FROM container.copy_bucket
543 WHERE owner = src_usr
545 suffix := ' (' || src_usr || ')';
548 UPDATE container.copy_bucket
549 SET owner = dest_usr, name = name || suffix
550 WHERE id = renamable_row.id;
551 EXCEPTION WHEN unique_violation THEN
552 suffix := suffix || ' ';
561 FROM container.user_bucket
562 WHERE owner = src_usr
564 suffix := ' (' || src_usr || ')';
567 UPDATE container.user_bucket
568 SET owner = dest_usr, name = name || suffix
569 WHERE id = renamable_row.id;
570 EXCEPTION WHEN unique_violation THEN
571 suffix := suffix || ' ';
578 DELETE FROM container.user_bucket_item WHERE target_user = src_usr;
581 DELETE FROM money.billable_xact WHERE usr = src_usr;
582 DELETE FROM money.collections_tracker WHERE usr = src_usr;
583 UPDATE money.collections_tracker SET collector = dest_usr WHERE collector = src_usr;
586 DELETE FROM permission.usr_grp_map WHERE usr = src_usr;
587 DELETE FROM permission.usr_object_perm_map WHERE usr = src_usr;
588 DELETE FROM permission.usr_perm_map WHERE usr = src_usr;
589 DELETE FROM permission.usr_work_ou_map WHERE usr = src_usr;
592 -- Update with a rename to avoid collisions
596 FROM reporter.output_folder
597 WHERE owner = src_usr
599 suffix := ' (' || src_usr || ')';
602 UPDATE reporter.output_folder
603 SET owner = dest_usr, name = name || suffix
604 WHERE id = renamable_row.id;
605 EXCEPTION WHEN unique_violation THEN
606 suffix := suffix || ' ';
612 EXCEPTION WHEN undefined_table THEN
617 UPDATE reporter.report SET owner = dest_usr WHERE owner = src_usr;
618 EXCEPTION WHEN undefined_table THEN
622 -- Update with a rename to avoid collisions
626 FROM reporter.report_folder
627 WHERE owner = src_usr
629 suffix := ' (' || src_usr || ')';
632 UPDATE reporter.report_folder
633 SET owner = dest_usr, name = name || suffix
634 WHERE id = renamable_row.id;
635 EXCEPTION WHEN unique_violation THEN
636 suffix := suffix || ' ';
642 EXCEPTION WHEN undefined_table THEN
647 UPDATE reporter.schedule SET runner = dest_usr WHERE runner = src_usr;
648 EXCEPTION WHEN undefined_table THEN
653 UPDATE reporter.template SET owner = dest_usr WHERE owner = src_usr;
654 EXCEPTION WHEN undefined_table THEN
658 -- Update with a rename to avoid collisions
662 FROM reporter.template_folder
663 WHERE owner = src_usr
665 suffix := ' (' || src_usr || ')';
668 UPDATE reporter.template_folder
669 SET owner = dest_usr, name = name || suffix
670 WHERE id = renamable_row.id;
671 EXCEPTION WHEN unique_violation THEN
672 suffix := suffix || ' ';
678 EXCEPTION WHEN undefined_table THEN
683 -- Update with a rename to avoid collisions
687 WHERE owner = src_usr
689 suffix := ' (' || src_usr || ')';
692 UPDATE vandelay.queue
693 SET owner = dest_usr, name = name || suffix
694 WHERE id = renamable_row.id;
695 EXCEPTION WHEN unique_violation THEN
696 suffix := suffix || ' ';
703 -- NULL-ify addresses last so other cleanup (e.g. circ anonymization)
704 -- can access the information before deletion.
708 mailing_address = NULL,
709 billing_address = NULL
715 COMMENT ON FUNCTION actor.usr_purge_data(INT, INT) IS $$
716 Finds rows dependent on a given row in actor.usr and either deletes them
717 or reassigns them to a different user.
722 CREATE OR REPLACE FUNCTION actor.usr_delete(
727 old_profile actor.usr.profile%type;
728 old_home_ou actor.usr.home_ou%type;
729 new_profile actor.usr.profile%type;
730 new_home_ou actor.usr.home_ou%type;
732 new_dob actor.usr.dob%type;
735 id || '-PURGED-' || now(),
749 -- Quit if no such user
751 IF old_profile IS NULL THEN
755 perform actor.usr_purge_data( src_usr, dest_usr );
757 -- Find the root grp_tree and the root org_unit. This would be simpler if we
758 -- could assume that there is only one root. Theoretically, someday, maybe,
759 -- there could be multiple roots, so we take extra trouble to get the right ones.
766 permission.grp_ancestors( old_profile )
775 actor.org_unit_ancestors( old_home_ou )
779 -- Truncate date of birth
781 IF new_dob IS NOT NULL THEN
782 new_dob := date_trunc( 'year', new_dob );
789 profile = new_profile,
792 passwd = random()::text,
797 FROM config.identification_type
802 net_access_level = DEFAULT,
805 first_given_name = new_name,
806 second_given_name = NULL,
807 family_name = new_name,
811 evening_phone = NULL,
813 mailing_address = NULL,
814 billing_address = NULL,
815 home_ou = new_home_ou,
818 master_account = DEFAULT,
819 super_user = DEFAULT,
824 claims_returned_count = DEFAULT,
825 credit_forward_balance = DEFAULT,
826 last_xact_id = DEFAULT,
827 alert_message = NULL,
835 COMMENT ON FUNCTION actor.usr_delete(INT, INT) IS $$
836 Logically deletes a user. Removes personally identifiable information,
837 and purges associated data in other tables.
842 CREATE OR REPLACE FUNCTION actor.approve_pending_address(pending_id INT) RETURNS BIGINT AS $$
846 SELECT INTO old_id replaces FROM actor.usr_address where id = pending_id;
847 IF old_id IS NULL THEN
848 UPDATE actor.usr_address SET pending = 'f' WHERE id = pending_id;
851 -- address replaces an existing address
852 DELETE FROM actor.usr_address WHERE id = -old_id;
853 UPDATE actor.usr_address SET id = -id WHERE id = old_id;
854 UPDATE actor.usr_address SET replaces = NULL, id = old_id, pending = 'f' WHERE id = pending_id;
859 COMMENT ON FUNCTION actor.approve_pending_address(INT) IS $$
860 Replaces an address with a pending address. This is done by giving the pending
861 address the ID of the old address. The replaced address is retained with -id.
864 CREATE OR REPLACE FUNCTION container.clear_expired_circ_history_items(
868 -- Delete old circulation bucket items for a specified user.
869 -- "Old" means older than the interval specified by a
870 -- user-level setting, if it is so specified.
873 threshold TIMESTAMP WITH TIME ZONE;
876 IF ac_usr IS NULL THEN
879 -- Determine the threshold date that defines "old". Subtract the
880 -- interval from the system date, then truncate to midnight.
884 now() - CAST( translate( value, '"', '' ) AS INTERVAL )
892 AND name = 'patron.max_reading_list_interval';
894 IF threshold is null THEN
895 -- No interval defined; don't delete anything
896 -- RAISE NOTICE 'No interval defined for user %', ac_usr;
900 -- RAISE NOTICE 'Date threshold: %', threshold;
902 -- Threshold found; do the delete
903 delete from container.copy_bucket_item
910 container.copy_bucket
913 and btype = 'circ_history'
915 and create_time < threshold;
921 COMMENT ON FUNCTION container.clear_expired_circ_history_items( INTEGER ) IS $$
922 Delete old circulation bucket items for a specified user.
923 "Old" means older than the interval specified by a
924 user-level setting, if it is so specified.
927 CREATE OR REPLACE FUNCTION container.clear_all_expired_circ_history_items( )
930 -- Delete expired circulation bucket items for all users that have
931 -- a setting for patron.max_reading_list_interval.
934 today TIMESTAMP WITH TIME ZONE;
935 threshold TIMESTAMP WITH TIME ZONE;
938 SELECT date_trunc( 'day', now() ) INTO today;
947 name = 'patron.max_reading_list_interval'
950 -- Make sure the setting is a valid interval
953 threshold := today - CAST( translate( usr_setting.value, '"', '' ) AS INTERVAL );
956 RAISE NOTICE 'Invalid setting patron.max_reading_list_interval for user %: ''%''',
957 usr_setting.usr, usr_setting.value;
961 --RAISE NOTICE 'User % threshold %', usr_setting.usr, threshold;
963 DELETE FROM container.copy_bucket_item
970 container.copy_bucket
972 owner = usr_setting.usr
973 AND btype = 'circ_history'
975 AND create_time < threshold;
981 COMMENT ON FUNCTION container.clear_all_expired_circ_history_items( ) IS $$
982 Delete expired circulation bucket items for all users that have
983 a setting for patron.max_reading_list_interval.
986 CREATE OR REPLACE FUNCTION asset.merge_record_assets( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
988 moved_objects INT := 0;
989 source_cn asset.call_number%ROWTYPE;
990 target_cn asset.call_number%ROWTYPE;
991 metarec metabib.metarecord%ROWTYPE;
992 hold action.hold_request%ROWTYPE;
993 ser_rec serial.record_entry%ROWTYPE;
994 ser_sub serial.subscription%ROWTYPE;
995 acq_lineitem acq.lineitem%ROWTYPE;
996 acq_request acq.user_request%ROWTYPE;
997 booking booking.resource_type%ROWTYPE;
998 source_part biblio.monograph_part%ROWTYPE;
999 target_part biblio.monograph_part%ROWTYPE;
1000 multi_home biblio.peer_bib_copy_map%ROWTYPE;
1004 uri_text TEXT := '';
1007 -- move any 856 entries on records that have at least one MARC-mapped URI entry
1008 SELECT INTO uri_count COUNT(*)
1009 FROM asset.uri_call_number_map m
1010 JOIN asset.call_number cn ON (m.call_number = cn.id)
1011 WHERE cn.record = source_record;
1013 IF uri_count > 0 THEN
1015 -- This returns more nodes than you might expect:
1016 -- 7 instead of 1 for an 856 with $u $y $9
1017 SELECT COUNT(*) INTO counter
1018 FROM oils_xpath_table(
1021 'biblio.record_entry',
1023 'id=' || source_record
1024 ) as t(i int,c text);
1026 FOR i IN 1 .. counter LOOP
1027 SELECT '<datafield xmlns="http://www.loc.gov/MARC21/slim"' ||
1029 ' ind1="' || FIRST(ind1) || '"' ||
1030 ' ind2="' || FIRST(ind2) || '">' ||
1032 '<subfield code="' || subfield || '">' ||
1035 regexp_replace(data,'&','&','g'),
1039 ) || '</subfield>', ''
1040 ) || '</datafield>' INTO uri_datafield
1041 FROM oils_xpath_table(
1044 'biblio.record_entry',
1045 '//*[@tag="856"][position()=' || i || ']/@ind1|' ||
1046 '//*[@tag="856"][position()=' || i || ']/@ind2|' ||
1047 '//*[@tag="856"][position()=' || i || ']/*/@code|' ||
1048 '//*[@tag="856"][position()=' || i || ']/*[@code]',
1049 'id=' || source_record
1050 ) as t(id int,ind1 text, ind2 text,subfield text,data text);
1052 -- As most of the results will be NULL, protect against NULLifying
1053 -- the valid content that we do generate
1054 uri_text := uri_text || COALESCE(uri_datafield, '');
1057 IF uri_text <> '' THEN
1058 UPDATE biblio.record_entry
1059 SET marc = regexp_replace(marc,'(</[^>]*record>)', uri_text || E'\\1')
1060 WHERE id = target_record;
1065 -- Find and move metarecords to the target record
1066 SELECT INTO metarec *
1067 FROM metabib.metarecord
1068 WHERE master_record = source_record;
1071 UPDATE metabib.metarecord
1072 SET master_record = target_record,
1074 WHERE id = metarec.id;
1076 moved_objects := moved_objects + 1;
1079 -- Find call numbers attached to the source ...
1080 FOR source_cn IN SELECT * FROM asset.call_number WHERE record = source_record LOOP
1082 SELECT INTO target_cn *
1083 FROM asset.call_number
1084 WHERE label = source_cn.label
1085 AND prefix = source_cn.prefix
1086 AND suffix = source_cn.suffix
1087 AND owning_lib = source_cn.owning_lib
1088 AND record = target_record
1091 -- ... and if there's a conflicting one on the target ...
1094 -- ... move the copies to that, and ...
1096 SET call_number = target_cn.id
1097 WHERE call_number = source_cn.id;
1099 -- ... move V holds to the move-target call number
1100 FOR hold IN SELECT * FROM action.hold_request WHERE target = source_cn.id AND hold_type = 'V' LOOP
1102 UPDATE action.hold_request
1103 SET target = target_cn.id
1106 moved_objects := moved_objects + 1;
1109 UPDATE asset.call_number SET deleted = TRUE WHERE id = source_cn.id;
1113 -- ... just move the call number to the target record
1114 UPDATE asset.call_number
1115 SET record = target_record
1116 WHERE id = source_cn.id;
1119 moved_objects := moved_objects + 1;
1122 -- Find T holds targeting the source record ...
1123 FOR hold IN SELECT * FROM action.hold_request WHERE target = source_record AND hold_type = 'T' LOOP
1125 -- ... and move them to the target record
1126 UPDATE action.hold_request
1127 SET target = target_record
1130 moved_objects := moved_objects + 1;
1133 -- Find serial records targeting the source record ...
1134 FOR ser_rec IN SELECT * FROM serial.record_entry WHERE record = source_record LOOP
1135 -- ... and move them to the target record
1136 UPDATE serial.record_entry
1137 SET record = target_record
1138 WHERE id = ser_rec.id;
1140 moved_objects := moved_objects + 1;
1143 -- Find serial subscriptions targeting the source record ...
1144 FOR ser_sub IN SELECT * FROM serial.subscription WHERE record_entry = source_record LOOP
1145 -- ... and move them to the target record
1146 UPDATE serial.subscription
1147 SET record_entry = target_record
1148 WHERE id = ser_sub.id;
1150 moved_objects := moved_objects + 1;
1153 -- Find booking resource types targeting the source record ...
1154 FOR booking IN SELECT * FROM booking.resource_type WHERE record = source_record LOOP
1155 -- ... and move them to the target record
1156 UPDATE booking.resource_type
1157 SET record = target_record
1158 WHERE id = booking.id;
1160 moved_objects := moved_objects + 1;
1163 -- Find acq lineitems targeting the source record ...
1164 FOR acq_lineitem IN SELECT * FROM acq.lineitem WHERE eg_bib_id = source_record LOOP
1165 -- ... and move them to the target record
1167 SET eg_bib_id = target_record
1168 WHERE id = acq_lineitem.id;
1170 moved_objects := moved_objects + 1;
1173 -- Find acq user purchase requests targeting the source record ...
1174 FOR acq_request IN SELECT * FROM acq.user_request WHERE eg_bib = source_record LOOP
1175 -- ... and move them to the target record
1176 UPDATE acq.user_request
1177 SET eg_bib = target_record
1178 WHERE id = acq_request.id;
1180 moved_objects := moved_objects + 1;
1183 -- Find parts attached to the source ...
1184 FOR source_part IN SELECT * FROM biblio.monograph_part WHERE record = source_record LOOP
1186 SELECT INTO target_part *
1187 FROM biblio.monograph_part
1188 WHERE label = source_part.label
1189 AND record = target_record;
1191 -- ... and if there's a conflicting one on the target ...
1194 -- ... move the copy-part maps to that, and ...
1195 UPDATE asset.copy_part_map
1196 SET part = target_part.id
1197 WHERE part = source_part.id;
1199 -- ... move P holds to the move-target part
1200 FOR hold IN SELECT * FROM action.hold_request WHERE target = source_part.id AND hold_type = 'P' LOOP
1202 UPDATE action.hold_request
1203 SET target = target_part.id
1206 moved_objects := moved_objects + 1;
1211 -- ... just move the part to the target record
1212 UPDATE biblio.monograph_part
1213 SET record = target_record
1214 WHERE id = source_part.id;
1217 moved_objects := moved_objects + 1;
1220 -- Find multi_home items attached to the source ...
1221 FOR multi_home IN SELECT * FROM biblio.peer_bib_copy_map WHERE peer_record = source_record LOOP
1222 -- ... and move them to the target record
1223 UPDATE biblio.peer_bib_copy_map
1224 SET peer_record = target_record
1225 WHERE id = multi_home.id;
1227 moved_objects := moved_objects + 1;
1230 -- And delete mappings where the item's home bib was merged with the peer bib
1231 DELETE FROM biblio.peer_bib_copy_map WHERE peer_record = (
1232 SELECT (SELECT record FROM asset.call_number WHERE id = call_number)
1233 FROM asset.copy WHERE id = target_copy
1236 -- Apply merge tracking
1237 UPDATE biblio.record_entry
1238 SET merge_date = NOW() WHERE id = target_record;
1240 UPDATE biblio.record_entry
1241 SET merge_date = NOW(), merged_to = target_record
1242 WHERE id = source_record;
1244 -- replace book bag entries of source_record with target_record
1245 UPDATE container.biblio_record_entry_bucket_item
1246 SET target_biblio_record_entry = target_record
1247 WHERE bucket IN (SELECT id FROM container.biblio_record_entry_bucket WHERE btype = 'bookbag')
1248 AND target_biblio_record_entry = source_record;
1250 -- Finally, "delete" the source record
1251 DELETE FROM biblio.record_entry WHERE id = source_record;
1253 -- That's all, folks!
1254 RETURN moved_objects;
1256 $func$ LANGUAGE plpgsql;
1258 -- Authority ingest routines
1259 CREATE OR REPLACE FUNCTION authority.propagate_changes
1260 (aid BIGINT, bid BIGINT) RETURNS BIGINT AS $func$
1262 bib_rec biblio.record_entry%ROWTYPE;
1266 SELECT INTO bib_rec * FROM biblio.record_entry WHERE id = bid;
1268 new_marc := vandelay.merge_record_xml(
1269 bib_rec.marc, authority.generate_overlay_template(aid));
1271 IF new_marc = bib_rec.marc THEN
1272 -- Authority record change had no impact on this bib record.
1273 -- Nothing left to do.
1277 PERFORM 1 FROM config.global_flag
1278 WHERE name = 'ingest.disable_authority_auto_update_bib_meta'
1282 -- update the bib record editor and edit_date
1284 SELECT editor FROM authority.record_entry WHERE id = aid);
1285 bib_rec.edit_date = NOW();
1288 UPDATE biblio.record_entry SET
1290 editor = bib_rec.editor,
1291 edit_date = bib_rec.edit_date
1297 $func$ LANGUAGE PLPGSQL;
1299 CREATE OR REPLACE FUNCTION authority.propagate_changes (aid BIGINT) RETURNS SETOF BIGINT AS $func$
1300 SELECT authority.propagate_changes( authority, bib ) FROM authority.bib_linking WHERE authority = $1;
1301 $func$ LANGUAGE SQL;
1303 CREATE OR REPLACE FUNCTION authority.map_thesaurus_to_control_set () RETURNS TRIGGER AS $func$
1305 IF NEW.control_set IS NULL THEN
1306 SELECT control_set INTO NEW.control_set
1307 FROM authority.thesaurus
1308 WHERE authority.extract_thesaurus(NEW.marc) = code;
1313 $func$ LANGUAGE PLPGSQL;
1315 CREATE OR REPLACE FUNCTION authority.reingest_authority_rec_descriptor( auth_id BIGINT ) RETURNS VOID AS $func$
1317 DELETE FROM authority.rec_descriptor WHERE record = auth_id;
1318 INSERT INTO authority.rec_descriptor (record, record_status, encoding_level, thesaurus)
1320 vandelay.marc21_extract_fixed_field(marc,'RecStat'),
1321 vandelay.marc21_extract_fixed_field(marc,'ELvl'),
1322 authority.extract_thesaurus(marc)
1323 FROM authority.record_entry
1327 $func$ LANGUAGE PLPGSQL;
1329 CREATE OR REPLACE FUNCTION authority.reingest_authority_full_rec( auth_id BIGINT ) RETURNS VOID AS $func$
1331 DELETE FROM authority.full_rec WHERE record = auth_id;
1332 INSERT INTO authority.full_rec (record, tag, ind1, ind2, subfield, value)
1333 SELECT record, tag, ind1, ind2, subfield, value FROM authority.flatten_marc( auth_id );
1337 $func$ LANGUAGE PLPGSQL;
1339 -- Given an authority record's ID, control set ID (if known), and marc::XML,
1340 -- return all links to other authority records in the form of rows that
1341 -- can be inserted into authority.authority_linking.
1342 CREATE OR REPLACE FUNCTION authority.calculate_authority_linking(
1343 rec_id BIGINT, rec_control_set INT, rec_marc_xml XML
1344 ) RETURNS SETOF authority.authority_linking AS $func$
1346 acsaf authority.control_set_authority_field%ROWTYPE;
1348 aal authority.authority_linking%ROWTYPE;
1350 IF rec_control_set IS NULL THEN
1351 -- No control_set on record? Guess at one
1352 SELECT control_set INTO rec_control_set
1353 FROM authority.control_set_authority_field
1356 XPATH('//*[starts-with(@tag,"1")]/@tag',rec_marc_xml)::TEXT[]
1361 RAISE WARNING 'Could not even guess at control set for authority record %', rec_id;
1366 aal.source := rec_id;
1369 SELECT * FROM authority.control_set_authority_field
1370 WHERE control_set = rec_control_set
1371 AND linking_subfield IS NOT NULL
1372 AND main_entry IS NOT NULL
1374 -- Loop over the trailing-number contents of all linking subfields
1376 SELECT SUBSTRING( x::TEXT, '\d+$' )
1382 || acsaf.linking_subfield
1389 -- Ignore links that are null, malformed, circular, or point to
1390 -- non-existent authority records.
1391 IF link IS NOT NULL AND link::BIGINT <> rec_id THEN
1392 PERFORM * FROM authority.record_entry WHERE id = link::BIGINT;
1394 aal.target := link::BIGINT;
1395 aal.field := acsaf.id;
1402 $func$ LANGUAGE PLPGSQL;
1404 -- AFTER UPDATE OR INSERT trigger for authority.record_entry
1405 CREATE OR REPLACE FUNCTION authority.indexing_ingest_or_delete () RETURNS TRIGGER AS $func$
1407 ashs authority.simple_heading%ROWTYPE;
1408 mbe_row metabib.browse_entry%ROWTYPE;
1413 IF NEW.deleted IS TRUE THEN -- If this authority is deleted
1414 DELETE FROM authority.bib_linking WHERE authority = NEW.id; -- Avoid updating fields in bibs that are no longer visible
1415 DELETE FROM authority.full_rec WHERE record = NEW.id; -- Avoid validating fields against deleted authority records
1416 DELETE FROM authority.simple_heading WHERE record = NEW.id;
1417 -- Should remove matching $0 from controlled fields at the same time?
1419 -- XXX What do we about the actual linking subfields present in
1420 -- authority records that target this one when this happens?
1421 DELETE FROM authority.authority_linking
1422 WHERE source = NEW.id OR target = NEW.id;
1424 RETURN NEW; -- and we're done
1427 IF TG_OP = 'UPDATE' THEN -- re-ingest?
1428 PERFORM * FROM config.internal_flag WHERE name = 'ingest.reingest.force_on_same_marc' AND enabled;
1430 IF NOT FOUND AND OLD.marc = NEW.marc THEN -- don't do anything if the MARC didn't change
1434 -- Unless there's a setting stopping us, propagate these updates to any linked bib records when the heading changes
1435 PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_auto_update' AND enabled;
1437 IF NOT FOUND AND NEW.heading <> OLD.heading THEN
1438 PERFORM authority.propagate_changes(NEW.id);
1441 DELETE FROM authority.simple_heading WHERE record = NEW.id;
1442 DELETE FROM authority.authority_linking WHERE source = NEW.id;
1445 INSERT INTO authority.authority_linking (source, target, field)
1446 SELECT source, target, field FROM authority.calculate_authority_linking(
1447 NEW.id, NEW.control_set, NEW.marc::XML
1450 FOR ashs IN SELECT * FROM authority.simple_heading_set(NEW.marc) LOOP
1452 INSERT INTO authority.simple_heading (record,atag,value,sort_value,thesaurus)
1453 VALUES (ashs.record, ashs.atag, ashs.value, ashs.sort_value, ashs.thesaurus);
1454 ash_id := CURRVAL('authority.simple_heading_id_seq'::REGCLASS);
1456 SELECT INTO mbe_row * FROM metabib.browse_entry
1457 WHERE value = ashs.value AND sort_value = ashs.sort_value;
1460 mbe_id := mbe_row.id;
1462 INSERT INTO metabib.browse_entry
1463 ( value, sort_value ) VALUES
1464 ( ashs.value, ashs.sort_value );
1466 mbe_id := CURRVAL('metabib.browse_entry_id_seq'::REGCLASS);
1469 INSERT INTO metabib.browse_entry_simple_heading_map (entry,simple_heading) VALUES (mbe_id,ash_id);
1473 -- Flatten and insert the afr data
1474 PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_full_rec' AND enabled;
1476 PERFORM authority.reingest_authority_full_rec(NEW.id);
1477 PERFORM * FROM config.internal_flag WHERE name = 'ingest.disable_authority_rec_descriptor' AND enabled;
1479 PERFORM authority.reingest_authority_rec_descriptor(NEW.id);
1485 $func$ LANGUAGE PLPGSQL;
1488 CREATE TRIGGER fingerprint_tgr BEFORE INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.fingerprint_trigger ('eng','BKS');
1489 CREATE TRIGGER aaa_indexing_ingest_or_delete AFTER INSERT OR UPDATE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE biblio.indexing_ingest_or_delete ();
1490 CREATE TRIGGER bbb_simple_rec_trigger AFTER INSERT OR UPDATE OR DELETE ON biblio.record_entry FOR EACH ROW EXECUTE PROCEDURE reporter.simple_rec_trigger ();
1492 CREATE TRIGGER map_thesaurus_to_control_set BEFORE INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE authority.map_thesaurus_to_control_set ();
1493 CREATE TRIGGER aaa_auth_ingest_or_delete AFTER INSERT OR UPDATE ON authority.record_entry FOR EACH ROW EXECUTE PROCEDURE authority.indexing_ingest_or_delete ();
1495 -- Utility routines, callable via cstore
1497 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_val INTERVAL )
1498 RETURNS INTEGER AS $$
1500 RETURN EXTRACT( EPOCH FROM interval_val );
1502 $$ LANGUAGE plpgsql;
1504 CREATE OR REPLACE FUNCTION config.interval_to_seconds( interval_string TEXT )
1505 RETURNS INTEGER AS $$
1507 RETURN config.interval_to_seconds( interval_string::INTERVAL );
1509 $$ LANGUAGE plpgsql;
1511 CREATE OR REPLACE FUNCTION vandelay.ingest_items ( import_id BIGINT, attr_def_id BIGINT ) RETURNS SETOF vandelay.import_item AS $$
1522 deposit_amount TEXT;
1538 tmp_attr_set RECORD;
1539 attr_set vandelay.import_item%ROWTYPE;
1546 SELECT * INTO attr_def FROM vandelay.import_item_attr_definition WHERE id = attr_def_id;
1550 attr_set.definition := attr_def.id;
1552 -- Build the combined XPath
1556 WHEN attr_def.owning_lib IS NULL THEN 'null()'
1557 WHEN LENGTH( attr_def.owning_lib ) = 1 THEN '*[@code="' || attr_def.owning_lib || '"]'
1558 ELSE '*' || attr_def.owning_lib
1563 WHEN attr_def.circ_lib IS NULL THEN 'null()'
1564 WHEN LENGTH( attr_def.circ_lib ) = 1 THEN '*[@code="' || attr_def.circ_lib || '"]'
1565 ELSE '*' || attr_def.circ_lib
1570 WHEN attr_def.call_number IS NULL THEN 'null()'
1571 WHEN LENGTH( attr_def.call_number ) = 1 THEN '*[@code="' || attr_def.call_number || '"]'
1572 ELSE '*' || attr_def.call_number
1577 WHEN attr_def.copy_number IS NULL THEN 'null()'
1578 WHEN LENGTH( attr_def.copy_number ) = 1 THEN '*[@code="' || attr_def.copy_number || '"]'
1579 ELSE '*' || attr_def.copy_number
1584 WHEN attr_def.status IS NULL THEN 'null()'
1585 WHEN LENGTH( attr_def.status ) = 1 THEN '*[@code="' || attr_def.status || '"]'
1586 ELSE '*' || attr_def.status
1591 WHEN attr_def.location IS NULL THEN 'null()'
1592 WHEN LENGTH( attr_def.location ) = 1 THEN '*[@code="' || attr_def.location || '"]'
1593 ELSE '*' || attr_def.location
1598 WHEN attr_def.circulate IS NULL THEN 'null()'
1599 WHEN LENGTH( attr_def.circulate ) = 1 THEN '*[@code="' || attr_def.circulate || '"]'
1600 ELSE '*' || attr_def.circulate
1605 WHEN attr_def.deposit IS NULL THEN 'null()'
1606 WHEN LENGTH( attr_def.deposit ) = 1 THEN '*[@code="' || attr_def.deposit || '"]'
1607 ELSE '*' || attr_def.deposit
1612 WHEN attr_def.deposit_amount IS NULL THEN 'null()'
1613 WHEN LENGTH( attr_def.deposit_amount ) = 1 THEN '*[@code="' || attr_def.deposit_amount || '"]'
1614 ELSE '*' || attr_def.deposit_amount
1619 WHEN attr_def.ref IS NULL THEN 'null()'
1620 WHEN LENGTH( attr_def.ref ) = 1 THEN '*[@code="' || attr_def.ref || '"]'
1621 ELSE '*' || attr_def.ref
1626 WHEN attr_def.holdable IS NULL THEN 'null()'
1627 WHEN LENGTH( attr_def.holdable ) = 1 THEN '*[@code="' || attr_def.holdable || '"]'
1628 ELSE '*' || attr_def.holdable
1633 WHEN attr_def.price IS NULL THEN 'null()'
1634 WHEN LENGTH( attr_def.price ) = 1 THEN '*[@code="' || attr_def.price || '"]'
1635 ELSE '*' || attr_def.price
1640 WHEN attr_def.barcode IS NULL THEN 'null()'
1641 WHEN LENGTH( attr_def.barcode ) = 1 THEN '*[@code="' || attr_def.barcode || '"]'
1642 ELSE '*' || attr_def.barcode
1647 WHEN attr_def.circ_modifier IS NULL THEN 'null()'
1648 WHEN LENGTH( attr_def.circ_modifier ) = 1 THEN '*[@code="' || attr_def.circ_modifier || '"]'
1649 ELSE '*' || attr_def.circ_modifier
1654 WHEN attr_def.circ_as_type IS NULL THEN 'null()'
1655 WHEN LENGTH( attr_def.circ_as_type ) = 1 THEN '*[@code="' || attr_def.circ_as_type || '"]'
1656 ELSE '*' || attr_def.circ_as_type
1661 WHEN attr_def.alert_message IS NULL THEN 'null()'
1662 WHEN LENGTH( attr_def.alert_message ) = 1 THEN '*[@code="' || attr_def.alert_message || '"]'
1663 ELSE '*' || attr_def.alert_message
1668 WHEN attr_def.opac_visible IS NULL THEN 'null()'
1669 WHEN LENGTH( attr_def.opac_visible ) = 1 THEN '*[@code="' || attr_def.opac_visible || '"]'
1670 ELSE '*' || attr_def.opac_visible
1675 WHEN attr_def.pub_note IS NULL THEN 'null()'
1676 WHEN LENGTH( attr_def.pub_note ) = 1 THEN '*[@code="' || attr_def.pub_note || '"]'
1677 ELSE '*' || attr_def.pub_note
1681 WHEN attr_def.priv_note IS NULL THEN 'null()'
1682 WHEN LENGTH( attr_def.priv_note ) = 1 THEN '*[@code="' || attr_def.priv_note || '"]'
1683 ELSE '*' || attr_def.priv_note
1688 WHEN attr_def.internal_id IS NULL THEN 'null()'
1689 WHEN LENGTH( attr_def.internal_id ) = 1 THEN '*[@code="' || attr_def.internal_id || '"]'
1690 ELSE '*' || attr_def.internal_id
1695 WHEN attr_def.stat_cat_data IS NULL THEN 'null()'
1696 WHEN LENGTH( attr_def.stat_cat_data ) = 1 THEN '*[@code="' || attr_def.stat_cat_data || '"]'
1697 ELSE '*' || attr_def.stat_cat_data
1702 WHEN attr_def.parts_data IS NULL THEN 'null()'
1703 WHEN LENGTH( attr_def.parts_data ) = 1 THEN '*[@code="' || attr_def.parts_data || '"]'
1704 ELSE '*' || attr_def.parts_data
1709 xpaths := ARRAY[owning_lib, circ_lib, call_number, copy_number, status, location, circulate,
1710 deposit, deposit_amount, ref, holdable, price, barcode, circ_modifier, circ_as_type,
1711 alert_message, pub_note, priv_note, internal_id, stat_cat_data, parts_data, opac_visible];
1715 FROM oils_xpath_tag_to_table( (SELECT marc FROM vandelay.queued_bib_record WHERE id = import_id), attr_def.tag, xpaths)
1716 AS t( ol TEXT, clib TEXT, cn TEXT, cnum TEXT, cs TEXT, cl TEXT, circ TEXT,
1717 dep TEXT, dep_amount TEXT, r TEXT, hold TEXT, pr TEXT, bc TEXT, circ_mod TEXT,
1718 circ_as TEXT, amessage TEXT, note TEXT, pnote TEXT, internal_id TEXT,
1719 stat_cat_data TEXT, parts_data TEXT, opac_vis TEXT )
1722 attr_set.import_error := NULL;
1723 attr_set.error_detail := NULL;
1724 attr_set.deposit_amount := NULL;
1725 attr_set.copy_number := NULL;
1726 attr_set.price := NULL;
1727 attr_set.circ_modifier := NULL;
1728 attr_set.location := NULL;
1729 attr_set.barcode := NULL;
1730 attr_set.call_number := NULL;
1732 IF tmp_attr_set.pr != '' THEN
1733 tmp_str = REGEXP_REPLACE(tmp_attr_set.pr, E'[^0-9\\.]', '', 'g');
1734 IF tmp_str = '' THEN
1735 attr_set.import_error := 'import.item.invalid.price';
1736 attr_set.error_detail := tmp_attr_set.pr; -- original value
1737 RETURN NEXT attr_set; CONTINUE;
1739 attr_set.price := tmp_str::NUMERIC(8,2);
1742 IF tmp_attr_set.dep_amount != '' THEN
1743 tmp_str = REGEXP_REPLACE(tmp_attr_set.dep_amount, E'[^0-9\\.]', '', 'g');
1744 IF tmp_str = '' THEN
1745 attr_set.import_error := 'import.item.invalid.deposit_amount';
1746 attr_set.error_detail := tmp_attr_set.dep_amount;
1747 RETURN NEXT attr_set; CONTINUE;
1749 attr_set.deposit_amount := tmp_str::NUMERIC(8,2);
1752 IF tmp_attr_set.cnum != '' THEN
1753 tmp_str = REGEXP_REPLACE(tmp_attr_set.cnum, E'[^0-9]', '', 'g');
1754 IF tmp_str = '' THEN
1755 attr_set.import_error := 'import.item.invalid.copy_number';
1756 attr_set.error_detail := tmp_attr_set.cnum;
1757 RETURN NEXT attr_set; CONTINUE;
1759 attr_set.copy_number := tmp_str::INT;
1762 IF tmp_attr_set.ol != '' THEN
1763 SELECT id INTO attr_set.owning_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.ol); -- INT
1765 attr_set.import_error := 'import.item.invalid.owning_lib';
1766 attr_set.error_detail := tmp_attr_set.ol;
1767 RETURN NEXT attr_set; CONTINUE;
1771 IF tmp_attr_set.clib != '' THEN
1772 SELECT id INTO attr_set.circ_lib FROM actor.org_unit WHERE shortname = UPPER(tmp_attr_set.clib); -- INT
1774 attr_set.import_error := 'import.item.invalid.circ_lib';
1775 attr_set.error_detail := tmp_attr_set.clib;
1776 RETURN NEXT attr_set; CONTINUE;
1780 IF tmp_attr_set.cs != '' THEN
1781 SELECT id INTO attr_set.status FROM config.copy_status WHERE LOWER(name) = LOWER(tmp_attr_set.cs); -- INT
1783 attr_set.import_error := 'import.item.invalid.status';
1784 attr_set.error_detail := tmp_attr_set.cs;
1785 RETURN NEXT attr_set; CONTINUE;
1789 IF COALESCE(tmp_attr_set.circ_mod, '') = '' THEN
1791 -- no circ mod defined, see if we should apply a default
1792 SELECT INTO attr_set.circ_modifier TRIM(BOTH '"' FROM value)
1793 FROM actor.org_unit_ancestor_setting(
1794 'vandelay.item.circ_modifier.default',
1798 -- make sure the value from the org setting is still valid
1799 PERFORM 1 FROM config.circ_modifier WHERE code = attr_set.circ_modifier;
1801 attr_set.import_error := 'import.item.invalid.circ_modifier';
1802 attr_set.error_detail := tmp_attr_set.circ_mod;
1803 RETURN NEXT attr_set; CONTINUE;
1808 SELECT code INTO attr_set.circ_modifier FROM config.circ_modifier WHERE code = tmp_attr_set.circ_mod;
1810 attr_set.import_error := 'import.item.invalid.circ_modifier';
1811 attr_set.error_detail := tmp_attr_set.circ_mod;
1812 RETURN NEXT attr_set; CONTINUE;
1816 IF tmp_attr_set.circ_as != '' THEN
1817 SELECT code INTO attr_set.circ_as_type FROM config.coded_value_map WHERE ctype = 'item_type' AND code = tmp_attr_set.circ_as;
1819 attr_set.import_error := 'import.item.invalid.circ_as_type';
1820 attr_set.error_detail := tmp_attr_set.circ_as;
1821 RETURN NEXT attr_set; CONTINUE;
1825 IF COALESCE(tmp_attr_set.cl, '') = '' THEN
1826 -- no location specified, see if we should apply a default
1828 SELECT INTO attr_set.location TRIM(BOTH '"' FROM value)
1829 FROM actor.org_unit_ancestor_setting(
1830 'vandelay.item.copy_location.default',
1834 -- make sure the value from the org setting is still valid
1835 PERFORM 1 FROM asset.copy_location
1836 WHERE id = attr_set.location AND NOT deleted;
1838 attr_set.import_error := 'import.item.invalid.location';
1839 attr_set.error_detail := tmp_attr_set.cs;
1840 RETURN NEXT attr_set; CONTINUE;
1844 -- search up the org unit tree for a matching copy location
1845 WITH RECURSIVE anscestor_depth AS (
1849 FROM actor.org_unit ou
1850 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
1851 WHERE ou.id = COALESCE(attr_set.owning_lib, attr_set.circ_lib)
1856 FROM actor.org_unit ou
1857 JOIN actor.org_unit_type out ON (out.id = ou.ou_type)
1858 JOIN anscestor_depth ot ON (ot.parent_ou = ou.id)
1859 ) SELECT cpl.id INTO attr_set.location
1860 FROM anscestor_depth a
1861 JOIN asset.copy_location cpl ON (cpl.owning_lib = a.id)
1862 WHERE LOWER(cpl.name) = LOWER(tmp_attr_set.cl)
1864 ORDER BY a.depth DESC
1868 attr_set.import_error := 'import.item.invalid.location';
1869 attr_set.error_detail := tmp_attr_set.cs;
1870 RETURN NEXT attr_set; CONTINUE;
1874 attr_set.circulate :=
1875 LOWER( SUBSTRING( tmp_attr_set.circ, 1, 1)) IN ('t','y','1')
1876 OR LOWER(tmp_attr_set.circ) = 'circulating'; -- BOOL
1879 LOWER( SUBSTRING( tmp_attr_set.dep, 1, 1 ) ) IN ('t','y','1')
1880 OR LOWER(tmp_attr_set.dep) = 'deposit'; -- BOOL
1882 attr_set.holdable :=
1883 LOWER( SUBSTRING( tmp_attr_set.hold, 1, 1 ) ) IN ('t','y','1')
1884 OR LOWER(tmp_attr_set.hold) = 'holdable'; -- BOOL
1886 attr_set.opac_visible :=
1887 LOWER( SUBSTRING( tmp_attr_set.opac_vis, 1, 1 ) ) IN ('t','y','1')
1888 OR LOWER(tmp_attr_set.opac_vis) = 'visible'; -- BOOL
1891 LOWER( SUBSTRING( tmp_attr_set.r, 1, 1 ) ) IN ('t','y','1')
1892 OR LOWER(tmp_attr_set.r) = 'reference'; -- BOOL
1894 attr_set.call_number := tmp_attr_set.cn; -- TEXT
1895 attr_set.barcode := tmp_attr_set.bc; -- TEXT,
1896 attr_set.alert_message := tmp_attr_set.amessage; -- TEXT,
1897 attr_set.pub_note := tmp_attr_set.note; -- TEXT,
1898 attr_set.priv_note := tmp_attr_set.pnote; -- TEXT,
1899 attr_set.alert_message := tmp_attr_set.amessage; -- TEXT,
1900 attr_set.internal_id := tmp_attr_set.internal_id::BIGINT;
1901 attr_set.stat_cat_data := tmp_attr_set.stat_cat_data; -- TEXT,
1902 attr_set.parts_data := tmp_attr_set.parts_data; -- TEXT,
1904 RETURN NEXT attr_set;
1913 $$ LANGUAGE PLPGSQL;
1918 CREATE OR REPLACE FUNCTION vandelay.ingest_bib_items ( ) RETURNS TRIGGER AS $func$
1921 item_data vandelay.import_item%ROWTYPE;
1924 IF TG_OP IN ('INSERT','UPDATE') AND NEW.imported_as IS NOT NULL THEN
1928 SELECT item_attr_def INTO attr_def FROM vandelay.bib_queue WHERE id = NEW.queue;
1930 FOR item_data IN SELECT * FROM vandelay.ingest_items( NEW.id::BIGINT, attr_def ) LOOP
1931 INSERT INTO vandelay.import_item (
1960 item_data.definition,
1961 item_data.owning_lib,
1963 item_data.call_number,
1964 item_data.copy_number,
1967 item_data.circulate,
1969 item_data.deposit_amount,
1974 item_data.circ_modifier,
1975 item_data.circ_as_type,
1976 item_data.alert_message,
1978 item_data.priv_note,
1979 item_data.internal_id,
1980 item_data.opac_visible,
1981 item_data.stat_cat_data,
1982 item_data.parts_data,
1983 item_data.import_error,
1984 item_data.error_detail
1990 $func$ LANGUAGE PLPGSQL;
1992 CREATE TRIGGER ingest_item_trigger
1993 AFTER INSERT OR UPDATE ON vandelay.queued_bib_record
1994 FOR EACH ROW EXECUTE PROCEDURE vandelay.ingest_bib_items();
1997 -- evergreen.generic_map_normalizer
1999 CREATE OR REPLACE FUNCTION evergreen.generic_map_normalizer ( TEXT, TEXT ) RETURNS TEXT AS $f$
2003 my $default = $string;
2006 while (/^\s*?(.*?)\s*?=>\s*?(\S+)\s*/) {
2010 $map{$2} = [split(/\s*,\s*/, $1)];
2015 for my $key ( keys %map ) {
2016 return $key if (grep { $_ eq $string } @{ $map{$key} });
2021 $f$ LANGUAGE PLPERLU;
2023 CREATE OR REPLACE FUNCTION actor.address_alert_matches (
2032 mailing_address BOOL DEFAULT FALSE,
2033 billing_address BOOL DEFAULT FALSE
2034 ) RETURNS SETOF actor.address_alert AS $$
2037 FROM actor.address_alert
2040 AND owner IN (SELECT id FROM actor.org_unit_ancestors($1))
2042 (NOT mailing_address AND NOT billing_address)
2043 OR (mailing_address AND $9)
2044 OR (billing_address AND $10)
2049 AND COALESCE($2, '') ~* COALESCE(street1, '.*')
2050 AND COALESCE($3, '') ~* COALESCE(street2, '.*')
2051 AND COALESCE($4, '') ~* COALESCE(city, '.*')
2052 AND COALESCE($5, '') ~* COALESCE(county, '.*')
2053 AND COALESCE($6, '') ~* COALESCE(state, '.*')
2054 AND COALESCE($7, '') ~* COALESCE(country, '.*')
2055 AND COALESCE($8, '') ~* COALESCE(post_code, '.*')
2069 ORDER BY actor.org_unit_proximity(owner, $1)
2072 CREATE OR REPLACE FUNCTION evergreen.coded_value_map_normalizer( input TEXT, ctype TEXT )
2074 SELECT COALESCE(value,$1)
2075 FROM config.coded_value_map
2076 WHERE ctype = $2 AND code = $1;
2079 -- user activity functions --
2081 -- remove transient activity entries on insert of new entries
2082 CREATE OR REPLACE FUNCTION actor.usr_activity_transient_trg () RETURNS TRIGGER AS $$
2084 DELETE FROM actor.usr_activity act USING config.usr_activity_type atype
2085 WHERE atype.transient AND
2086 NEW.etype = atype.id AND
2087 act.etype = atype.id AND
2091 $$ LANGUAGE PLPGSQL;
2093 CREATE TRIGGER remove_transient_usr_activity
2094 BEFORE INSERT ON actor.usr_activity
2095 FOR EACH ROW EXECUTE PROCEDURE actor.usr_activity_transient_trg();
2097 -- given a set of activity criteria, find the most approprate activity type
2098 CREATE OR REPLACE FUNCTION actor.usr_activity_get_type (
2102 ) RETURNS SETOF config.usr_activity_type AS $$
2103 SELECT * FROM config.usr_activity_type
2106 (ewho IS NULL OR ewho = $1) AND
2107 (ewhat IS NULL OR ewhat = $2) AND
2108 (ehow IS NULL OR ehow = $3)
2110 -- BOOL comparisons sort false to true
2111 COALESCE(ewho, '') != COALESCE($1, ''),
2112 COALESCE(ewhat,'') != COALESCE($2, ''),
2113 COALESCE(ehow, '') != COALESCE($3, '')
2117 -- given a set of activity criteria, finds the best
2118 -- activity type and inserts the activity entry
2119 CREATE OR REPLACE FUNCTION actor.insert_usr_activity (
2124 ) RETURNS SETOF actor.usr_activity AS $$
2126 new_row actor.usr_activity%ROWTYPE;
2128 SELECT id INTO new_row.etype FROM actor.usr_activity_get_type(ewho, ewhat, ehow);
2131 INSERT INTO actor.usr_activity (usr, etype)
2132 VALUES (usr, new_row.etype)
2133 RETURNING * INTO new_row;
2134 RETURN NEXT new_row;
2137 $$ LANGUAGE plpgsql;
2139 CREATE OR REPLACE FUNCTION evergreen.rel_bump(terms TEXT[], value TEXT, bumps TEXT[], mults NUMERIC[]) RETURNS NUMERIC AS
2142 my ($terms,$value,$bumps,$mults) = @_;
2146 for (my $id = 0; $id < @$bumps; $id++) {
2147 if ($bumps->[$id] eq 'first_word') {
2148 $retval *= $mults->[$id] if ($value =~ /^$terms->[0]/);
2149 } elsif ($bumps->[$id] eq 'full_match') {
2150 my $fullmatch = join(' ', @$terms);
2151 $retval *= $mults->[$id] if ($value =~ /^$fullmatch$/);
2152 } elsif ($bumps->[$id] eq 'word_order') {
2153 my $wordorder = join('.*', @$terms);
2154 $retval *= $mults->[$id] if ($value =~ /$wordorder/);
2158 $BODY$ LANGUAGE plperlu IMMUTABLE STRICT COST 100;
2160 -- user activity functions --
2163 -- find the most relevant set of credentials for the Z source and org
2164 CREATE OR REPLACE FUNCTION config.z3950_source_credentials_lookup
2165 (source TEXT, owner INTEGER)
2166 RETURNS config.z3950_source_credentials AS $$
2169 FROM config.z3950_source_credentials creds
2170 JOIN actor.org_unit aou ON (aou.id = creds.owner)
2171 JOIN actor.org_unit_type aout ON (aout.id = aou.ou_type)
2172 WHERE creds.source = $1 AND creds.owner IN (
2173 SELECT id FROM actor.org_unit_ancestors($2)
2175 ORDER BY aout.depth DESC LIMIT 1;
2177 $$ LANGUAGE SQL STABLE;
2179 -- since we are not exposing config.z3950_source_credentials
2180 -- via the IDL, providing a stored proc gives us a way to
2181 -- set values in the table via cstore
2182 CREATE OR REPLACE FUNCTION config.z3950_source_credentials_apply
2183 (src TEXT, org INTEGER, uname TEXT, passwd TEXT)
2186 PERFORM 1 FROM config.z3950_source_credentials
2187 WHERE owner = org AND source = src;
2190 IF COALESCE(uname, '') = '' AND COALESCE(passwd, '') = '' THEN
2191 DELETE FROM config.z3950_source_credentials
2192 WHERE owner = org AND source = src;
2194 UPDATE config.z3950_source_credentials
2195 SET username = uname, password = passwd
2196 WHERE owner = org AND source = src;
2199 IF COALESCE(uname, '') <> '' OR COALESCE(passwd, '') <> '' THEN
2200 INSERT INTO config.z3950_source_credentials
2201 (source, owner, username, password)
2202 VALUES (src, org, uname, passwd);
2206 $$ LANGUAGE PLPGSQL;
2208 -- Handy function for transforming marc to a variant available on config.xml_transform
2209 CREATE OR REPLACE FUNCTION evergreen.marc_to (marc text, xfrm text) RETURNS TEXT AS $$
2210 SELECT evergreen.xml_pretty_print(xslt_process($1,xslt)::XML)::TEXT FROM config.xml_transform WHERE name = $2;