Bug 26311: (QA follow-up) Update script documentation
[koha.git] / misc / batchRebuildBiblioTables.pl
1 #!/usr/bin/perl
2 # Small script that rebuilds the non-MARC DB
3 # Formerly named rebuildnonmarc.pl
4
5 use strict;
6 #use warnings; FIXME - Bug 2505
7
8 # Koha modules used
9 use Koha::Script;
10 use MARC::Record;
11 use C4::Charset;
12 use C4::Context;
13 use C4::Biblio qw(
14     GetXmlBiblio
15     TransformMarcToKoha
16 );
17 use Time::HiRes qw( gettimeofday );
18
19 use Getopt::Long qw( GetOptions );
20
21 my ($version, $confirm);
22 GetOptions(
23     'c' => \$confirm,
24     'h' => \$version
25 );
26
27 if ($version || (!$confirm)) {
28     print <<EOF
29 This script rebuilds the non-MARC fields from the MARC values.
30 You can/must use it when you change your mapping.
31
32 Example: you decide to map biblio.title to 200\$a (it was previously mapped to 610\$a).
33 Run this script or you will have strange results in the UI!
34
35 Syntax:
36 \t./batchRebuildBiblioTables.pl -h (or without arguments => show this screen)
37 \t./batchRebuildBiblioTables.pl -c (c like confirm => rebuild non-MARC fields (may take long)
38 EOF
39 ;
40     exit;
41 }
42
43 $|=1; # non-buffered output
44
45 my $dbh = C4::Context->dbh;
46 my $i=0;
47 my $starttime = gettimeofday;
48 my $marcflavour = C4::Context->preference('marcflavour');
49 my $sth = $dbh->prepare('SELECT biblionumber, frameworkcode FROM biblio');
50 $sth->execute();
51
52 my @errors;
53 while (my ($biblionumber, $frameworkcode) = $sth->fetchrow) {
54     my $marcxml = GetXmlBiblio($biblionumber);
55     if (not defined $marcxml) {
56         push @errors, $biblionumber;
57         next;
58     }
59
60     $marcxml = C4::Charset::StripNonXmlChars( $marcxml );
61     my $record = eval {
62         MARC::Record::new_from_xml($marcxml, 'UTF-8', $marcflavour);
63     };
64     if ($@) {
65         push @errors, $biblionumber;
66         next;
67     }
68
69     my $biblio = TransformMarcToKoha({ record => $record });
70     C4::Biblio::_koha_modify_biblio($dbh, $biblio, $frameworkcode);
71     C4::Biblio::_koha_modify_biblioitem_nonmarc($dbh, $biblio);
72
73     $i++;
74     printf("%lu records processed in %.2f seconds\n", $i, gettimeofday() - $starttime) unless ($i % 100);
75 }
76
77 printf("\n%lu records processed in %.2f seconds\n", $i, gettimeofday() - $starttime);
78 if (scalar(@errors) > 0) {
79     print "Some records could not be processed though: ", join(' ', @errors);
80 }