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