/
marc_export.in
executable file
·1295 lines (1165 loc) · 50.8 KB
/
marc_export.in
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# ---------------------------------------------------------------
# Copyright © 2013 Merrimack Valley Library Consortium
# Jason Stephenson <jstephenson@mvlc.org>
#
# 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 .= <<ACN_JOIN;
join $acnTable on $acnTable.record = $breTable.id
and $acnTable.owning_lib in (
ACN_JOIN
$from .= join(',', @{$self->{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();