2 # ---------------------------------------------------------------
3 # Copyright © 2013 Merrimack Valley Library Consortium
4 # Jason Stephenson <jstephenson@mvlc.org>
6 # This program is part of Evergreen; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; either version 2 of the
9 # License, or (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 # ---------------------------------------------------------------
18 use OpenILS::Utils::Fieldmapper;
19 use OpenILS::Application::AppUtils;
20 use OpenSRF::Utils::JSON;
23 use MARC::File::XML (BinaryEncoding => 'UTF-8');
24 use Date::Manip::Date;
26 my $U = 'OpenILS::Application::AppUtils';
28 binmode(STDERR, ':utf8');
32 our $config = Marque::Config->new();
33 Fieldmapper->import(IDL => $config->option_value('xml-idl'));
35 # Look for passed in ids:
37 if ($config->need_ids()) {
38 print STDERR "Waiting for input\n" if (-t);
40 push @ids, $i if ($i =~ /^\s*[0-9]+\s*$/);
44 die "IDs required but none entered, exiting\n" if ($config->need_ids() && !@ids);
47 if ($config->option_value('type') eq 'authority') {
48 $exporter = Marque::Authority->new(\@ids);
50 $exporter = Marque::Biblio->new(\@ids);
53 Marque::Output::output($exporter);
55 # ------------------------------------------------------------------
56 package Marque::Config;
59 use List::MoreUtils qw(none);
61 use OpenSRF::Utils::SettingsClient;
63 use constant FORMATS => qw(USMARC UNIMARC XML BRE ARE);
64 use constant STORES => qw(reporter cstore storage);
65 use constant TYPES => qw(authority biblio);
73 # For command line options.
76 # set some default values
77 $opts{'format'} = 'USMARC';
78 $opts{'encoding'} = 'UTF-8';
79 $opts{'type'} = 'biblio';
82 $opts{'config'} = '@sysconfdir@/opensrf_core.xml';
83 $opts{'store'} = 'reporter';
84 $opts{'852b'} = 'both';
85 $opts{'batch-size'} = 10000;
115 This script exports MARC authority, bibliographic, and serial holdings
116 records from an Evergreen database.
118 Input to this script can consist of a list of record IDs, with one record ID
119 per line, corresponding to the record ID in the Evergreen database table of
120 your requested record type.
122 Alternately, passing the --all option will attempt to export all records of
123 the specified type from the Evergreen database. The --all option starts at
124 record ID 1 and increments the ID by 1 until the largest ID in the database
125 is retrieved. This may not be very efficient for databases with large gaps
126 in their ID sequences.
129 --help or -h This screen.
130 --config or -c Configuration file [@sysconfdir@/opensrf_core.xml]
131 --format or -f Output format (USMARC, UNIMARC, XML, BRE, ARE) [USMARC]
132 --encoding or -e Output encoding (UTF-8, ISO-8859-?, MARC8) [UTF-8]
133 --xml-idl or -x Location of the IDL XML
134 --timeout Remains for backward compatibility. No longer used.
135 --type or -t Record type (BIBLIO, AUTHORITY) [BIBLIO]
136 --all or -a Export all records; ignores input list
137 --replace_001 Replace the 001 field value with the record ID
139 Strip fields or subfields matching regular expressions
140 --store Use the given storage backend to connect to the database.
141 Choices are (reporter, cstore, storage) [reporter]
142 --since Export records modified since a certain date and time.
143 --pipe Force record ids to be read from list on standard input,
144 despite other options to the contrary
145 --batch-size Number of records to fetch at a time for processing
146 (default 10000). This option can be adjusted
147 depending on your database performance or
148 environment. Doing smaller batch sizes can
149 sometimes speed up the extraction. Finding the
150 best value for your situation requires
153 Additional options for type = 'BIBLIO':
154 --items or -i Include items (holdings) in the output
155 --852b Accepts 'owning_lib', 'circ_lib', or 'both' to
156 control whether the 852$b in exported embedded
157 holdings has the owning library, the circulation
158 library, or both in separate repeats of the $b.
159 If not supplied, defaults to 'both', which is the
161 --money Currency symbol to use in item price field [\$]
162 --mfhd Export serial MFHD records for associated bib records
163 Not compatible with --format=BRE
164 --location or -l MARC Location Code for holdings from
165 http://www.loc.gov/marc/organizations/orgshome.html
166 --library Export the bibliographic records that have attached
167 holdings for the listed library or libraries as
168 identified by shortname
169 --descendants Like the --library option, but org. tree aware. It
170 exports records that have attached holdings for the
171 specified org. unit and all of its descendants in
173 --uris or -u Include records with located URIs in the output
174 --exclude-hidden Exclude records and items if the item is not
175 OPAC-visible per its org unit, status, shelving,
176 location, or flag on the item record. This option
177 is effective only if the --library and/or --items
178 flags are supplied. This option takes precedence;
179 for example, if the org unit specified by --library
180 is not OPAC-visible, its records will not be included
185 To export a set of USMARC records in a file named "output_file" based on the
186 IDs contained in a file named "list_of_ids":
187 cat list_of_ids | $0 > output_file
189 To export a set of MARC21XML authority records in a file named "output.xml"
190 for all authority records in the database:
191 $0 --format XML --type AUTHORITY --all > output.xml
193 To export a set of USMARC bibliographic records encoded in UTF-8 in a file
194 named "sys1_bibs.mrc" based on records which have attached callnumbers for the
195 libraries with the short names "BR1" and "BR2":
197 $0 --library BR1 --library BR2 --encoding UTF-8 > sys1_bibs.mrc
199 The --strip option can be used more than once which imples an "OR" operation.
200 If the field argument is omitted (e.g., "/0", it is treated like "..." (all fields).
201 If the subfield argument is omitted (e.g. "100/", it is treated like "."
202 (all subfields). Examples:
204 --strip /0 Remove all 0 subfields
205 --strip 1[23]. Remove fields with tags 120 through 139, inclusive.
206 --strip 856/x Remove subfield x from 856 tags
211 OpenSRF::System->bootstrap_client( config_file => $opts{config} );
212 my $sclient = OpenSRF::Utils::SettingsClient->new();
213 unless ($opts{'xml-idl'}) {
214 $opts{'xml-idl'} = $sclient->config_value('IDL');
217 # Validate some of the settings.
218 if ($opts{all} && ($opts{library} || $opts{descendants})) {
219 die('Incompatible arguments: you cannot combine a request for all ' .
220 'records with a request for records by library');
222 if ($opts{all} && $opts{since}) {
223 die('Incompatible arguments: you cannot combine a request for all ' .
224 'records with a request for records added or changed since a certain date');
226 if ($opts{all} && $opts{pipe}) {
227 die('Incompatible arguments: you cannot combine a request for all ' .
228 'records with the option to read record ids via standard input');
230 if ($opts{since} && $opts{pipe}) {
231 die('Incompatible arguments: you cannot combine a request for records added or '.
232 'changed since a certain date with ' .
233 'the option to read record ids via standard input');
235 $opts{type} = lc($opts{type});
236 if (none {$_ eq $opts{type}} (TYPES)) {
237 die "Please select a supported type. ".
238 "Right now that means one of [".
239 join('|',(TYPES)). "]\n";
241 $opts{format} = uc($opts{format});
242 if (none {$_ eq $opts{format}} (FORMATS)) {
243 die "Please select a supported format. ".
244 "Right now that means one of [".
245 join('|',(FORMATS)). "]\n";
247 # Process --strip arguments. They are in the form tagRE/subRE. Note
248 # that the RE pieces cannot contain a slash (/), as this would create
249 # ambiguity. If there is no /subRE, then it's OK, and just the tagRE
251 # $opts{strip} is an array-ref for this multi-valued option.
254 foreach my $strip_value (@{$opts{strip}}) {
256 if ($strip_value eq "/") {
257 print STDERR "Ignoring empty --strip parameter; all records would be empty.\n";
260 if ($strip_value =~ /\//) {
262 $trec->{tag} = "..." if ($` eq "");
263 $trec->{subfield} = $';
264 $trec->{subfield} = "." if ($' eq "");
267 $trec->{tag} = $strip_value;
268 $trec->{subfield} = '';
273 if ($opts{format} eq 'ARE' && $opts{type} ne 'authority') {
274 die "Format ARE is not compatible with type " . $opts{type};
276 if ($opts{format} eq 'BRE' && $opts{type} ne 'biblio') {
277 die "Format BRE is not compatible with type " . $opts{type};
279 if ($opts{format} eq 'BRE' && $opts{items}) {
280 die "Format BRE is not compatible with exporting holdings."
284 if ($opts{type} ne 'biblio') {
285 die "MFHD export only works with bibliographic records.";
286 } elsif ($opts{format} eq 'BRE') {
287 die "MFHD export incompatible with format BRE.";
291 if ($opts{'852b'} ne 'circ_lib' &&
292 $opts{'852b'} ne 'owning_lib' &&
293 $opts{'852b'} ne 'both') {
294 die "Invalid value '" . $opts{'852b'} . "' for --852b; must be 'circ_lib', 'owning_lib', or 'both'";
297 $opts{store} = lc($opts{store});
298 if (none {$_ eq $opts{store}} (STORES)) {
299 die "Please select a supported store. ".
300 "Right now that means one of [".
301 join('|',(STORES)). "]\n";
304 if ($opts{store} eq 'reporter') {
305 $app = 'open-ils.reporter-store';
307 $app = 'open-ils.' . $opts{store};
309 if ($app eq 'open-ils.storage') {
310 $self->{dbsettings} = $sclient->config_value(
311 apps => $app => app_settings => databases => 'database');
313 $self->{dbsettings} = $sclient->config_value(
314 apps => $app => app_settings => 'database');
317 $opts{encoding} = uc($opts{encoding});
319 $opts{strip} = \@strip;
321 $self->{'options'} = \%opts;
327 my ($self, $option) = @_;
328 return $self->{options}->{$option};
331 sub database_settings {
333 return $self->{dbsettings};
340 $rv = 0 if ($self->{options}->{since});
341 $rv = 0 if ($self->{options}->{library});
342 $rv = 0 if ($self->{options}->{descendants});
343 # --pipe trumps the above.
344 $rv = 1 if ($self->{options}->{pipe});
345 # --all trumps --pipe, but we should throw an error before we get here.
346 $rv = 0 if ($self->{options}->{all});
351 # ------------------------------------------------------------------
352 # This package exists to get a connection to the database. Since
353 # we'll need one for both biblio records and authorities, we've made a
354 # single subpackage with a function so that we don't have to duplicate
356 package Marque::Connector;
360 # Pass a Marque::Config object's database_settings return value into
361 # this to get a DBI connection.
363 # my $db = Marque::Connector::connect($config->database_settings);
367 # Build a connect string from the args.
368 my $connect_string = 'DBI:Pg:';
369 $connect_string .= 'dbname=' . $args->{db} . ';';
370 $connect_string .= 'host=' . $args->{host} . ';';
371 $connect_string .= 'port=' . $args->{port};
373 my $db_handle = DBI->connect($connect_string,
374 $args->{user}, $args->{pw});
378 # A function to get the date into a format better for PostgreSQL.
382 if (ref($input) eq 'Date::Manip::Date') {
385 $date = Date::Manip::Date->new();
386 if ($date->parse($input)) {
387 die "Can't parse date $input";
390 return $date->printf("%Y-%m-%dT%H:%M:%S%z");
393 # ------------------------------------------------------------------
394 # You would typically have the next two packages inherit from a common
395 # superclass, but ineritance doesn't seem to work when all packages
396 # are in single file, so we have some duplicated code between these
399 # Get bibliographic records from the database.
400 package Marque::Biblio;
405 my $self = {idlist => $idlist};
406 $self->{handle} = Marque::Connector::connect(
407 $Marque::config->database_settings);
408 $self->{since_date} = Date::Manip::Date->new;
409 $self->{since_date}->parse($Marque::config->option_value('since'));
411 # We need multiple fieldmapper classes depending on our
412 # options. We'll just get the information that we'll need for them
413 # all right here instead of only fetching the information when
415 $self->{breClass} = Fieldmapper::class_for_hint('bre');
416 $self->{acnClass} = Fieldmapper::class_for_hint('acn');
417 $self->{acpClass} = Fieldmapper::class_for_hint('acp');
418 $self->{sreClass} = Fieldmapper::class_for_hint('sre');
419 $self->{acnpClass} = Fieldmapper::class_for_hint('acnp');
420 $self->{acnsClass} = Fieldmapper::class_for_hint('acns');
421 $self->{auricnmClass} = Fieldmapper::class_for_hint('auricnm');
423 # Make an arrayref of shortname ids if the library option was
426 if ($Marque::config->option_value('library')) {
427 # This is done not only for speed, but to prevent SQL injection.
428 my $query = 'select id from actor.org_unit where shortname=any(?::text[])';
429 if ($Marque::config->option_value('exclude-hidden')) {
430 $query .= ' AND opac_visible';
432 my $sth = $self->{handle}->prepare($query);
433 if ($sth->execute($Marque::config->option_value('library'))) {
434 my $r = $sth->fetchall_arrayref();
435 my @ids = map {$_->[0]} @{$r};
436 $self->{libs} = \@ids;
440 # Ditto for descendants. We don't worry about redundancy, the db can deal with it.
441 if ($Marque::config->option_value('descendants')) {
442 # Unlike the above, we're looping to make this simpler in the database.
443 my $query = 'select id, opac_visible from actor.org_unit_descendants((select id from actor.org_unit where shortname=?))';
444 my $sth = $self->{handle}->prepare($query);
445 foreach my $shortname (@{$Marque::config->option_value('descendants')}) {
446 if ($sth->execute($shortname)) {
447 my $r = $sth->fetchall_arrayref();
449 if ($Marque::config->option_value('exclude-hidden')) {
450 @ids = map {$_->[0]} grep {$_->[1]} @{$r};
452 @ids = map {$_->[0]} @{$r};
454 push(@{$self->{libs}}, @ids);
467 # TODO: There is some unfortunate code repetition in this
468 # subroutine and it is now about 93 lines long with comments and
469 # whitespace. It should probably be refactored into a series of
470 # smaller subroutines to avoid the repetition.
472 # Get the field names and tables for our classes. We add the fully
473 # qualified table names to the fields so that the joins will work.
474 my $breTable = $self->{breClass}->Table();
475 my @breFields = map {$breTable . '.' . $_} $self->{breClass}->real_fields();
476 my $acnTable = $self->{acnClass}->Table();
477 my $acpTable = $self->{acpClass}->Table();
478 my $acnpTable = $self->{acnpClass}->Table();
479 my $acnsTable = $self->{acnsClass}->Table();
480 my $auricnmTable = $self->{auricnmClass}->Table();
482 # Now we build the query in pieces:
484 # We always select the bre fields:
485 my $select = 'select distinct ' . join(',', @breFields);
486 # We always use the bre table.
487 my $from = "from $breTable";
489 # If have the libraries or items options, we need to join the
490 # asset.call_number table. If we have both, this variable checks
491 # that it has already been joined so we don't create an invalid
494 # Join to the acn table as needed for the library option.
495 if (@{$self->{libs}}) {
499 join $acnTable on $acnTable.record = $breTable.id
500 and $acnTable.owning_lib in (
502 $from .= join(',', @{$self->{libs}}) . ")";
503 $from .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since'));
506 if ($Marque::config->option_value('items')) {
507 unless ($acn_joined) {
508 $from .= "\njoin $acnTable on $acnTable.record = $breTable.id";
509 if ($Marque::config->option_value('exclude-hidden')) {
510 $from .= "\n AND $acnTable.owning_lib in (select id from actor.org_unit where opac_visible)";
512 $from .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since'));
514 $from .= "\njoin $acpTable on $acpTable.call_number = $acnTable.id";
515 $from .= "\nand $acpTable.deleted = 'f'" unless ($Marque::config->option_value('since'));
516 $from .= "\nand $acpTable.opac_visible" if ($Marque::config->option_value('exclude-hidden'));
517 $from .= "\nleft outer join $acnpTable on $acnTable.prefix = $acnpTable.id";
518 $from .= "\nleft outer join $acnsTable on $acnTable.suffix = $acnsTable.id";
521 # The where really depends on a few options:
522 my $where = "where $breTable.id > 0 and ";
523 # We fill in the where as necessary.
524 if ($self->{idlist} && @{$self->{idlist}}) {
525 $where .= "$breTable.id in (" . join(',', @{$self->{idlist}}) . ')';
526 } elsif ($Marque::config->option_value('since')) {
527 my $since_str = Marque::Connector::db_date($self->{since_date});
528 $where .= "($breTable.edit_date > '$since_str'";
529 $where .= " or $breTable.create_date > '$since_str')";
531 # We want all non-deleted records.
532 $where .= "$breTable.deleted = 'f'";
535 # Support the --uris option. It is orthogonal to --items, so we
536 # may have to build a second query to use with a UNION DISTINCT.
538 if ($Marque::config->option_value('uris')) {
539 if ($Marque::config->option_value('items')) {
540 # Build UNION DISTINCT for main query.
541 $uri_union = "\nunion distinct\n";
542 $uri_union .= $select;
543 $uri_union .= "\nfrom $breTable";
544 $uri_union .= "\njoin $acnTable on $acnTable.record = $breTable.id";
545 $uri_union .= "\nand $acnTable.owning_lib in (" . join(',', @{$self->{libs}}) . ")" if (@{$self->{libs}});
546 $uri_union .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since'));
547 $uri_union .= "\njoin $auricnmTable on $auricnmTable.call_number = $acnTable.id";
548 $uri_union .= "\n$where";
550 unless ($acn_joined) {
551 $from .= "\njoin $acnTable on $acnTable.record = $breTable.id";
552 $from .= "\nand $acnTable.deleted = 'f'" unless ($Marque::config->option_value('since'));
554 $from .= "\njoin $auricnmTable on $auricnmTable.call_number = $acnTable.id";
558 $self->{query} = $select . "\n" . $from . "\n" . $where;
559 $self->{query} .= $uri_union if ($uri_union);
560 $self->{query} .= "\n" . "order by id"; #sort results by bre id.
565 $self->build_query() unless ($self->{query});
566 unless ($self->{cursor}) {
567 $self->{cursor} = 'DECLARE bibs CURSOR WITH HOLD FOR ' . $self->{query};
568 $self->{handle}->do($self->{cursor});
569 $self->{fetchcmd} = 'fetch ' . $Marque::config->option_value('batch-size') . ' from bibs';
571 $self->{sth} = $self->{handle}->prepare($self->{fetchcmd});
572 return $self->{sth}->execute;
579 # $r holds the record object, either sre or bre. $marc holds the
580 # current record's MARC, either sre.marc or bre.marc
582 # If we have the mfhd option and we've previously retrieved some
583 # sres, then we output one of the retrieved sres for each call
584 # until we run out. These sres "go with" the previous bib record.
585 if ($Marque::config->option_value('mfhd') && $self->{mfhds} && @{$self->{mfhds}}) {
586 $r = shift(@{$self->{mfhds}});
588 local $SIG{__WARN__} = sub {
589 my $message = "Warning from serial record " . $r->id() . ": "
593 $marc = MARC::Record->new_from_xml($r->marc(),
594 $Marque::config->option_value('encoding'),
595 $Marque::config->option_value('format'));
598 warn("Error in serial record " . $r->id() . ": $@");
599 import MARC::File::XML; # Reset SAX Parser.
600 return $self->next();
603 my $data = $self->{sth}->fetchrow_hashref;
606 # We ran out of data, so fetch the next batch.
607 if ($self->execute_query()) {
608 $data = $self->{sth}->fetchrow_hashref;
613 $r = $self->{breClass}->from_bare_hash($data);
614 if ($Marque::config->option_value('format') eq 'BRE') {
615 $output = OpenSRF::Utils::JSON->perl2JSON($r);
618 local $SIG{__WARN__} = sub {
619 my $message = "Warning from bibliographic record " . $r->id() . ": "
623 $marc = MARC::Record->new_from_xml($r->marc(),
624 $Marque::config->option_value('encoding'),
625 $Marque::config->option_value('format'));
628 warn("Error in bibliographic record " . $r->id() . ": $@");
629 import MARC::File::XML; # Reset SAX Parser.
630 return $self->next();
632 if ($Marque::config->option_value('replace_001')) {
633 my $tcn = $marc->field('001');
635 $tcn->update($r->id());
637 $tcn = MARC::Field->new('001', $r->id());
638 $marc->insert_fields_ordered($tcn);
642 my $strip_arg_ref = $Marque::config->option_value('strip');
643 my @strip = @{$strip_arg_ref};
644 foreach my $strip_ref (@strip) {
645 my $tagRE = $strip_ref->{tag};
646 my $subfieldRE = $strip_ref->{subfield};
648 if ( $subfieldRE eq "") {
649 # Case 1: Field only check, e.g. "--strip 5.[0,1]"
650 # If the supplied regexp matches the field, then
652 foreach my $test_field ($marc->fields()) {
653 if ($test_field->tag() =~ /$tagRE/) {
655 $marc->delete_field($test_field);
658 } elsif ($subfieldRE ne "" && $tagRE ne "") {
659 # Case 2: Field & subfield supplied.
660 # Note a blank tag will be wildcarded to "*".
661 # Traverse fields, then traverse subfields if match
663 foreach my $test_field ($marc->fields()) {
664 if ( !$test_field->is_control_field() &&
665 $test_field->tag() =~ /$tagRE/) {
666 # Traverse all subfields:
667 foreach my $test_subfield ($test_field->subfields()) {
668 my $sfcode = @{$test_subfield}[0];
669 if ($sfcode =~ /$subfieldRE/) {
670 $test_field->delete_subfield($sfcode);
678 if ($Marque::config->option_value('items')) {
679 # If --items was passed discard any static 852 fields; they're either dupes, out-of-sync, or junk.
680 $marc->delete_fields($marc->field('852'));
681 my @acps = $self->acps_for_bre($r);
685 foreach my $acp (@acps) {
687 if ($Marque::config->option_value('exclude-hidden')) {
688 next unless $U->is_true($acp->status()->opac_visible());
689 next unless $U->is_true($acp->location()->opac_visible());
691 my $location = $Marque::config->option_value('location');
692 my $price = ($acp->price() ? $Marque::config->option_value('money').$acp->price() : '');
693 my $prefix = $acp->call_number()->prefix()->label();
694 my $suffix = $acp->call_number()->suffix()->label();
695 my $status = $acp->status()->name();
697 local $SIG{__WARN__} = sub {
698 my $message = "Warning from bibliographic record " . $r->id() . ": "
704 my $f852b_option = $Marque::config->option_value('852b');
705 if ($f852b_option eq 'owning_lib') {
707 b => Encode::decode_utf8($acp->call_number()->owning_lib()->shortname()),
709 } elsif ($f852b_option eq 'circ_lib') {
711 b => Encode::decode_utf8($acp->circ_lib()->shortname()),
715 b => Encode::decode_utf8($acp->call_number()->owning_lib()->shortname()),
716 b => Encode::decode_utf8($acp->circ_lib()->shortname()),
725 ($location ? ('a' => $location) : ()),
727 c => Encode::decode_utf8($acp->location()->name()),
728 ($prefix ? (k => Encode::decode_utf8($prefix)) : ()),
729 j => Encode::decode_utf8($acp->call_number()->label()),
730 ($suffix ? (m => Encode::decode_utf8($suffix)) : ()),
731 ($acp->circ_modifier() ? (g => Encode::decode_utf8($acp->circ_modifier())) : ()),
732 p => Encode::decode_utf8($acp->barcode()),
733 s => Encode::decode_utf8($status),
734 ($price ? (y => Encode::decode_utf8($price)) : ()),
735 ($acp->copy_number() ? (t => $acp->copy_number()) : ()),
736 ($U->is_true($acp->ref()) ? (x => 'reference') : ()),
737 (!$U->is_true($acp->holdable()) ? (x => 'unholdable') : ()),
738 (!$U->is_true($acp->circulate()) ? (x => 'noncirculating') : ()),
739 (!$U->is_true($acp->opac_visible()) ? (x => 'hidden') : ())
743 warn("Error in bibliographic record " . $r->id() . ": $@");
744 import MARC::File::XML; # Reset SAX Parser.
745 return $self->next();
748 my $firsttag = shift @itemtags;
750 $marc->insert_grouped_field($firsttag);
752 $marc->insert_fields_after($firsttag,@itemtags);
756 #Check if no items are visible, skip bib if empty and exclude-hidden is enabled
757 #Finally check if there are located uris and skip excluding the bib
758 return $self->next() if (!$itemcount
759 and $Marque::config->option_value('exclude-hidden')
760 and !($Marque::config->option_value('uris') and $self->uris_exist_for_bre($r)));
762 if ($Marque::config->option_value('mfhd')) {
763 $self->{mfhds} = [$self->sres_for_bre($r)];
768 # Common stuff that doesn't depend on record type.
770 if ($Marque::config->option_value('since')) {
771 my $leader = $marc->leader();
772 if ($U->is_true($r->deleted())) {
773 substr($leader, 5, 1) = 'd';
774 $marc->leader($leader);
776 my $create_date = Date::Manip::Date->new;
777 $create_date->parse($r->create_date());
778 my $edit_date = Date::Manip::Date->new;
779 $edit_date->parse($r->edit_date());
780 if ($self->{since_date}->cmp($create_date) < 0) {
781 substr($leader, 5, 1) = 'n';
782 $marc->leader($leader);
783 } elsif ($self->{since_date}->cmp($edit_date) < 0) {
784 substr($leader, 5, 1) = 'c';
785 $marc->leader($leader);
789 if ($Marque::config->option_value('format') eq 'XML') {
791 local $SIG{__WARN__} = sub {
792 my $message = "Warning from bibliographic record " . $r->id() . ": "
796 $output = $marc->as_xml_record;
797 $output =~ s/^<\?.+?\?>$//mo;
800 warn("Error in bibliographic record " . $r->id() . ": $@");
801 return $self->next();
805 local $SIG{__WARN__} = sub {
806 my $message = "Warning from bibliographic record " . $r->id() . ": "
810 $output = $marc->as_usmarc;
813 warn("Error in bibliographic record " . $r->id() . ": $@");
814 return $self->next();
821 # Returns a hash reference to aou objects in a hash, id as key.
824 unless ($self->{orgs} && %{$self->{orgs}}) {
825 my $fmClass = Fieldmapper::class_for_hint('aou');
826 my @classFields = $fmClass->real_fields();
827 my $classTable = $fmClass->Table();
828 my $query = 'select ' . join(',', @classFields);
829 $query .= "\nfrom $classTable";
830 my $sth = $self->{handle}->prepare($query);
831 if ($sth->execute()) {
832 my $result = $sth->fetchall_hashref('id');
833 my %orgs = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result }; #translate with fieldmapper
834 $self->{orgs} = \%orgs;
835 #print STDERR Data::Dumper->new([\%orgs],[qw(orgs)])->Indent(3)->Quotekeys(0)->Dump;
840 return $self->{orgs};
843 # Returns a reference to a hash of acpl objects, id as key.
847 unless ($self->{shelves} && %{$self->{shelves}}) {
848 my $fmClass = Fieldmapper::class_for_hint('acpl');
849 my @classFields = $fmClass->real_fields();
850 my $classTable = $fmClass->Table();
851 my $query = 'select ' . join(',', @classFields);
852 $query .= "\nfrom $classTable";
853 #my $result = $self->{handle}->selectall_arrayref($query, {Slice=>{}});
854 my $result = $self->{handle}->selectall_hashref($query, 'id');
855 #Translate into fieldmapper objects
856 my %shelves = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result };
857 $self->{shelves} = \%shelves;
860 return $self->{shelves};
863 # Returns an reference to a hash of ccs objects.
867 unless ($self->{statuses} && %{$self->{statuses}}) {
868 my $fmClass = Fieldmapper::class_for_hint('ccs');
869 my @classFields = $fmClass->real_fields();
870 my $classTable = $fmClass->Table();
871 my $query = 'select ' . join(',', @classFields);
872 $query .= "\nfrom $classTable";
873 my $result = $self->{handle}->selectall_hashref($query, 'id');
874 my %statuses = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result };
875 $self->{statuses} = \%statuses;
878 return $self->{statuses};
881 # Returns a reference to a hash of acnp objects, id as key.
885 unless ($self->{prefixes} && %{$self->{prefixes}}) {
886 my $fmClass = Fieldmapper::class_for_hint('acnp');
887 my @classFields = $fmClass->real_fields();
888 my $classTable = $fmClass->Table();
889 my $query = 'select ' . join(',', @classFields);
890 $query .= "\nfrom $classTable";
891 my $result = $self->{handle}->selectall_hashref($query, 'id');
892 my %prefixes = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result };
893 $self->{prefixes} = \%prefixes;
896 return $self->{prefixes};
899 # Returns a reference to a hash of acns objects, id as key
903 unless ($self->{suffixes} && %{$self->{suffixes}}) {
904 my $fmClass = Fieldmapper::class_for_hint('acns');
905 my @classFields = $fmClass->real_fields();
906 my $classTable = $fmClass->Table();
907 my $query = 'select ' . join(',', @classFields);
908 $query .= "\nfrom $classTable";
909 my $result = $self->{handle}->selectall_hashref($query, 'id');
910 my %suffixes = map {$_ => $fmClass->from_bare_hash($$result{$_})} keys %{ $result };
911 $self->{suffixes} = \%suffixes;
914 return $self->{suffixes};
917 # Return true if an in scope uri exists for the given bre object or id.
918 # Purpose is prevent excluding a bib if it has no copies but it does have scoped uris
919 # Assumptions - --uris is in use, --items is in use and --exclude-hidden is in use
920 sub uris_exist_for_bre {
923 $bre = $bre->id() if (ref($bre));
925 unless ($self->{acnUriHandle}) {
926 my $acnTable = $self->{acnClass}->Table();
927 my $auricnmTable = $self->{auricnmClass}->Table();
929 my $query = "select 1";
930 $query .= "\nfrom $acnTable";
931 $query .= "\njoin $auricnmTable on $auricnmTable.call_number = $acnTable.id";
933 $query .= "\n$acnTable.record = ?";
934 $query .= "\nand $acnTable.owning_lib in (select id from actor.org_unit where opac_visible)";
935 if (@{$self->{libs}}) {
936 $query .= "\nand owning_lib in (";
937 $query .= join(',', @{$self->{libs}}) . ")";
939 $query .= "\nand deleted = 'f'" unless($Marque::config->option_value('since'));
940 $query .= "\nlimit 1";
941 $self->{acnUriHandle} = $self->{handle}->prepare($query);
944 if ($self->{acnUriHandle}->execute($bre)) {
945 (my $result) = $self->{acnUriHandle}->fetchrow_array();
949 # If for some reason, we don't find anything.
953 # Returns an array of acn objects for a given bre object or id.
957 $bre = $bre->id() if (ref($bre));
959 unless ($self->{acnHandle}) {
960 my $query = "select " . join(',', $self->{acnClass}->real_fields());
961 $query .= "\nfrom " . $self->{acnClass}->Table();
962 $query .= "\nwhere record = ?";
963 if (@{$self->{libs}}) {
964 $query .= "\nand owning_lib in (";
965 $query .= join(',', @{$self->{libs}}) . ")";
966 } elsif ($Marque::config->option_value('exclude-hidden')) {
967 $query .= "\nand owning_lib in (select id from actor.org_unit where opac_visible)";
969 $query .= "\nand deleted = 'f'" unless($Marque::config->option_value('since'));
970 $self->{acnHandle} = $self->{handle}->prepare($query);
973 if ($self->{acnHandle}->execute($bre)) {
974 my $result = $self->{acnHandle}->fetchall_arrayref({});
975 return map {$self->{acnClass}->from_bare_hash($_)} @{$result};
978 # If for some reason, we don't find anything.
982 # Returns an array of acp objects for a given bre object or id.
986 $bre = $bre->id() if (ref($bre));
988 my $orgs = $self->orgs();
989 my $locations = $self->shelves();
990 my $prefixes = $self->prefixes();
991 my $suffixes = $self->suffixes();
992 my $statuses = $self->statuses();
994 my @acns = $self->acns_for_bre($bre);
997 #Setup a prepared statement for the first call
998 unless ($self->{acpHandle}) {
999 my $query = 'select ' . join(',', $self->{acpClass}->real_fields());
1000 $query .= "\nfrom " . $self->{acpClass}->Table();
1001 $query .= "\nwhere call_number = ANY(?::INT[])";
1002 #$query .= join(',', map {$_->id()} @acns);
1004 $query .= "\nand deleted = 'f'" unless ($Marque::config->option_value('since'));
1005 $query .= "\nand opac_visible" if ($Marque::config->option_value('exclude-hidden'));
1006 $self->{acpHandle} = $self->{handle}->prepare($query);
1009 #Use the prepared statement
1011 my @acnsa = map {$_->id()} @acns;
1012 if ($self->{acpHandle}->execute( \@acnsa )) {
1013 $result = $self->{acpHandle}->fetchall_arrayref( {} );
1016 if ($result && @{$result}) {
1017 my @acps = map {$self->{acpClass}->from_bare_hash($_)} @{$result};
1019 my $cn = $_->call_number();
1020 my ($acn) = grep {$_->id() == $cn} @acns;
1021 $acn->owning_lib($orgs->{$acn->owning_lib()});
1022 $_->call_number($acn);
1023 $_->circ_lib($orgs->{$_->circ_lib()});
1024 $_->location($locations->{$_->location()});
1025 $_->status($statuses->{$_->status()});
1026 $_->call_number->prefix($prefixes->{$acn->prefix()});
1027 $_->call_number->suffix($suffixes->{$acn->suffix()});
1033 # If for some reason, we don't find anything.
1037 # Retreive an array for sre objects when the --mfhd option is used.
1041 $bre = $bre->id() if (ref($bre));
1043 # Build a query to retrieve SREs when the MFHD option is passed.
1044 if ($Marque::config->option_value('mfhd')) {
1045 # Create a persistent handle as needed.
1046 unless ($self->{sreSth}) {
1047 my $query = "select " . join(',', $self->{sreClass}->real_fields());
1048 $query .= "\nfrom " . $self->{sreClass}->Table();
1049 $query .= "\nwhere record = ?";
1050 $query .= "\nand deleted = 'f'" unless ($Marque::config->option_value('since'));
1051 $self->{sreSth} = $self->{handle}->prepare($query);
1053 if ($self->{sreSth}->execute($bre)) {
1054 while (my $data = $self->{sreSth}->fetchrow_hashref) {
1055 push @sres, $self->{sreClass}->from_bare_hash($data);
1057 $self->{sreSth}->finish; # Sometimes DBI complains.
1064 # Get authority records from the database.
1065 package Marque::Authority;
1070 my $self = {idlist => $idlist};
1071 $self->{handle} = Marque::Connector::connect(
1072 $Marque::config->database_settings);
1073 $self->{fmClass} = Fieldmapper::class_for_hint('are');
1074 $self->{since_date} = Date::Manip::Date->new;
1075 $self->{since_date}->parse($Marque::config->option_value('since'));
1076 bless $self, $class;
1083 # Get the information for are object from the Fieldmapper:
1084 my @fields = $self->{fmClass}->real_fields();
1085 my $table = $self->{fmClass}->Table();
1087 # Build the actual query.
1088 my $select = "select " . join(',', @fields);
1089 my $from = "from $table";
1090 my $where = 'where ';
1092 # If we have an idlist, we pretty much ignore anything else.
1093 if ($self->{idlist} && @{$self->{idlist}}) {
1094 $where .= 'id in (' . join(',', @{$self->{idlist}}) . ')';
1095 } elsif ($Marque::config->option_value('since')) {
1096 my $since_str = Marque::Connector::db_date($self->{since_date});
1097 $where .= "edit_date > '$since_str'";
1098 $where .= " or create_date > '$since_str'";
1100 # We want all non-deleted records.
1101 $where .= "deleted = 'f'";
1104 $self->{query} = $select . "\n" . $from . "\n" . $where;
1110 $self->build_query() unless ($self->{query});
1111 unless ($self->{cursor}) {
1112 $self->{cursor} = 'DECLARE auths CURSOR WITH HOLD FOR ' . $self->{query};
1113 $self->{handle}->do($self->{cursor});
1114 $self->{fetchcmd} = 'fetch ' . $Marque::config->option_value('batch-size') . ' from auths';
1116 $self->{sth} = $self->{handle}->prepare($self->{fetchcmd});
1117 return $self->{sth}->execute;
1123 my $data = $self->{sth}->fetchrow_hashref;
1126 # We ran out of data, so try fetching the next batch.
1127 if ($self->execute_query()) {
1128 $data = $self->{sth}->fetchrow_hashref();
1133 my $format = $Marque::config->option_value('format');
1134 my $r = $self->{fmClass}->from_bare_hash($data);
1135 if ($format eq 'ARE') {
1136 $output = OpenSRF::Utils::JSON->perl2JSON($r);
1140 local $SIG{__WARN__} = sub {
1141 my $message = "Warning from authority record " . $r->id() . ": "
1145 $marc = MARC::Record->new_from_xml($r->marc(),
1146 $Marque::config->option_value('encoding'),
1147 $Marque::config->option_value('format'));
1150 warn("Error in authority record " . $r->id() . ": $@");
1151 import MARC::File::XML; # Reset SAX Parser.
1152 return $self->next();
1154 if ($Marque::config->option_value('replace_001')) {
1155 my $tcn = $marc->field('001');
1157 $tcn->update($r->id());
1159 $tcn = MARC::Field->new('001', $r->id());
1160 $marc->insert_fields_ordered($tcn);
1164 my $strip_arg_ref = $Marque::config->option_value('strip');
1165 my @strip = @{$strip_arg_ref};
1167 foreach my $strip_ref (@strip) {
1168 my $tagRE = $strip_ref->{tag};
1169 my $subfieldRE = $strip_ref->{subfield};
1171 if ( $subfieldRE eq "") {
1172 # Case 1: Field only check, e.g. "--strip 5.[0,1]"
1173 # If the supplied regexp matches the field, then
1174 # delete that field.
1175 foreach my $test_field ($marc->fields()) {
1176 if ($test_field->tag() =~ /$tagRE/) {
1178 $marc->delete_field($test_field);
1181 } elsif ($subfieldRE ne "" && $tagRE ne "") {
1182 # Case 2: Field & subfield supplied.
1183 # Note a blank tag will be wildcarded to "*".
1184 # Traverse fields, then traverse subfields if match
1186 foreach my $test_field ($marc->fields()) {
1187 if ( !$test_field->is_control_field() &&
1188 $test_field->tag() =~ /$tagRE/) {
1189 # Traverse all subfields:
1190 foreach my $test_subfield ($test_field->subfields()) {
1191 my $sfcode = @{$test_subfield}[0];
1192 if ($sfcode =~ /$subfieldRE/) {
1193 $test_field->delete_subfield($sfcode);
1201 if ($Marque::config->option_value('since')) {
1202 my $leader = $marc->leader();
1203 if ($U->is_true($r->deleted())) {
1204 substr($leader, 5, 1) = 'd';
1205 $marc->leader($leader);
1207 my $create_date = Date::Manip::Date->new;
1208 $create_date->parse($r->create_date());
1209 my $edit_date = Date::Manip::Date->new;
1210 $edit_date->parse($r->edit_date());
1211 if ($self->{since_date}->cmp($create_date) < 0) {
1212 substr($leader, 5, 1) = 'n';
1213 $marc->leader($leader);
1214 } elsif ($self->{since_date}->cmp($edit_date) < 0) {
1215 substr($leader, 5, 1) = 'c';
1216 $marc->leader($leader);
1220 if ($Marque::config->option_value('format') eq 'XML') {
1222 local $SIG{__WARN__} = sub {
1223 my $message = "Warning from authority record " . $r->id() . ": "
1227 $output = $marc->as_xml_record;
1228 $output =~ s/^<\?.+?\?>$//mo;
1231 warn("Error in authority record " . $r->id() . ": $@");
1232 return $self->next();
1236 local $SIG{__WARN__} = sub {
1237 my $message = "Warning from authority record " . $r->id() . ": "
1241 $output = $marc->as_usmarc;
1244 warn("Error in authority record " . $r->id() . ": $@");
1245 return $self->next();
1254 # ------------------------------------------------------------------
1255 # Since the ultimate output is largely independent of the type of the
1256 # records, we use a single subpackage to group our output routines.
1257 package Marque::Output;
1260 my $extractor = shift;
1261 if ($extractor->execute_query) {
1262 if ($Marque::config->option_value('encoding') eq 'UTF-8') {
1263 binmode(STDOUT, ':utf8');
1265 binmode(STDOUT, ':raw');
1269 while (my $output = $extractor->next()) {
1274 print STDERR $extractor->{query} if ($Marque::config->option_value('debug'));
1275 die "Database query failed!";
1280 if ($Marque::config->option_value('format') eq 'XML') {
1281 my $encoding = $Marque::config->option_value('encoding');
1283 <?xml version="1.0" encoding="$encoding"?>
1284 <collection xmlns='http://www.loc.gov/MARC21/slim'>
1290 if ($Marque::config->option_value('format') eq 'XML') {
1291 print "</collection>\n";