1 -- Evergreen DB patch 0783.schema.enforce_use_id_for_tcn.sql
3 -- Sets the TCN value in the biblio.record_entry row to bib ID,
4 -- if the appropriate setting is in place
8 -- check whether patch can be applied
9 SELECT evergreen.upgrade_deps_block_check('0783', :eg_version);
11 -- FIXME: add/check SQL statements to perform the upgrade
12 CREATE OR REPLACE FUNCTION evergreen.maintain_901 () RETURNS TRIGGER AS $func$
15 use MARC::File::XML (BinaryEncoding => 'UTF-8');
18 use Unicode::Normalize;
20 MARC::Charset->assume_unicode(1);
22 my $schema = $_TD->{table_schema};
23 my $marc = MARC::Record->new_from_xml($_TD->{new}{marc});
25 my @old901s = $marc->field('901');
26 $marc->delete_fields(@old901s);
28 if ($schema eq 'biblio') {
29 my $tcn_value = $_TD->{new}{tcn_value};
31 # Set TCN value to record ID?
32 my $id_as_tcn = spi_exec_query("
34 FROM config.global_flag
35 WHERE name = 'cat.bib.use_id_for_tcn'
37 if (($id_as_tcn->{processed}) && $id_as_tcn->{rows}[0]->{enabled} eq 't') {
38 $tcn_value = $_TD->{new}{id};
39 $_TD->{new}{tcn_value} = $tcn_value;
42 my $new_901 = MARC::Field->new("901", " ", " ",
44 "b" => $_TD->{new}{tcn_source},
45 "c" => $_TD->{new}{id},
49 if ($_TD->{new}{owner}) {
50 $new_901->add_subfields("o" => $_TD->{new}{owner});
53 if ($_TD->{new}{share_depth}) {
54 $new_901->add_subfields("d" => $_TD->{new}{share_depth});
57 $marc->append_fields($new_901);
58 } elsif ($schema eq 'authority') {
59 my $new_901 = MARC::Field->new("901", " ", " ",
60 "c" => $_TD->{new}{id},
63 $marc->append_fields($new_901);
64 } elsif ($schema eq 'serial') {
65 my $new_901 = MARC::Field->new("901", " ", " ",
66 "c" => $_TD->{new}{id},
68 "o" => $_TD->{new}{owning_lib},
71 if ($_TD->{new}{record}) {
72 $new_901->add_subfields("r" => $_TD->{new}{record});
75 $marc->append_fields($new_901);
77 my $new_901 = MARC::Field->new("901", " ", " ",
78 "c" => $_TD->{new}{id},
81 $marc->append_fields($new_901);
84 my $xml = $marc->as_xml_record();
86 $xml =~ s/^<\?xml.+\?\s*>//go;
87 $xml =~ s/>\s+</></go;
90 # Embed a version of OpenILS::Application::AppUtils->entityize()
91 # to avoid having to set PERL5LIB for PostgreSQL as well
93 # If we are going to convert non-ASCII characters to XML entities,
94 # we had better be dealing with a UTF8 string to begin with
95 $xml = decode_utf8($xml);
99 # Convert raw ampersands to entities
100 $xml =~ s/&(?!\S+;)/&/gso;
102 # Convert Unicode characters to entities
103 $xml =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
105 $xml =~ s/[\x00-\x1f]//go;
106 $_TD->{new}{marc} = $xml;
109 $func$ LANGUAGE PLPERLU;