3 INSERT INTO config.upgrade_log (version) VALUES ('0472'); -- dbs
5 CREATE OR REPLACE FUNCTION authority.merge_records ( target_record BIGINT, source_record BIGINT ) RETURNS INT AS $func$
7 moved_objects INT := 0;
9 bib_rec biblio.record_entry%ROWTYPE;
10 auth_link authority.bib_linking%ROWTYPE;
14 -- Defining our terms:
15 -- "target record" = the record that will survive the merge
16 -- "source record" = the record that is sacrifing its existence and being
17 -- replaced by the target record
19 -- 1. Update all bib records with the ID from target_record in their $0
20 FOR bib_rec IN SELECT bre.* FROM biblio.record_entry bre
21 INNER JOIN authority.bib_linking abl ON abl.bib = bre.id
22 WHERE abl.authority = source_record LOOP
24 UPDATE biblio.record_entry
25 SET marc = REGEXP_REPLACE(marc,
26 E'(<subfield\\s+code="0"\\s*>[^<]*?\\))' || source_record || '<',
27 E'\\1' || target_record || '<', 'g')
28 WHERE id = bib_rec.id;
30 moved_objects := moved_objects + 1;
33 -- 2. Grab the current value of reingest on same MARC flag
34 SELECT enabled INTO ingest_same
35 FROM config.internal_flag
36 WHERE name = 'ingest.reingest.force_on_same_marc'
39 -- 3. Temporarily set reingest on same to TRUE
40 UPDATE config.internal_flag
42 WHERE name = 'ingest.reingest.force_on_same_marc'
45 -- 4. Make a harmless update to target_record to trigger auto-update
46 -- in linked bibliographic records
47 UPDATE authority.record_entry
49 WHERE id = target_record;
51 -- 5. "Delete" source_record
52 DELETE FROM authority.record_entry
53 WHERE id = source_record;
55 -- 6. Set "reingest on same MARC" flag back to initial value
56 UPDATE config.internal_flag
57 SET enabled = ingest_same
58 WHERE name = 'ingest.reingest.force_on_same_marc'
63 $func$ LANGUAGE plpgsql;