#!/usr/bin/perl # --------------------------------------------------------------- # Copyright © 2013 Merrimack Valley Library Consortium # Jason Stephenson # # This program is part of Evergreen; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # --------------------------------------------------------------- use strict; use warnings; use OpenILS::Utils::Fieldmapper; use OpenILS::Application::AppUtils; use OpenSRF::Utils::JSON; use MARC::Field; use MARC::Record; use MARC::File::XML (BinaryEncoding => 'UTF-8'); use Date::Manip::Date; use Encode; my $U = 'OpenILS::Application::AppUtils'; binmode(STDERR, ':utf8'); package Marque; our $config = Marque::Config->new(); Fieldmapper->import(IDL => $config->option_value('xml-idl')); # Look for passed in ids: my @ids = (); if ($config->need_ids()) { print STDERR "Waiting for input\n" if (-t); while (my $i = <>) { push @ids, $i if ($i =~ /^\s*[0-9]+\s*$/); } } die "IDs required but none entered, exiting\n" if ($config->need_ids() && !@ids); my $exporter; if ($config->option_value('type') eq 'authority') { $exporter = Marque::Authority->new(\@ids); } else { $exporter = Marque::Biblio->new(\@ids); } Marque::Output::output($exporter); # ------------------------------------------------------------------ package Marque::Config; use Getopt::Long; use List::MoreUtils qw(none); use OpenSRF::System; use OpenSRF::Utils::SettingsClient; use constant FORMATS => qw(USMARC UNIMARC XML BRE ARE); use constant STORES => qw(reporter cstore storage); use constant TYPES => qw(authority biblio); sub new { my $class = shift; my $self = {}; # For command line options. my %opts; # set some default values $opts{'format'} = 'USMARC'; $opts{'encoding'} = 'UTF-8'; $opts{'type'} = 'biblio'; $opts{'money'} = '$'; $opts{'timeout'} = 0; $opts{'config'} = '@sysconfdir@/opensrf_core.xml'; $opts{'store'} = 'reporter'; $opts{'852b'} = 'both'; $opts{'batch-size'} = 10000; GetOptions(\%opts, 'help', 'items', '852b=s', 'exclude-hidden', 'mfhd', 'all', 'replace_001', 'strip=s@', 'location=s', 'money=s', 'config=s', 'format=s', 'type=s', 'xml-idl=s', 'encoding|e=s', 'timeout=i', 'library=s@', 'descendants=s@', 'since=s', 'store=s', 'uris', 'debug', 'pipe', 'batch-size=i'); if ($opts{help}) { print <<"HELP"; This script exports MARC authority, bibliographic, and serial holdings records from an Evergreen database. Input to this script can consist of a list of record IDs, with one record ID per line, corresponding to the record ID in the Evergreen database table of your requested record type. Alternately, passing the --all option will attempt to export all records of the specified type from the Evergreen database. The --all option starts at record ID 1 and increments the ID by 1 until the largest ID in the database is retrieved. This may not be very efficient for databases with large gaps in their ID sequences. Usage: $0 [options] --help or -h This screen. --config or -c Configuration file [@sysconfdir@/opensrf_core.xml] --format or -f Output format (USMARC, UNIMARC, XML, BRE, ARE) [USMARC] --encoding or -e Output encoding (UTF-8, ISO-8859-?, MARC8) [UTF-8] --xml-idl or -x Location of the IDL XML --timeout Remains for backward compatibility. No longer used. --type or -t Record type (BIBLIO, AUTHORITY) [BIBLIO] --all or -a Export all records; ignores input list --replace_001 Replace the 001 field value with the record ID --strip tagRE/subRE Strip fields or subfields matching regular expressions --store Use the given storage backend to connect to the database. Choices are (reporter, cstore, storage) [reporter] --since Export records modified since a certain date and time. --pipe Force record ids to be read from list on standard input, despite other options to the contrary --batch-size Number of records to fetch at a time for processing (default 10000). This option can be adjusted depending on your database performance or environment. Doing smaller batch sizes can sometimes speed up the extraction. Finding the best value for your situation requires experimentation. Additional options for type = 'BIBLIO': --items or -i Include items (holdings) in the output --852b Accepts 'owning_lib', 'circ_lib', or 'both' to control whether the 852$b in exported embedded holdings has the owning library, the circulation library, or both in separate repeats of the $b. If not supplied, defaults to 'both', which is the legacy behavior. --money Currency symbol to use in item price field [\$] --mfhd Export serial MFHD records for associated bib records Not compatible with --format=BRE --location or -l MARC Location Code for holdings from http://www.loc.gov/marc/organizations/orgshome.html --library Export the bibliographic records that have attached holdings for the listed library or libraries as identified by shortname --descendants Like the --library option, but org. tree aware. It exports records that have attached holdings for the specified org. unit and all of its descendants in the tree. --uris or -u Include records with located URIs in the output --exclude-hidden Exclude records and items if the item is not OPAC-visible per its org unit, status, shelving, location, or flag on the item record. This option is effective only if the --library and/or --items flags are supplied. This option takes precedence; for example, if the org unit specified by --library is not OPAC-visible, its records will not be included in the export. Examples: To export a set of USMARC records in a file named "output_file" based on the IDs contained in a file named "list_of_ids": cat list_of_ids | $0 > output_file To export a set of MARC21XML authority records in a file named "output.xml" for all authority records in the database: $0 --format XML --type AUTHORITY --all > output.xml To export a set of USMARC bibliographic records encoded in UTF-8 in a file named "sys1_bibs.mrc" based on records which have attached callnumbers for the libraries with the short names "BR1" and "BR2": $0 --library BR1 --library BR2 --encoding UTF-8 > sys1_bibs.mrc The --strip option can be used more than once which imples an "OR" operation. If the field argument is omitted (e.g., "/0", it is treated like "..." (all fields). If the subfield argument is omitted (e.g. "100/", it is treated like "." (all subfields). Examples: --strip /0 Remove all 0 subfields --strip 1[23]. Remove fields with tags 120 through 139, inclusive. --strip 856/x Remove subfield x from 856 tags HELP exit; } OpenSRF::System->bootstrap_client( config_file => $opts{config} ); my $sclient = OpenSRF::Utils::SettingsClient->new(); unless ($opts{'xml-idl'}) { $opts{'xml-idl'} = $sclient->config_value('IDL'); } # Validate some of the settings. if ($opts{all} && ($opts{library} || $opts{descendants})) { die('Incompatible arguments: you cannot combine a request for all ' . 'records with a request for records by library'); } if ($opts{all} && $opts{since}) { die('Incompatible arguments: you cannot combine a request for all ' . 'records with a request for records added or changed since a certain date'); } if ($opts{all} && $opts{pipe}) { die('Incompatible arguments: you cannot combine a request for all ' . 'records with the option to read record ids via standard input'); } if ($opts{since} && $opts{pipe}) { die('Incompatible arguments: you cannot combine a request for records added or '. 'changed since a certain date with ' . 'the option to read record ids via standard input'); } $opts{type} = lc($opts{type}); if (none {$_ eq $opts{type}} (TYPES)) { die "Please select a supported type. ". "Right now that means one of [". join('|',(TYPES)). "]\n"; } $opts{format} = uc($opts{format}); if (none {$_ eq $opts{format}} (FORMATS)) { die "Please select a supported format. ". "Right now that means one of [". join('|',(FORMATS)). "]\n"; } # Process --strip arguments. They are in the form tagRE/subRE. Note # that the RE pieces cannot contain a slash (/), as this would create # ambiguity. If there is no /subRE, then it's OK, and just the tagRE # is specified. # $opts{strip} is an array-ref for this multi-valued option. my @strip = (); foreach my $strip_value (@{$opts{strip}}) { my $trec = {}; if ($strip_value eq "/") { print STDERR "Ignoring empty --strip parameter; all records would be empty.\n"; next; } if ($strip_value =~ /\//) { $trec->{tag} = $`; $trec->{tag} = "..." if ($` eq ""); $trec->{subfield} = $'; $trec->{subfield} = "." if ($' eq ""); } else { # No slash case $trec->{tag} = $strip_value; $trec->{subfield} = ''; } push @strip, $trec; } if ($opts{format} eq 'ARE' && $opts{type} ne 'authority') { die "Format ARE is not compatible with type " . $opts{type}; } if ($opts{format} eq 'BRE' && $opts{type} ne 'biblio') { die "Format BRE is not compatible with type " . $opts{type}; } if ($opts{format} eq 'BRE' && $opts{items}) { die "Format BRE is not compatible with exporting holdings." } if ($opts{mfhd}) { if ($opts{type} ne 'biblio') { die "MFHD export only works with bibliographic records."; } elsif ($opts{format} eq 'BRE') { die "MFHD export incompatible with format BRE."; } } if ($opts{'852b'} ne 'circ_lib' && $opts{'852b'} ne 'owning_lib' && $opts{'852b'} ne 'both') { die "Invalid value '" . $opts{'852b'} . "' for --852b; must be 'circ_lib', 'owning_lib', or 'both'"; } $opts{store} = lc($opts{store}); if (none {$_ eq $opts{store}} (STORES)) { die "Please select a supported store. ". "Right now that means one of [". join('|',(STORES)). "]\n"; } else { my $app; if ($opts{store} eq 'reporter') { $app = 'open-ils.reporter-store'; } else { $app = 'open-ils.' . $opts{store}; } if ($app eq 'open-ils.storage') { $self->{dbsettings} = $sclient->config_value( apps => $app => app_settings => databases => 'database'); } else { $self->{dbsettings} = $sclient->config_value( apps => $app => app_settings => 'database'); } } $opts{encoding} = uc($opts{encoding}); $opts{strip} = \@strip; $self->{'options'} = \%opts; bless $self, $class; return $self; } sub option_value { my ($self, $option) = @_; return $self->{options}->{$option}; } sub database_settings { my $self = shift; return $self->{dbsettings}; } sub need_ids { my $self = shift; my $rv = 1; $rv = 0 if ($self->{options}->{since}); $rv = 0 if ($self->{options}->{library}); $rv = 0 if ($self->{options}->{descendants}); # --pipe trumps the above. $rv = 1 if ($self->{options}->{pipe}); # --all trumps --pipe, but we should throw an error before we get here. $rv = 0 if ($self->{options}->{all}); return $rv; } # ------------------------------------------------------------------ # This package exists to get a connection to the database. Since # we'll need one for both biblio records and authorities, we've made a # single subpackage with a function so that we don't have to duplicate # code. package Marque::Connector; use DBI; # Pass a Marque::Config object's database_settings return value into # this to get a DBI connection. # ex: # my $db = Marque::Connector::connect($config->database_settings); sub connect { my $args = shift; # Build a connect string from the args. my $connect_string = 'DBI:Pg:'; $connect_string .= 'dbname=' . $args->{db} . ';'; $connect_string .= 'host=' . $args->{host} . ';'; $connect_string .= 'port=' . $args->{port}; my $db_handle = DBI->connect($connect_string, $args->{user}, $args->{pw}); return $db_handle; } # A function to get the date into a format better for PostgreSQL. sub db_date { my $input = shift; my $date; if (ref($input) eq 'Date::Manip::Date') { $date = $input; } else { $date = Date::Manip::Date->new(); if ($date->parse($input)) { die "Can't parse date $input"; } } return $date->printf("%Y-%m-%dT%H:%M:%S%z"); } # ------------------------------------------------------------------ # You would typically have the next two packages inherit from a common # superclass, but ineritance doesn't seem to work when all packages # are in single file, so we have some duplicated code between these # two. # Get bibliographic records from the database. package Marque::Biblio; sub new { my $class = shift; my $idlist = shift; my $self = {idlist => $idlist}; $self->{handle} = Marque::Connector::connect( $Marque::config->database_settings); $self->{since_date} = Date::Manip::Date->new; $self->{since_date}->parse($Marque::config->option_value('since')); # We need multiple fieldmapper classes depending on our # options. We'll just get the information that we'll need for them # all right here instead of only fetching the information when # needed. $self->{breClass} = Fieldmapper::class_for_hint('bre'); $self->{acnClass} = Fieldmapper::class_for_hint('acn'); $self->{acpClass} = Fieldmapper::class_for_hint('acp'); $self->{sreClass} = Fieldmapper::class_for_hint('sre'); $self->{acnpClass} = Fieldmapper::class_for_hint('acnp'); $self->{acnsClass} = Fieldmapper::class_for_hint('acns'); $self->{auricnmClass} = Fieldmapper::class_for_hint('auricnm'); # Make an arrayref of shortname ids if the library option was # specified: $self->{libs} = []; if ($Marque::config->option_value('library')) { # This is done not only for speed, but to prevent SQL injection. my $query = 'select id from actor.org_unit where shortname=any(?::text[])'; if ($Marque::config->option_value('exclude-hidden')) { $query .= ' AND opac_visible'; } my $sth = $self->{handle}->prepare($query); if ($sth->execute($Marque::config->option_value('library'))) { my $r = $sth->fetchall_arrayref(); my @ids = map {$_->[0]} @{$r}; $self->{libs} = \@ids; $sth->finish(); } } # Ditto for descendants. We don't worry about redundancy, the db can deal with it. if ($Marque::config->option_value('descendants')) { # Unlike the above, we're looping to make this simpler in the database. my $query = 'select id, opac_visible from actor.org_unit_descendants((select id from actor.org_unit where shortname=?))'; my $sth = $self->{handle}->prepare($query); foreach my $shortname (@{$Marque::config->option_value('descendants')}) { if ($sth->execute($shortname)) { my $r = $sth->fetchall_arrayref(); my @ids = (); if ($Marque::config->option_value('exclude-hidden')) { @ids = map {$_->[0]} grep {$_->[1]} @{$r}; } else { @ids = map {$_->[0]} @{$r}; } push(@{$self->{libs}}, @ids); $sth->finish(); } } } bless $self, $class; return $self; } sub build_query { my $self = shift; # TODO: There is some unfortunate code repetition in this # subroutine and it is now about 93 lines long with comments and # whitespace. It should probably be refactored into a series of # smaller subroutines to avoid the repetition. # Get the field names and tables for our classes. We add the fully # qualified table names to the fields so that the joins will work. my $breTable = $self->{breClass}->Table(); my @breFields = map {$breTable . '.' . $_} $self->{breClass}->real_fields(); my $acnTable = $self->{acnClass}->Table(); my $acpTable = $self->{acpClass}->Table(); my $acnpTable = $self->{acnpClass}->Table(); my $acnsTable = $self->{acnsClass}->Table(); my $auricnmTable = $self->{auricnmClass}->Table(); # Now we build the query in pieces: # We always select the bre fields: my $select = 'select distinct ' . join(',', @breFields); # We always use the bre table. my $from = "from $breTable"; # If have the libraries or items options, we need to join the # asset.call_number table. If we have both, this variable checks # that it has already been joined so we don't create an invalid # query. my $acn_joined = 0; # Join to the acn table as needed for the library option. if (@{$self->{libs}}) { $acn_joined = 1; $from .= <{libs}}) . ")"; $from .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since')); } if ($Marque::config->option_value('items')) { unless ($acn_joined) { $from .= "\njoin $acnTable on $acnTable.record = $breTable.id"; if ($Marque::config->option_value('exclude-hidden')) { $from .= "\n AND $acnTable.owning_lib in (select id from actor.org_unit where opac_visible)"; } $from .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since')); } $from .= "\njoin $acpTable on $acpTable.call_number = $acnTable.id"; $from .= "\nand $acpTable.deleted = 'f'" unless ($Marque::config->option_value('since')); $from .= "\nand $acpTable.opac_visible" if ($Marque::config->option_value('exclude-hidden')); $from .= "\nleft outer join $acnpTable on $acnTable.prefix = $acnpTable.id"; $from .= "\nleft outer join $acnsTable on $acnTable.suffix = $acnsTable.id"; } # The where really depends on a few options: my $where = "where $breTable.id > 0 and "; # We fill in the where as necessary. if ($self->{idlist} && @{$self->{idlist}}) { $where .= "$breTable.id in (" . join(',', @{$self->{idlist}}) . ')'; } elsif ($Marque::config->option_value('since')) { my $since_str = Marque::Connector::db_date($self->{since_date}); $where .= "($breTable.edit_date > '$since_str'"; $where .= " or $breTable.create_date > '$since_str')"; } else { # We want all non-deleted records. $where .= "$breTable.deleted = 'f'"; } # Support the --uris option. It is orthogonal to --items, so we # may have to build a second query to use with a UNION DISTINCT. my $uri_union = ""; if ($Marque::config->option_value('uris')) { if ($Marque::config->option_value('items')) { # Build UNION DISTINCT for main query. $uri_union = "\nunion distinct\n"; $uri_union .= $select; $uri_union .= "\nfrom $breTable"; $uri_union .= "\njoin $acnTable on $acnTable.record = $breTable.id"; $uri_union .= "\nand $acnTable.owning_lib in (" . join(',', @{$self->{libs}}) . ")" if (@{$self->{libs}}); $uri_union .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since')); $uri_union .= "\njoin $auricnmTable on $auricnmTable.call_number = $acnTable.id"; $uri_union .= "\n$where"; } else { unless ($acn_joined) { $from .= "\njoin $acnTable on $acnTable.record = $breTable.id"; $from .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since')); } $from .= "\njoin $auricnmTable on $auricnmTable.call_number = $acnTable.id"; } } $self->{query} = $select . "\n" . $from . "\n" . $where; $self->{query} .= $uri_union if ($uri_union); $self->{query} .= "\n" . "order by id"; #sort results by bre id. } sub execute_query { my $self = shift; $self->build_query() unless ($self->{query}); unless ($self->{cursor}) { $self->{cursor} = 'DECLARE bibs CURSOR WITH HOLD FOR ' . $self->{query}; $self->{handle}->do($self->{cursor}); $self->{fetchcmd} = 'fetch ' . $Marque::config->option_value('batch-size') . ' from bibs'; } $self->{sth} = $self->{handle}->prepare($self->{fetchcmd}); return $self->{sth}->execute; } sub next { my $self = shift; my $output; # $r holds the record object, either sre or bre. $marc holds the # current record's MARC, either sre.marc or bre.marc my ($r,$marc); # If we have the mfhd option and we've previously retrieved some # sres, then we output one of the retrieved sres for each call # until we run out. These sres "go with" the previous bib record. if ($Marque::config->option_value('mfhd') && $self->{mfhds} && @{$self->{mfhds}}) { $r = shift(@{$self->{mfhds}}); eval { local $SIG{__WARN__} = sub { my $message = "Warning from serial record " . $r->id() . ": " . shift; warn($message); }; $marc = MARC::Record->new_from_xml($r->marc(), $Marque::config->option_value('encoding'), $Marque::config->option_value('format')); }; if ($@) { warn("Error in serial record " . $r->id() . ": $@"); import MARC::File::XML; # Reset SAX Parser. return $self->next(); } } else { my $data = $self->{sth}->fetchrow_hashref; unless ($data){ # We ran out of data, so fetch the next batch. if ($self->execute_query()) { $data = $self->{sth}->fetchrow_hashref; } } if ($data) { $r = $self->{breClass}->from_bare_hash($data); if ($Marque::config->option_value('format') eq 'BRE') { $output = OpenSRF::Utils::JSON->perl2JSON($r); } else { eval { local $SIG{__WARN__} = sub { my $message = "Warning from bibliographic record " . $r->id() . ": " . shift; warn($message); }; $marc = MARC::Record->new_from_xml($r->marc(), $Marque::config->option_value('encoding'), $Marque::config->option_value('format')); }; if ($@) { warn("Error in bibliographic record " . $r->id() . ": $@"); import MARC::File::XML; # Reset SAX Parser. return $self->next(); } if ($Marque::config->option_value('replace_001')) { my $tcn = $marc->field('001'); if ($tcn) { $tcn->update($r->id()); } else { $tcn = MARC::Field->new('001', $r->id()); $marc->insert_fields_ordered($tcn); } } my $strip_arg_ref = $Marque::config->option_value('strip'); my @strip = @{$strip_arg_ref}; foreach my $strip_ref (@strip) { my $tagRE = $strip_ref->{tag}; my $subfieldRE = $strip_ref->{subfield}; if ( $subfieldRE eq "") { # Case 1: Field only check, e.g. "--strip 5.[0,1]" # If the supplied regexp matches the field, then # delete that field. foreach my $test_field ($marc->fields()) { if ($test_field->tag() =~ /$tagRE/) { # A hit! $marc->delete_field($test_field); } } } elsif ($subfieldRE ne "" && $tagRE ne "") { # Case 2: Field & subfield supplied. # Note a blank tag will be wildcarded to "*". # Traverse fields, then traverse subfields if match # is found. foreach my $test_field ($marc->fields()) { if ( !$test_field->is_control_field() && $test_field->tag() =~ /$tagRE/) { # Traverse all subfields: foreach my $test_subfield ($test_field->subfields()) { my $sfcode = @{$test_subfield}[0]; if ($sfcode =~ /$subfieldRE/) { $test_field->delete_subfield($sfcode); } } } } } } if ($Marque::config->option_value('items')) { # If --items was passed discard any static 852 fields; they're either dupes, out-of-sync, or junk. $marc->delete_fields($marc->field('852')); my @acps = $self->acps_for_bre($r); my @itemtags = (); my $itemcount = 0; foreach my $acp (@acps) { next unless ($acp); if ($Marque::config->option_value('exclude-hidden')) { next unless $U->is_true($acp->status()->opac_visible()); next unless $U->is_true($acp->location()->opac_visible()); } my $location = $Marque::config->option_value('location'); my $price = ($acp->price() ? $Marque::config->option_value('money').$acp->price() : ''); my $prefix = $acp->call_number()->prefix()->label(); my $suffix = $acp->call_number()->suffix()->label(); my $status = $acp->status()->name(); eval { local $SIG{__WARN__} = sub { my $message = "Warning from bibliographic record " . $r->id() . ": " . shift; warn($message); }; my @sfb = (); my $f852b_option = $Marque::config->option_value('852b'); if ($f852b_option eq 'owning_lib') { @sfb = ( b => Encode::decode_utf8($acp->call_number()->owning_lib()->shortname()), ); } elsif ($f852b_option eq 'circ_lib') { @sfb = ( b => Encode::decode_utf8($acp->circ_lib()->shortname()), ); } else { @sfb = ( b => Encode::decode_utf8($acp->call_number()->owning_lib()->shortname()), b => Encode::decode_utf8($acp->circ_lib()->shortname()), ); } $itemcount++; push( @itemtags, MARC::Field->new( '852', '4', ' ', ($location ? ('a' => $location) : ()), @sfb, c => Encode::decode_utf8($acp->location()->name()), ($prefix ? (k => Encode::decode_utf8($prefix)) : ()), j => Encode::decode_utf8($acp->call_number()->label()), ($suffix ? (m => Encode::decode_utf8($suffix)) : ()), ($acp->circ_modifier() ? (g => Encode::decode_utf8($acp->circ_modifier())) : ()), p => Encode::decode_utf8($acp->barcode()), s => Encode::decode_utf8($status), ($price ? (y => Encode::decode_utf8($price)) : ()), ($acp->copy_number() ? (t => $acp->copy_number()) : ()), ($U->is_true($acp->ref()) ? (x => 'reference') : ()), (!$U->is_true($acp->holdable()) ? (x => 'unholdable') : ()), (!$U->is_true($acp->circulate()) ? (x => 'noncirculating') : ()), (!$U->is_true($acp->opac_visible()) ? (x => 'hidden') : ()) )); }; if ($@) { warn("Error in bibliographic record " . $r->id() . ": $@"); import MARC::File::XML; # Reset SAX Parser. return $self->next(); } } my $firsttag = shift @itemtags; if ($firsttag) { $marc->insert_grouped_field($firsttag); if (@itemtags) { $marc->insert_fields_after($firsttag,@itemtags); } } #Check if no items are visible, skip bib if empty and exclude-hidden is enabled #Finally check if there are located uris and skip excluding the bib return $self->next() if (!$itemcount and $Marque::config->option_value('exclude-hidden') and !($Marque::config->option_value('uris') and $self->uris_exist_for_bre($r))); } if ($Marque::config->option_value('mfhd')) { $self->{mfhds} = [$self->sres_for_bre($r)]; } } } } # Common stuff that doesn't depend on record type. if ($marc) { if ($Marque::config->option_value('since')) { my $leader = $marc->leader(); if ($U->is_true($r->deleted())) { substr($leader, 5, 1) = 'd'; $marc->leader($leader); } else { my $create_date = Date::Manip::Date->new; $create_date->parse($r->create_date()); my $edit_date = Date::Manip::Date->new; $edit_date->parse($r->edit_date()); if ($self->{since_date}->cmp($create_date) < 0) { substr($leader, 5, 1) = 'n'; $marc->leader($leader); } elsif ($self->{since_date}->cmp($edit_date) < 0) { substr($leader, 5, 1) = 'c'; $marc->leader($leader); } } } if ($Marque::config->option_value('format') eq 'XML') { eval { local $SIG{__WARN__} = sub { my $message = "Warning from bibliographic record " . $r->id() . ": " . shift; warn($message); }; $output = $marc->as_xml_record; $output =~ s/^<\?.+?\?>$//mo; }; if ($@) { warn("Error in bibliographic record " . $r->id() . ": $@"); return $self->next(); } } else { eval { local $SIG{__WARN__} = sub { my $message = "Warning from bibliographic record " . $r->id() . ": " . shift; warn($message); }; $output = $marc->as_usmarc; }; if ($@) { warn("Error in bibliographic record " . $r->id() . ": $@"); return $self->next(); } } } return $output; } # Returns a hash reference to aou objects in a hash, id as key. sub orgs { my $self = shift; unless ($self->{orgs} && %{$self->{orgs}}) { my $fmClass = Fieldmapper::class_for_hint('aou'); my @classFields = $fmClass->real_fields(); my $classTable = $fmClass->Table(); my $query = 'select ' . join(',', @classFields); $query .= "\nfrom $classTable"; my $sth = $self->{handle}->prepare($query); if ($sth->execute()) { my $result = $sth->fetchall_hashref('id'); my %orgs = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result }; #translate with fieldmapper $self->{orgs} = \%orgs; #print STDERR Data::Dumper->new([\%orgs],[qw(orgs)])->Indent(3)->Quotekeys(0)->Dump; } else { $self->{orgs} = {}; } } return $self->{orgs}; } # Returns a reference to a hash of acpl objects, id as key. sub shelves { my $self = shift; unless ($self->{shelves} && %{$self->{shelves}}) { my $fmClass = Fieldmapper::class_for_hint('acpl'); my @classFields = $fmClass->real_fields(); my $classTable = $fmClass->Table(); my $query = 'select ' . join(',', @classFields); $query .= "\nfrom $classTable"; #my $result = $self->{handle}->selectall_arrayref($query, {Slice=>{}}); my $result = $self->{handle}->selectall_hashref($query, 'id'); #Translate into fieldmapper objects my %shelves = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result }; $self->{shelves} = \%shelves; } return $self->{shelves}; } # Returns an reference to a hash of ccs objects. sub statuses { my $self = shift; unless ($self->{statuses} && %{$self->{statuses}}) { my $fmClass = Fieldmapper::class_for_hint('ccs'); my @classFields = $fmClass->real_fields(); my $classTable = $fmClass->Table(); my $query = 'select ' . join(',', @classFields); $query .= "\nfrom $classTable"; my $result = $self->{handle}->selectall_hashref($query, 'id'); my %statuses = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result }; $self->{statuses} = \%statuses; } return $self->{statuses}; } # Returns a reference to a hash of acnp objects, id as key. sub prefixes { my $self = shift; unless ($self->{prefixes} && %{$self->{prefixes}}) { my $fmClass = Fieldmapper::class_for_hint('acnp'); my @classFields = $fmClass->real_fields(); my $classTable = $fmClass->Table(); my $query = 'select ' . join(',', @classFields); $query .= "\nfrom $classTable"; my $result = $self->{handle}->selectall_hashref($query, 'id'); my %prefixes = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result }; $self->{prefixes} = \%prefixes; } return $self->{prefixes}; } # Returns a reference to a hash of acns objects, id as key sub suffixes { my $self = shift; unless ($self->{suffixes} && %{$self->{suffixes}}) { my $fmClass = Fieldmapper::class_for_hint('acns'); my @classFields = $fmClass->real_fields(); my $classTable = $fmClass->Table(); my $query = 'select ' . join(',', @classFields); $query .= "\nfrom $classTable"; my $result = $self->{handle}->selectall_hashref($query, 'id'); my %suffixes = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result }; $self->{suffixes} = \%suffixes; } return $self->{suffixes}; } # Return true if an in scope uri exists for the given bre object or id. # Purpose is prevent excluding a bib if it has no copies but it does have scoped uris # Assumptions - --uris is in use, --items is in use and --exclude-hidden is in use sub uris_exist_for_bre { my $self = shift; my $bre = shift; $bre = $bre->id() if (ref($bre)); unless ($self->{acnUriHandle}) { my $acnTable = $self->{acnClass}->Table(); my $auricnmTable = $self->{auricnmClass}->Table(); my $query = "select 1"; $query .= "\nfrom $acnTable"; $query .= "\njoin $auricnmTable on $auricnmTable.call_number = $acnTable.id"; $query .= "\nwhere"; $query .= "\n$acnTable.record = ?"; $query .= "\nand $acnTable.owning_lib in (select id from actor.org_unit where opac_visible)"; if (@{$self->{libs}}) { $query .= "\nand owning_lib in ("; $query .= join(',', @{$self->{libs}}) . ")"; } $query .= "\nand deleted = 'f'" unless($Marque::config->option_value('since')); $query .= "\nlimit 1"; $self->{acnUriHandle} = $self->{handle}->prepare($query); } if ($self->{acnUriHandle}->execute($bre)) { (my $result) = $self->{acnUriHandle}->fetchrow_array(); return 1 if $result; } # If for some reason, we don't find anything. return undef; } # Returns an array of acn objects for a given bre object or id. sub acns_for_bre { my $self = shift; my $bre = shift; $bre = $bre->id() if (ref($bre)); unless ($self->{acnHandle}) { my $query = "select " . join(',', $self->{acnClass}->real_fields()); $query .= "\nfrom " . $self->{acnClass}->Table(); $query .= "\nwhere record = ?"; if (@{$self->{libs}}) { $query .= "\nand owning_lib in ("; $query .= join(',', @{$self->{libs}}) . ")"; } elsif ($Marque::config->option_value('exclude-hidden')) { $query .= "\nand owning_lib in (select id from actor.org_unit where opac_visible)"; } $query .= "\nand deleted = 'f'" unless($Marque::config->option_value('since')); $self->{acnHandle} = $self->{handle}->prepare($query); } if ($self->{acnHandle}->execute($bre)) { my $result = $self->{acnHandle}->fetchall_arrayref({}); return map {$self->{acnClass}->from_bare_hash($_)} @{$result}; } # If for some reason, we don't find anything. return undef; } # Returns an array of acp objects for a given bre object or id. sub acps_for_bre { my $self = shift; my $bre = shift; $bre = $bre->id() if (ref($bre)); my $orgs = $self->orgs(); my $locations = $self->shelves(); my $prefixes = $self->prefixes(); my $suffixes = $self->suffixes(); my $statuses = $self->statuses(); my @acns = $self->acns_for_bre($bre); if (@acns) { #Setup a prepared statement for the first call unless ($self->{acpHandle}) { my $query = 'select ' . join(',', $self->{acpClass}->real_fields()); $query .= "\nfrom " . $self->{acpClass}->Table(); $query .= "\nwhere call_number = ANY(?::INT[])"; #$query .= join(',', map {$_->id()} @acns); #$query .= ")"; $query .= "\nand deleted = 'f'" unless ($Marque::config->option_value('since')); $query .= "\nand opac_visible" if ($Marque::config->option_value('exclude-hidden')); $self->{acpHandle} = $self->{handle}->prepare($query); } #Use the prepared statement my $result; my @acnsa = map {$_->id()} @acns; if ($self->{acpHandle}->execute( \@acnsa )) { $result = $self->{acpHandle}->fetchall_arrayref( {} ); } if ($result && @{$result}) { my @acps = map {$self->{acpClass}->from_bare_hash($_)} @{$result}; foreach (@acps) { my $cn = $_->call_number(); my ($acn) = grep {$_->id() == $cn} @acns; $acn->owning_lib($orgs->{$acn->owning_lib()}); $_->call_number($acn); $_->circ_lib($orgs->{$_->circ_lib()}); $_->location($locations->{$_->location()}); $_->status($statuses->{$_->status()}); $_->call_number->prefix($prefixes->{$acn->prefix()}); $_->call_number->suffix($suffixes->{$acn->suffix()}); } return @acps; } } # If for some reason, we don't find anything. return undef; } # Retreive an array for sre objects when the --mfhd option is used. sub sres_for_bre { my $self = shift; my $bre = shift; $bre = $bre->id() if (ref($bre)); my @sres; # Build a query to retrieve SREs when the MFHD option is passed. if ($Marque::config->option_value('mfhd')) { # Create a persistent handle as needed. unless ($self->{sreSth}) { my $query = "select " . join(',', $self->{sreClass}->real_fields()); $query .= "\nfrom " . $self->{sreClass}->Table(); $query .= "\nwhere record = ?"; $query .= "\nand deleted = 'f'" unless ($Marque::config->option_value('since')); $self->{sreSth} = $self->{handle}->prepare($query); } if ($self->{sreSth}->execute($bre)) { while (my $data = $self->{sreSth}->fetchrow_hashref) { push @sres, $self->{sreClass}->from_bare_hash($data); } $self->{sreSth}->finish; # Sometimes DBI complains. } } # May be empty. return @sres; } # Get authority records from the database. package Marque::Authority; sub new { my $class = shift; my $idlist = shift; my $self = {idlist => $idlist}; $self->{handle} = Marque::Connector::connect( $Marque::config->database_settings); $self->{fmClass} = Fieldmapper::class_for_hint('are'); $self->{since_date} = Date::Manip::Date->new; $self->{since_date}->parse($Marque::config->option_value('since')); bless $self, $class; return $self; } sub build_query { my $self = shift; # Get the information for are object from the Fieldmapper: my @fields = $self->{fmClass}->real_fields(); my $table = $self->{fmClass}->Table(); # Build the actual query. my $select = "select " . join(',', @fields); my $from = "from $table"; my $where = 'where '; # If we have an idlist, we pretty much ignore anything else. if ($self->{idlist} && @{$self->{idlist}}) { $where .= 'id in (' . join(',', @{$self->{idlist}}) . ')'; } elsif ($Marque::config->option_value('since')) { my $since_str = Marque::Connector::db_date($self->{since_date}); $where .= "edit_date > '$since_str'"; $where .= " or create_date > '$since_str'"; } else { # We want all non-deleted records. $where .= "deleted = 'f'"; } $self->{query} = $select . "\n" . $from . "\n" . $where; } sub execute_query { my $self = shift; $self->build_query() unless ($self->{query}); unless ($self->{cursor}) { $self->{cursor} = 'DECLARE auths CURSOR WITH HOLD FOR ' . $self->{query}; $self->{handle}->do($self->{cursor}); $self->{fetchcmd} = 'fetch ' . $Marque::config->option_value('batch-size') . ' from auths'; } $self->{sth} = $self->{handle}->prepare($self->{fetchcmd}); return $self->{sth}->execute; } sub next { my $self = shift; my $output; my $data = $self->{sth}->fetchrow_hashref; unless ($data) { # We ran out of data, so try fetching the next batch. if ($self->execute_query()) { $data = $self->{sth}->fetchrow_hashref(); } } if ($data) { my $format = $Marque::config->option_value('format'); my $r = $self->{fmClass}->from_bare_hash($data); if ($format eq 'ARE') { $output = OpenSRF::Utils::JSON->perl2JSON($r); } else { my $marc; eval { local $SIG{__WARN__} = sub { my $message = "Warning from authority record " . $r->id() . ": " . shift; warn($message); }; $marc = MARC::Record->new_from_xml($r->marc(), $Marque::config->option_value('encoding'), $Marque::config->option_value('format')); }; if ($@) { warn("Error in authority record " . $r->id() . ": $@"); import MARC::File::XML; # Reset SAX Parser. return $self->next(); } if ($Marque::config->option_value('replace_001')) { my $tcn = $marc->field('001'); if ($tcn) { $tcn->update($r->id()); } else { $tcn = MARC::Field->new('001', $r->id()); $marc->insert_fields_ordered($tcn); } } my $strip_arg_ref = $Marque::config->option_value('strip'); my @strip = @{$strip_arg_ref}; foreach my $strip_ref (@strip) { my $tagRE = $strip_ref->{tag}; my $subfieldRE = $strip_ref->{subfield}; if ( $subfieldRE eq "") { # Case 1: Field only check, e.g. "--strip 5.[0,1]" # If the supplied regexp matches the field, then # delete that field. foreach my $test_field ($marc->fields()) { if ($test_field->tag() =~ /$tagRE/) { # A hit! $marc->delete_field($test_field); } } } elsif ($subfieldRE ne "" && $tagRE ne "") { # Case 2: Field & subfield supplied. # Note a blank tag will be wildcarded to "*". # Traverse fields, then traverse subfields if match # is found. foreach my $test_field ($marc->fields()) { if ( !$test_field->is_control_field() && $test_field->tag() =~ /$tagRE/) { # Traverse all subfields: foreach my $test_subfield ($test_field->subfields()) { my $sfcode = @{$test_subfield}[0]; if ($sfcode =~ /$subfieldRE/) { $test_field->delete_subfield($sfcode); } } } } } } if ($Marque::config->option_value('since')) { my $leader = $marc->leader(); if ($U->is_true($r->deleted())) { substr($leader, 5, 1) = 'd'; $marc->leader($leader); } else { my $create_date = Date::Manip::Date->new; $create_date->parse($r->create_date()); my $edit_date = Date::Manip::Date->new; $edit_date->parse($r->edit_date()); if ($self->{since_date}->cmp($create_date) < 0) { substr($leader, 5, 1) = 'n'; $marc->leader($leader); } elsif ($self->{since_date}->cmp($edit_date) < 0) { substr($leader, 5, 1) = 'c'; $marc->leader($leader); } } } if ($Marque::config->option_value('format') eq 'XML') { eval { local $SIG{__WARN__} = sub { my $message = "Warning from authority record " . $r->id() . ": " . shift; warn($message); }; $output = $marc->as_xml_record; $output =~ s/^<\?.+?\?>$//mo; }; if ($@) { warn("Error in authority record " . $r->id() . ": $@"); return $self->next(); } } else { eval { local $SIG{__WARN__} = sub { my $message = "Warning from authority record " . $r->id() . ": " . shift; warn($message); }; $output = $marc->as_usmarc; }; if ($@) { warn("Error in authority record " . $r->id() . ": $@"); return $self->next(); } } } } return $output; } # ------------------------------------------------------------------ # Since the ultimate output is largely independent of the type of the # records, we use a single subpackage to group our output routines. package Marque::Output; sub output { my $extractor = shift; if ($extractor->execute_query) { if ($Marque::config->option_value('encoding') eq 'UTF-8') { binmode(STDOUT, ':utf8'); } else { binmode(STDOUT, ':raw'); } &preamble; while (my $output = $extractor->next()) { print $output; } &postamble; } else { print STDERR $extractor->{query} if ($Marque::config->option_value('debug')); die "Database query failed!"; } } sub preamble { if ($Marque::config->option_value('format') eq 'XML') { my $encoding = $Marque::config->option_value('encoding'); print < PREAMBLE } } sub postamble { if ($Marque::config->option_value('format') eq 'XML') { print "\n"; } } 1;