Bug 11278: Adjusting bulkmarcimport.pl for customization routine and verbose printing
[koha.git] / misc / migration_tools / bulkmarcimport.pl
1 #!/usr/bin/perl
2 # Import an iso2709 file into Koha 3
3
4 use strict;
5 use warnings;
6 #use diagnostics;
7 BEGIN {
8     # find Koha's Perl modules
9     # test carefully before changing this
10     use FindBin;
11     eval { require "$FindBin::Bin/../kohalib.pl" };
12 }
13
14 # Koha modules used
15 use MARC::File::USMARC;
16 use MARC::File::XML;
17 use MARC::Record;
18 use MARC::Batch;
19 use MARC::Charset;
20
21 use C4::Context;
22 use C4::Biblio;
23 use C4::Koha;
24 use C4::Debug;
25 use C4::Charset;
26 use C4::Items;
27 use YAML;
28 use Unicode::Normalize;
29 use Time::HiRes qw(gettimeofday);
30 use Getopt::Long;
31 use IO::File;
32 use Pod::Usage;
33
34 my $localcust= $FindBin::Bin.'/LocalChanges.pm';
35 $localcust= -e $localcust? $localcust: undef;
36 require $localcust if $localcust;
37 $localcust=\&customize if $localcust;
38
39 use open qw( :std :encoding(UTF-8) );
40 binmode( STDOUT, ":encoding(UTF-8)" );
41 my ( $input_marc_file, $number, $offset) = ('',0,0);
42 my ($version, $delete, $test_parameter, $skip_marc8_conversion, $char_encoding, $verbose, $commit, $fk_off,$format,$biblios,$authorities,$keepids,$match, $isbn_check, $logfile);
43 my ( $insert, $filters, $update, $all, $yamlfile, $authtypes, $append );
44 my $cleanisbn = 1;
45 my ($sourcetag,$sourcesubfield,$idmapfl, $dedup_barcode);
46 my $framework = '';
47
48 $|=1;
49
50 GetOptions(
51     'commit:f'    => \$commit,
52     'file:s'    => \$input_marc_file,
53     'n:f' => \$number,
54     'o|offset:f' => \$offset,
55     'h' => \$version,
56     'd' => \$delete,
57     't|test' => \$test_parameter,
58     's' => \$skip_marc8_conversion,
59     'c:s' => \$char_encoding,
60     'v:i' => \$verbose,
61     'fk' => \$fk_off,
62     'm:s' => \$format,
63     'l:s' => \$logfile,
64     'append' => \$append,
65     'k|keepids:s' => \$keepids,
66     'b|biblios' => \$biblios,
67     'a|authorities' => \$authorities,
68     'authtypes:s' => \$authtypes,
69     'filter=s@'     => \$filters,
70     'insert'        => \$insert,
71     'update'        => \$update,
72     'all'           => \$all,
73     'match=s@'    => \$match,
74     'i|isbn' => \$isbn_check,
75     'x:s' => \$sourcetag,
76     'y:s' => \$sourcesubfield,
77     'idmap:s' => \$idmapfl,
78     'cleanisbn!'     => \$cleanisbn,
79     'yaml:s'        => \$yamlfile,
80     'dedupbarcode' => \$dedup_barcode,
81     'framework=s' => \$framework,
82 );
83 $biblios ||= !$authorities;
84 $insert  ||= !$update;
85 my $writemode = ($append) ? "a" : "w";
86
87 if ($all) {
88     $insert = 1;
89     $update = 1;
90 }
91
92 if ($version || ($input_marc_file eq '')) {
93     pod2usage( -verbose => 2 );
94     exit;
95 }
96
97 my $dbh = C4::Context->dbh;
98 my $heading_fields=get_heading_fields();
99
100 if (defined $idmapfl) {
101   open(IDMAP,">$idmapfl") or die "cannot open $idmapfl \n";
102 }
103
104 if ((not defined $sourcesubfield) && (not defined $sourcetag)){
105   $sourcetag="910";
106   $sourcesubfield="a";
107 }
108
109 # save the CataloguingLog property : we don't want to log a bulkmarcimport. It will slow the import & 
110 # will create problems in the action_logs table, that can't handle more than 1 entry per second per user.
111 my $CataloguingLog = C4::Context->preference('CataloguingLog');
112 $dbh->do("UPDATE systempreferences SET value=0 WHERE variable='CataloguingLog'");
113
114 if ($fk_off) {
115         $dbh->do("SET FOREIGN_KEY_CHECKS = 0");
116 }
117
118
119 if ($delete) {
120         if ($biblios){
121         print "deleting biblios\n";
122         $dbh->do("truncate biblio");
123         $dbh->do("truncate biblioitems");
124         $dbh->do("truncate items");
125         }
126         else {
127         print "deleting authorities\n";
128         $dbh->do("truncate auth_header");
129         }
130     $dbh->do("truncate zebraqueue");
131 }
132
133
134
135 if ($test_parameter) {
136     print "TESTING MODE ONLY\n    DOING NOTHING\n===============\n";
137 }
138
139 my $marcFlavour = C4::Context->preference('marcflavour') || 'MARC21';
140
141 print "Characteristic MARC flavour: $marcFlavour\n" if $verbose;
142 my $starttime = gettimeofday;
143 my $batch;
144 my $fh = IO::File->new($input_marc_file); # don't let MARC::Batch open the file, as it applies the ':utf8' IO layer
145 if (defined $format && $format =~ /XML/i) {
146     # ugly hack follows -- MARC::File::XML, when used by MARC::Batch,
147     # appears to try to convert incoming XML records from MARC-8
148     # to UTF-8.  Setting the BinaryEncoding key turns that off
149     # TODO: see what happens to ISO-8859-1 XML files.
150     # TODO: determine if MARC::Batch can be fixed to handle
151     #       XML records properly -- it probably should be
152     #       be using a proper push or pull XML parser to
153     #       extract the records, not using regexes to look
154     #       for <record>.*</record>.
155     $MARC::File::XML::_load_args{BinaryEncoding} = 'utf-8';
156     my $recordformat= ($marcFlavour eq "MARC21"?"USMARC":uc($marcFlavour));
157 #UNIMARC Authorities have a different way to manage encoding than UNIMARC biblios.
158     $recordformat=$recordformat."AUTH" if ($authorities and $marcFlavour ne "MARC21");
159     $MARC::File::XML::_load_args{RecordFormat} = $recordformat;
160     $batch = MARC::Batch->new( 'XML', $fh );
161 } else {
162     $batch = MARC::Batch->new( 'USMARC', $fh );
163 }
164 $batch->warnings_off();
165 $batch->strict_off();
166 my $i=0;
167 my $commitnum = $commit ? $commit : 50;
168 my $yamlhash;
169
170 # Skip file offset
171 if ( $offset ) {
172     print "Skipping file offset: $offset records\n";
173     $batch->next() while ($offset--);
174 }
175
176 my ($tagid,$subfieldid);
177 if ($authorities){
178           $tagid='001';
179 }
180 else {
181    ( $tagid, $subfieldid ) =
182             GetMarcFromKohaField( "biblio.biblionumber", $framework );
183         $tagid||="001";
184 }
185
186 # the SQL query to search on isbn
187 my $sth_isbn = $dbh->prepare("SELECT biblionumber,biblioitemnumber FROM biblioitems WHERE isbn=?");
188
189 $dbh->{AutoCommit} = 0;
190 my $loghandle;
191 if ($logfile){
192    $loghandle= IO::File->new($logfile, $writemode) ;
193    print $loghandle "id;operation;status\n";
194 }
195 RECORD: while (  ) {
196     my $record;
197     # get records
198     eval { $record = $batch->next() };
199     if ( $@ ) {
200         print "Bad MARC record $i: $@ skipped\n";
201         # FIXME - because MARC::Batch->next() combines grabbing the next
202         # blob and parsing it into one operation, a correctable condition
203         # such as a MARC-8 record claiming that it's UTF-8 can't be recovered
204         # from because we don't have access to the original blob.  Note
205         # that the staging import can deal with this condition (via
206         # C4::Charset::MarcToUTF8Record) because it doesn't use MARC::Batch.
207         next;
208     }
209     # skip if we get an empty record (that is MARC valid, but will result in AddBiblio failure
210     last unless ( $record );
211     $i++;
212     if( ($verbose//1)==1 ) { #no dot for verbose==2
213         print "." . ( $i % 100==0 ? "\n$i" : '' );
214     }
215
216     # transcode the record to UTF8 if needed & applicable.
217     if ($record->encoding() eq 'MARC-8' and not $skip_marc8_conversion) {
218         # FIXME update condition
219         my ($guessed_charset, $charset_errors);
220          ($record, $guessed_charset, $charset_errors) = MarcToUTF8Record($record, $marcFlavour.(($authorities and $marcFlavour ne "MARC21")?'AUTH':''));
221         if ($guessed_charset eq 'failed') {
222             warn "ERROR: failed to perform character conversion for record $i\n";
223             next RECORD;            
224         }
225     }
226     SetUTF8Flag($record);
227     &$localcust($record) if $localcust;
228     my $isbn;
229     # remove trailing - in isbn (only for biblios, of course)
230     if ($biblios && $cleanisbn) {
231         my $tag = $marcFlavour eq 'UNIMARC' ? '010' : '020';
232         my $field = $record->field($tag);
233         my $isbn = $field && $field->subfield('a');
234         if ( $isbn ) {
235             $isbn =~ s/-//g;
236             $field->update('a' => $isbn);
237         }
238     }
239     my $id;
240     # search for duplicates (based on Local-number)
241     my $originalid;
242     $originalid = GetRecordId( $record, $tagid, $subfieldid );
243     if ($match) {
244         require C4::Search;
245         my $query = build_query( $match, $record );
246         my $server = ( $authorities ? 'authorityserver' : 'biblioserver' );
247         $debug && warn $query;
248         my ( $error, $results, $totalhits ) = C4::Search::SimpleSearch( $query, 0, 3, [$server] );
249         die "unable to search the database for duplicates : $error" if ( defined $error );
250         $debug && warn "$query $server : $totalhits";
251         if ( $results && scalar(@$results) == 1 ) {
252             my $marcrecord = C4::Search::new_record_from_zebra( $server, $results->[0] );
253             SetUTF8Flag($marcrecord);
254             $id = GetRecordId( $marcrecord, $tagid, $subfieldid );
255             if ( $authorities && $marcFlavour ) {
256                 #Skip if authority in database is the same as the on in database
257                 if ( $marcrecord->field('005') && $record->field('005') &&
258                      $marcrecord->field('005')->data && $record->field('005')->data &&
259                      $marcrecord->field('005')->data >= $record->field('005')->data ) {
260                     if ($yamlfile) {
261                         $yamlhash->{$originalid}->{'authid'} = $id;
262
263                         # we recover all subfields of the heading authorities
264                         my @subfields;
265                         foreach my $field ( $marcrecord->field("2..") ) {
266                             push @subfields, map { ( $_->[0] =~ /[a-z]/ ? $_->[1] : () ) } $field->subfields();
267                         }
268                         $yamlhash->{$originalid}->{'subfields'} = \@subfields;
269                     }
270                     next;
271                 }
272             }
273         } elsif ( $results && scalar(@$results) > 1 ) {
274             $debug && warn "more than one match for $query";
275         } else {
276             $debug && warn "nomatch for $query";
277         }
278     }
279     if ($keepids && $originalid) {
280             my $storeidfield;
281             if ( length($keepids) == 3 ) {
282                 $storeidfield = MARC::Field->new( $keepids, $originalid );
283             } else {
284                 $storeidfield = MARC::Field->new( substr( $keepids, 0, 3 ), "", "", substr( $keepids, 3, 1 ), $originalid );
285             }
286             $record->insert_fields_ordered($storeidfield);
287             $record->delete_field( $record->field($tagid) );
288     }
289     foreach my $stringfilter (@$filters) {
290         if ( length($stringfilter) == 3 ) {
291             foreach my $field ( $record->field($stringfilter) ) {
292                 $record->delete_field($field);
293                 $debug && warn "removed : ", $field->as_string;
294             }
295         } elsif ($stringfilter =~ /([0-9]{3})([a-z0-9])(.*)/) {
296             my $removetag = $1;
297             my $removesubfield = $2;
298             my $removematch = $3;
299             if ( ( $removetag > "010" ) && $removesubfield ) {
300                 foreach my $field ( $record->field($removetag) ) {
301                     $field->delete_subfield( code => "$removesubfield", match => $removematch );
302                     $debug && warn "Potentially removed : ", $field->subfield($removesubfield);
303                 }
304             }
305         }
306     }
307     unless ($test_parameter) {
308         if ($authorities){
309             use C4::AuthoritiesMarc;
310             my $authtypecode=GuessAuthTypeCode($record, $heading_fields);
311             my $authid= ($id?$id:GuessAuthId($record));
312             if ($authid && GetAuthority($authid) && $update ){
313             ## Authority has an id and is in database : Replace
314                 eval { ( $authid ) = ModAuthority($authid,$record, $authtypecode) };
315                 if ($@){
316                     warn "Problem with authority $authid Cannot Modify";
317                                         printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ERROR"}) if ($logfile);
318                 }
319                                 else{
320                                         printlog({id=>$originalid||$id||$authid, op=>"edit",status=>"ok"}) if ($logfile);
321                                 }
322             }  
323             elsif (defined $authid) {
324             ## An authid is defined but no authority in database : add
325                 eval { ( $authid ) = AddAuthority($record,$authid, $authtypecode) };
326                 if ($@){
327                     warn "Problem with authority $authid Cannot Add ".$@;
328                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
329                 }
330                                 else{
331                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
332                                 }
333             }
334                 else {
335             ## True insert in database
336                 eval { ( $authid ) = AddAuthority($record,"", $authtypecode) };
337                 if ($@){
338                     warn "Problem with authority $authid Cannot Add".$@;
339                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ERROR"}) if ($logfile);
340                 }
341                                 else{
342                                         printlog({id=>$originalid||$id||$authid, op=>"insert",status=>"ok"}) if ($logfile);
343                                 }
344                 }
345             if ($yamlfile) {
346             $yamlhash->{$originalid}->{'authid'} = $authid;
347             my @subfields;
348             foreach my $field ( $record->field("2..") ) {
349                 push @subfields, map { ( $_->[0] =~ /[a-z]/ ? $_->[1] : () ) } $field->subfields();
350             }
351             $yamlhash->{$originalid}->{'subfields'} = \@subfields;
352             }
353         }
354         else {
355             my ( $biblionumber, $biblioitemnumber, $itemnumbers_ref, $errors_ref );
356             $biblionumber = $id;
357             # check for duplicate, based on ISBN (skip it if we already have found a duplicate with match parameter
358             if (!$biblionumber && $isbn_check && $isbn) {
359     #         warn "search ISBN : $isbn";
360                 $sth_isbn->execute($isbn);
361                 ($biblionumber,$biblioitemnumber) = $sth_isbn->fetchrow;
362             }
363                 if (defined $idmapfl) {
364                                 if ($sourcetag < "010"){
365                                         if ($record->field($sourcetag)){
366                                           my $source = $record->field($sourcetag)->data();
367                                           printf(IDMAP "%s|%s\n",$source,$biblionumber);
368                                         }
369                             } else {
370                                         my $source=$record->subfield($sourcetag,$sourcesubfield);
371                                         printf(IDMAP "%s|%s\n",$source,$biblionumber);
372                           }
373                         }
374                                         # create biblio, unless we already have it ( either match or isbn )
375             if ($biblionumber) {
376                 eval{$biblioitemnumber=GetBiblioData($biblionumber)->{biblioitemnumber};};
377                 if ($update) {
378                     eval { ( $biblionumber, $biblioitemnumber ) = ModBiblio( $record, $biblionumber, GetFrameworkcode($biblionumber) ) };
379                     if ($@) {
380                         warn "ERROR: Edit biblio $biblionumber failed: $@\n";
381                         printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "ERROR" } ) if ($logfile);
382                         next RECORD;
383                     } else {
384                         printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "ok" } ) if ($logfile);
385                     }
386                 } else {
387                     printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "warning : already in database" } ) if ($logfile);
388                 }
389             } else {
390                 if ($insert) {
391                     eval { ( $biblionumber, $biblioitemnumber ) = AddBiblio( $record, '', { defer_marc_save => 1 } ) };
392                     if ($@) {
393                         warn "ERROR: Adding biblio $biblionumber failed: $@\n";
394                         printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "ERROR" } ) if ($logfile);
395                         next RECORD;
396                     } else {
397                         printlog( { id => $id || $originalid || $biblionumber, op => "insert", status => "ok" } ) if ($logfile);
398                     }
399                 } else {
400                     printlog( { id => $id || $originalid || $biblionumber, op => "update", status => "warning : not in database" } ) if ($logfile);
401                 }
402             }
403             eval { ( $itemnumbers_ref, $errors_ref ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
404             my $error_adding = $@;
405             # Work on a clone so that if there are real errors, we can maybe
406             # fix them up later.
407                         my $clone_record = $record->clone();
408             C4::Biblio::_strip_item_fields($clone_record, '');
409             # This sets the marc fields if there was an error, and also calls
410             # defer_marc_save.
411             ModBiblioMarc( $clone_record, $biblionumber, $framework );
412             if ( $error_adding ) {
413                 warn "ERROR: Adding items to bib $biblionumber failed: $error_adding";
414                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
415                 # if we failed because of an exception, assume that 
416                 # the MARC columns in biblioitems were not set.
417                 next RECORD;
418             }
419                         else{
420                                 printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
421                         }
422             if ($dedup_barcode && grep { exists $_->{error_code} && $_->{error_code} eq 'duplicate_barcode' } @$errors_ref) {
423                 # Find the record called 'barcode'
424                 my ($tag, $sub) = C4::Biblio::GetMarcFromKohaField('items.barcode', $framework);
425                 # Now remove any items that didn't have a duplicate_barcode error,
426                 # erase the barcodes on items that did, and re-add those items.
427                 my %dupes;
428                 foreach my $i (0 .. $#{$errors_ref}) {
429                     my $ref = $errors_ref->[$i];
430                     if ($ref && ($ref->{error_code} eq 'duplicate_barcode')) {
431                         $dupes{$ref->{item_sequence}} = 1;
432                         # Delete the error message because we're going to
433                         # retry this one.
434                         delete $errors_ref->[$i];
435                     }
436                 }
437                 my $seq = 0;
438                 foreach my $field ($record->field($tag)) {
439                     $seq++;
440                     if ($dupes{$seq}) {
441                         # Here we remove the barcode
442                         $field->delete_subfield(code => $sub);
443                     } else {
444                         # otherwise we delete the field because we don't want
445                         # two of them
446                         $record->delete_fields($field);
447                     }
448                 }
449                 # Now re-add the record as before, adding errors to the prev list
450                 my $more_errors;
451                 eval { ( $itemnumbers_ref, $more_errors ) = AddItemBatchFromMarc( $record, $biblionumber, $biblioitemnumber, '' ); };
452                 if ( $@ ) {
453                     warn "ERROR: Adding items to bib $biblionumber failed: $@\n";
454                     printlog({id=>$id||$originalid||$biblionumber, op=>"insertitem",status=>"ERROR"}) if ($logfile);
455                     # if we failed because of an exception, assume that
456                     # the MARC columns in biblioitems were not set.
457                     ModBiblioMarc( $record, $biblionumber, $framework );
458                     next RECORD;
459                 } else {
460                     printlog({id=>$id||$originalid||$biblionumber, op=>"insert",status=>"ok"}) if ($logfile);
461                 }
462                 push @$errors_ref, @{ $more_errors };
463             }
464             if ($#{ $errors_ref } > -1) {
465                 report_item_errors($biblionumber, $errors_ref);
466             }
467             $yamlhash->{$originalid} = $biblionumber if ($yamlfile);
468         }
469         $dbh->commit() if (0 == $i % $commitnum);
470     }
471     print $record->as_formatted()."\n" if ($verbose//0)==2;
472     last if $i == $number;
473 }
474 $dbh->commit();
475 $dbh->{AutoCommit} = 1;
476
477
478 if ($fk_off) {
479         $dbh->do("SET FOREIGN_KEY_CHECKS = 1");
480 }
481
482 # restore CataloguingLog
483 $dbh->do("UPDATE systempreferences SET value=$CataloguingLog WHERE variable='CataloguingLog'");
484
485 my $timeneeded = gettimeofday - $starttime;
486 print "\n$i MARC records done in $timeneeded seconds\n";
487 if ($logfile){
488   print $loghandle "file : $input_marc_file\n";
489   print $loghandle "$i MARC records done in $timeneeded seconds\n";
490   $loghandle->close;
491 }
492 if ($yamlfile) {
493     open my $yamlfileout, q{>}, "$yamlfile" or die "cannot open $yamlfile \n";
494     print $yamlfileout Dump($yamlhash);
495 }
496 exit 0;
497
498 sub GetRecordId{
499         my $marcrecord=shift;
500         my $tag=shift;
501         my $subfield=shift;
502         my $id;
503         if ($tag lt "010"){
504                 return $marcrecord->field($tag)->data() if $marcrecord->field($tag);
505         } 
506         elsif ($subfield){
507                 if ($marcrecord->field($tag)){
508                         return $marcrecord->subfield($tag,$subfield);
509                 }
510         }
511         return $id;
512 }
513 sub build_query {
514         my $match = shift;
515         my $record=shift;
516         my @searchstrings;
517         foreach my $matchingpoint (@$match){
518           my $string = build_simplequery($matchingpoint,$record);
519           push @searchstrings,$string if (length($string)>0);
520         }
521     my $QParser;
522     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
523     my $op;
524     if ($QParser) {
525         $op = '&&';
526     } else {
527         $op = 'and';
528     }
529     return join(" $op ",@searchstrings);
530 }
531 sub build_simplequery {
532         my $element=shift;
533         my $record=shift;
534     my @searchstrings;
535     my ($index,$recorddata)=split /,/,$element;
536     if ($recorddata=~/(\d{3})(.*)/) {
537         my ($tag,$subfields) =($1,$2);
538         foreach my $field ($record->field($tag)){
539                   if (length($field->as_string("$subfields"))>0){
540               push @searchstrings,"$index:\"".$field->as_string("$subfields")."\"";
541                   }
542         }
543     }
544     my $QParser;
545     $QParser = C4::Context->queryparser if (C4::Context->preference('UseQueryParser'));
546     my $op;
547     if ($QParser) {
548         $op = '&&';
549     } else {
550         $op = 'and';
551     }
552     return join(" $op ",@searchstrings);
553 }
554 sub report_item_errors {
555     my $biblionumber = shift;
556     my $errors_ref = shift;
557
558     foreach my $error (@{ $errors_ref }) {
559         next if !$error;
560         my $msg = "Item not added (bib $biblionumber, item tag #$error->{'item_sequence'}, barcode $error->{'item_barcode'}): ";
561         my $error_code = $error->{'error_code'};
562         $error_code =~ s/_/ /g;
563         $msg .= "$error_code $error->{'error_information'}";
564         print $msg, "\n";
565     }
566 }
567 sub printlog{
568         my $logelements=shift;
569     print $loghandle join( ";", map { defined $_ ? $_ : "" } @$logelements{qw<id op status>} ), "\n";
570 }
571 sub get_heading_fields{
572     my $headingfields;
573     if ($authtypes){
574         $headingfields=YAML::LoadFile($authtypes);
575         $headingfields={C4::Context->preference('marcflavour')=>$headingfields};
576         $debug && warn YAML::Dump($headingfields);
577     }
578     unless ($headingfields){
579         $headingfields=$dbh->selectall_hashref("SELECT auth_tag_to_report, authtypecode from auth_types",'auth_tag_to_report',{Slice=>{}});
580         $headingfields={C4::Context->preference('marcflavour')=>$headingfields};
581     }
582     return $headingfields;
583 }
584
585 =head1 NAME
586
587 bulkmarcimport.pl - Import bibliographic/authority records into Koha
588
589 =head1 USAGE
590
591  $ export KOHA_CONF=/etc/koha.conf
592  $ perl misc/migration_tools/bulkmarcimport.pl -d -commit 1000 \\
593     -file /home/jmf/koha.mrc -n 3000
594
595 =head1 WARNING
596
597 Don't use this script before you've entered and checked your MARC parameters
598 tables twice (or more!). Otherwise, the import won't work correctly and you
599 will get invalid data.
600
601 =head1 DESCRIPTION
602
603 =over
604
605 =item  B<-h>
606
607 This version/help screen
608
609 =item B<-b, -biblios>
610
611 Type of import: bibliographic records
612
613 =item B<-a, -authorities>
614
615 Type of import: authority records
616
617 =item B<-file>=I<FILE>
618
619 The I<FILE> to import
620
621 =item  B<-v>
622
623 Verbose mode. 1 means "some infos", 2 means "MARC dumping"
624
625 =item B<-fk>
626
627 Turn off foreign key checks during import.
628
629 =item B<-n>=I<NUMBER>
630
631 The I<NUMBER> of records to import. If missing, all the file is imported
632
633 =item B<-o, -offset>=I<NUMBER>
634
635 File offset before importing, ie I<NUMBER> of records to skip.
636
637 =item B<-commit>=I<NUMBER>
638
639 The I<NUMBER> of records to wait before performing a 'commit' operation
640
641 =item B<-l>
642
643 File logs actions done for each record and their status into file
644
645 =item B<-append>
646
647 If specified, data will be appended to the logfile. If not, the logfile will be erased for each execution.
648
649 =item B<-t, -test>
650
651 Test mode: parses the file, saying what he would do, but doing nothing.
652
653 =item B<-s>
654
655 Skip automatic conversion of MARC-8 to UTF-8.  This option is provided for
656 debugging.
657
658 =item B<-c>=I<CHARACTERISTIC>
659
660 The I<CHARACTERISTIC> MARC flavour. At the moment, only I<MARC21> and
661 I<UNIMARC> are supported. MARC21 by default.
662
663 =item B<-d>
664
665 Delete EVERYTHING related to biblio in koha-DB before import. Tables: biblio,
666 biblioitems, items
667
668 =item B<-m>=I<FORMAT>
669
670 Input file I<FORMAT>: I<MARCXML> or I<ISO2709> (defaults to ISO2709)
671
672 =item B<-authtypes>
673
674 file yamlfile with authoritiesTypes and distinguishable record field in order
675 to store the correct authtype
676
677 =item B<-yaml>
678
679 yaml file  format a yaml file with ids
680
681 =item B<-filter>
682
683 list of fields that will not be imported. Can be any from 000 to 999 or field,
684 subfield and subfield's matching value such as 200avalue
685
686 =item B<-insert>
687
688 if set, only insert when possible
689
690 =item B<-update>
691
692 if set, only updates (any biblio should have a matching record)
693
694 =item B<-all>
695
696 if set, do whatever is required
697
698 =item B<-k, -keepids>=<FIELD>
699
700 Field store ids in I<FIELD> (usefull for authorities, where 001 contains the
701 authid for Koha, that can contain a very valuable info for authorities coming
702 from LOC or BNF. useless for biblios probably)
703
704 =item B<-match>=<FIELD>
705
706 I<FIELD> matchindex,fieldtomatch matchpoint to use to deduplicate fieldtomatch
707 can be either 001 to 999 or field and list of subfields as such 100abcde
708
709 =item B<-i,-isbn>
710
711 If set, a search will be done on isbn, and, if the same isbn is found, the
712 biblio is not added. It's another method to deduplicate.  B<-match> & B<-isbn>
713 can be both set.
714
715 =item B<-cleanisbn>
716
717 Clean ISBN fields from entering biblio records, ie removes hyphens. By default,
718 ISBN are cleaned. --nocleanisbn will keep ISBN unchanged.
719
720 =item B<-x>=I<TAG>
721
722 Source bib I<TAG> for reporting the source bib number
723
724 =item B<-y>=I<SUBFIELD>
725
726 Source I<SUBFIELD> for reporting the source bib number
727
728 =item B<-idmap>=I<FILE>
729
730 I<FILE> for the koha bib and source id
731
732 =item B<-keepids>
733
734 Store ids in 009 (usefull for authorities, where 001 contains the authid for
735 Koha, that can contain a very valuable info for authorities coming from LOC or
736 BNF. useless for biblios probably)
737
738 =item B<-dedupbarcode>
739
740 If set, whenever a duplicate barcode is detected, it is removed and the attempt
741 to add the record is retried, thereby giving the record a blank barcode. This
742 is useful when something has set barcodes to be a biblio ID, or similar
743 (usually other software.)
744
745 =item B<-framework>
746
747 This is the code for the framework that the requested records will have attached
748 to them when they are created. If not specified, then the default framework
749 will be used.
750
751 =back
752
753 =cut
754