DB improvements : adding foreign keys on some tables. partial stuff done.
[koha.git] / updater / updatedatabase
1 #!/usr/bin/perl
2
3 # $Id$
4
5 # Database Updater
6 # This script checks for required updates to the database.
7
8 # Part of the Koha Library Software www.koha.org
9 # Licensed under the GPL.
10
11 # Bugs/ToDo:
12 # - Would also be a good idea to offer to do a backup at this time...
13
14 # NOTE:  If you do something more than once in here, make it table driven.
15 use strict;
16
17 # CPAN modules
18 use DBI;
19 use Getopt::Long;
20 # Koha modules
21 use C4::Context;
22
23 use MARC::Record;
24 use MARC::File::XML;
25
26 # FIXME - The user might be installing a new database, so can't rely
27 # on /etc/koha.conf anyway.
28
29 my $debug = 0;
30
31 my (
32     $sth, $sti,
33     $query,
34     %existingtables,    # tables already in database
35     %types,
36     $table,
37     $column,
38     $type, $null, $key, $default, $extra,
39     $prefitem,          # preference item in systempreferences table
40 );
41
42 my $silent;
43 GetOptions(
44         's' =>\$silent
45         );
46 my $dbh = C4::Context->dbh;
47 print "connected to your DB. Checking & modifying it\n" unless $silent;
48 $|=1; # flushes output
49
50 #-------------------
51 # Defines
52
53 # Tables to add if they don't exist
54 my %requiretables = (
55     categorytable       => "(categorycode char(5) NOT NULL default '',
56                              description text default '',
57                              itemtypecodes text default '',
58                              PRIMARY KEY (categorycode)
59                             )",
60     subcategorytable       => "(subcategorycode char(5) NOT NULL default '',
61                              description text default '',
62                              itemtypecodes text default '',
63                              PRIMARY KEY (subcategorycode)
64                             )",
65     mediatypetable       => "(mediatypecode char(5) NOT NULL default '',
66                              description text default '',
67                              itemtypecodes text default '',
68                              PRIMARY KEY (mediatypecode)
69                             )",
70     action_logs         => "(
71                                     `timestamp` TIMESTAMP NOT NULL ,
72                                     `user` INT( 11 ) NOT NULL ,
73                                     `module` TEXT default '',
74                                     `action` TEXT default '' ,
75                                     `object` INT(11) default '' ,
76                                     `info` TEXT default '' ,
77                                     PRIMARY KEY ( `timestamp` , `user` )
78                             )",
79         letter          => "(
80                                         module varchar(20) NOT NULL default '',
81                                         code varchar(20) NOT NULL default '',
82                                         name varchar(100) NOT NULL default '',
83                                         title varchar(200) NOT NULL default '',
84                                         content text,
85                                         PRIMARY KEY  (module,code)
86                                 )",
87         alert           =>"(
88                                         alertid int(11) NOT NULL auto_increment,
89                                         borrowernumber int(11) NOT NULL default '0',
90                                         type varchar(10) NOT NULL default '',
91                                         externalid varchar(20) NOT NULL default '',
92                                         PRIMARY KEY  (alertid),
93                                         KEY borrowernumber (borrowernumber),
94                                         KEY type (type,externalid)
95                                 )",
96
97 );
98
99 my %requirefields = (
100         subscription => { 'letter' => 'char(20) NULL', 'distributedto' => 'text NULL'},
101         itemtypes => { 'imageurl' => 'char(200) NULL'},
102 #    tablename        => { 'field' => 'fieldtype' },
103 );
104
105 my %dropable_table = (
106 # tablename => 'tablename',
107 );
108
109 my %uselessfields = (
110 # tablename => "field1,field2",
111         );
112 # the other hash contains other actions that can't be done elsewhere. they are done
113 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
114
115 # The tabledata hash contains data that should be in the tables.
116 # The uniquefieldrequired hash entry is used to determine which (if any) fields
117 # must not exist in the table for this row to be inserted.  If the
118 # uniquefieldrequired entry is already in the table, the existing data is not
119 # modified, unless the forceupdate hash entry is also set.  Fields in the
120 # anonymous "forceupdate" hash will be forced to be updated to the default
121 # values given in the %tabledata hash.
122
123 my %tabledata = (
124 # tablename => [
125 #       {       uniquefielrequired => 'fieldname', # the primary key in the table
126 #               fieldname => fieldvalue,
127 #               fieldname2 => fieldvalue2,
128 #       },
129 # ],
130     systempreferences => [
131                 {
132             uniquefieldrequired => 'variable',
133             variable            => 'Activate_Log',
134             value               => 'On',
135             forceupdate         => { 'explanation' => 1,
136                                      'type' => 1},
137             explanation         => 'Turn Log Actions on DB On an Off',
138             type                => 'YesNo',
139         },
140         {
141             uniquefieldrequired => 'variable',
142             variable            => 'IndependantBranches',
143             value               => 0,
144             forceupdate         => { 'explanation' => 1,
145                                      'type' => 1},
146             explanation         => 'Turn Branch independancy management On an Off',
147             type                => 'YesNo',
148         },
149                 {
150             uniquefieldrequired => 'variable',
151             variable            => 'ReturnBeforeExpiry',
152             value               => 'Off',
153             forceupdate         => { 'explanation' => 1,
154                                      'type' => 1},
155             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
156             type                => 'YesNo',
157         },
158         {
159             uniquefieldrequired => 'variable',
160             variable            => 'opacstylesheet',
161             value               => '',
162             forceupdate         => { 'explanation' => 1,
163                                      'type' => 1},
164             explanation         => 'Enter a complete URL to use an alternate stylesheet in OPAC',
165             type                => 'free',
166         },
167         {
168             uniquefieldrequired => 'variable',
169             variable            => 'opacsmallimage',
170             value               => '',
171             forceupdate         => { 'explanation' => 1,
172                                      'type' => 1},
173             explanation         => 'Enter a complete URL to an image, will be on top/left instead of the Koha logo',
174             type                => 'free',
175         },
176         {
177             uniquefieldrequired => 'variable',
178             variable            => 'opaclargeimage',
179             value               => '',
180             forceupdate         => { 'explanation' => 1,
181                                      'type' => 1},
182             explanation         => 'Enter a complete URL to an image, will be on the main page, instead of the Koha logo',
183             type                => 'free',
184         },
185         {
186             uniquefieldrequired => 'variable',
187             variable            => 'delimiter',
188             value               => ';',
189             forceupdate         => { 'explanation' => 1,
190                                      'type' => 1},
191             explanation         => 'separator for reports exported to spreadsheet',
192             type                => 'free',
193         },
194         {
195             uniquefieldrequired => 'variable',
196             variable            => 'MIME',
197             value               => 'OPENOFFICE.ORG',
198             forceupdate         => { 'explanation' => 1,
199                                      'type' => 1,
200                                      'options' => 1},
201             explanation         => 'Define the default application for report exportations into files',
202                 type            => 'Choice',
203                 options         => 'EXCEL|OPENOFFICE.ORG'
204         },
205         {
206             uniquefieldrequired => 'variable',
207             variable            => 'Delimiter',
208             value               => ';',
209                 forceupdate             => { 'explanation' => 1,
210                                      'type' => 1,
211                                      'options' => 1},
212             explanation         => 'Define the default separator character for report exportations into files',
213                 type            => 'Choice',
214                 options         => ';|tabulation|,|/|\|#'
215         },
216         {
217             uniquefieldrequired => 'variable',
218             variable            => 'SubscriptionHistory',
219             value               => ';',
220                 forceupdate             => { 'explanation' => 1,
221                                      'type' => 1,
222                                      'options' => 1},
223             explanation         => 'Define the information level for serials history in OPAC',
224                 type            => 'Choice',
225                 options         => 'simplified|full'
226         },
227         {
228             uniquefieldrequired => 'variable',
229             variable            => 'hidelostitems',
230             value               => 'No',
231             forceupdate         => { 'explanation' => 1,
232                                      'type' => 1},
233             explanation         => 'show or hide "lost" items in OPAC.',
234             type                => 'YesNo',
235         },
236                  {
237             uniquefieldrequired => 'variable',
238             variable            => 'IndependantBranches',
239             value               => '0',
240             forceupdate         => { 'explanation' => 1,
241                                      'type' => 1},
242             explanation         => 'Turn Branch independancy management On an Off',
243             type                => 'YesNo',
244         },
245                 {
246             uniquefieldrequired => 'variable',
247             variable            => 'ReturnBeforeExpiry',
248             value               => '0',
249             forceupdate         => { 'explanation' => 1,
250                                      'type' => 1},
251             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
252             type                => 'YesNo',
253         },
254         {
255             uniquefieldrequired => 'variable',
256             variable            => 'Disable_Dictionary',
257             value               => '0',
258             forceupdate         => { 'explanation' => 1,
259                                      'type' => 1},
260             explanation         => 'Disables Dictionary buttons if set to yes',
261             type                => 'YesNo',
262         },
263         {
264             uniquefieldrequired => 'variable',
265             variable            => 'hide_marc',
266             value               => '0',
267             forceupdate         => { 'explanation' => 1,
268                                      'type' => 1},
269             explanation         => 'hide marc specific datas like subfield code & indicators to library',
270             type                => 'YesNo',
271         },
272         {
273             uniquefieldrequired => 'variable',
274             variable            => 'NotifyBorrowerDeparture',
275             value               => '0',
276             forceupdate         => { 'explanation' => 1,
277                                      'type' => 1},
278             explanation         => 'Delay before expiry where a notice is sent when issuing',
279             type                => 'Integer',
280         },
281         {
282             uniquefieldrequired => 'variable',
283             variable            => 'OpacPasswordChange',
284             value               => '1',
285             forceupdate         => { 'explanation' => 1,
286                                      'type' => 1},
287             explanation         => 'Enable/Disable password change in OPAC (disable it when using LDAP auth)',
288             type                => 'YesNo',
289         },
290     ],
291
292 );
293
294 my %fielddefinitions = (
295 # fieldname => [
296 #       {                 field => 'fieldname',
297 #             type    => 'fieldtype',
298 #             null    => '',
299 #             key     => '',
300 #             default => ''
301 #         },
302 #     ],
303         serial => [
304         {
305             field   => 'notes',
306             type    => 'TEXT',
307             null    => 'NULL',
308             key     => '',
309             default => '',
310             extra   => ''
311         },
312     ],
313         aqbasket =>  [
314                 {
315                         field   => 'booksellerid',
316                         type    => 'int(11)',
317                         null    => 'NOT NULL',
318                         key             => '',
319                         default => '1',
320                         extra   => '',
321                 },
322         ],
323 );
324
325 my %indexes = (
326 #       table => [
327 #               {       indexname => 'index detail'
328 #               }
329 #       ],
330         shelfcontents => [
331                 {       indexname => 'shelfnumber',
332                         content => 'shelfnumber',
333                 },
334                 {       indexname => 'itemnumber',
335                         content => 'itemnumber',
336                 }
337         ],
338         bibliosubject => [
339                 {       indexname => 'biblionumber',
340                         content => 'biblionumber',
341                 }
342         ],
343         items => [
344                 {       indexname => 'homebranch',
345                         content => 'homebranch',
346                 },
347                 {       indexname => 'holdingbranch',
348                         content => 'holdingbranch',
349                 }
350         ],
351         aqbooksellers => [
352                 {       indexname => 'PRIMARY',
353                         content => 'id',
354                         type => 'PRIMARY',
355                 }
356         ],
357         aqbasket => [
358                 {       indexname => 'booksellerid',
359                         content => 'booksellerid',
360                 },
361         ],
362         aqorders => [
363                 {       indexname => 'basketno',
364                         content => 'basketno',
365                 },
366         ],
367         aqorderbreakdown => [
368                 {       indexname => 'ordernumber',
369                         content => 'ordernumber',
370                 },
371         ],
372 );
373
374 my %foreign_keys = (
375 #       table => [
376 #               {       key => 'the key in table' (must be indexed)
377 #                       foreigntable => 'the foreigntable name', # (the parent)
378 #                       foreignkey => 'the foreign key column(s)' # (in the parent)
379 #                       onUpdate => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
380 #                       onDelete => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
381 #               }
382 #       ],
383         shelfcontents => [
384                 {       key => 'shelfnumber',
385                         foreigntable => 'bookshelf',
386                         foreignkey => 'shelfnumber',
387                         onUpdate => 'CASCADE',
388                         onDelete => 'CASCADE',
389                 },
390                 {       key => 'itemnumber',
391                         foreigntable => 'items',
392                         foreignkey => 'itemnumber',
393                         onUpdate => 'CASCADE',
394                         onDelete => 'CASCADE',
395                 },
396         ],
397         biblioitems => [
398                 {       key => 'biblionumber',
399                         foreigntable => 'biblio',
400                         foreignkey => 'biblionumber',
401                         onUpdate => 'CASCADE',
402                         onDelete => 'CASCADE',
403                 },
404         ],
405         items => [
406                 {       key => 'biblioitemnumber',
407                         foreigntable => 'biblioitems',
408                         foreignkey => 'biblioitemnumber',
409                         onUpdate => 'CASCADE',
410                         onDelete => 'CASCADE',
411                 },
412                 {       key => 'homebranch',
413                         foreigntable => 'branches',
414                         foreignkey => 'branchcode',
415                         onUpdate => 'RESTRICT',
416                         onDelete => 'RESTRICT',
417                 },
418                 {       key => 'holdingbranch',
419                         foreigntable => 'branches',
420                         foreignkey => 'branchcode',
421                         onUpdate => 'RESTRICT',
422                         onDelete => 'RESTRICT',
423                 },
424         ],
425         additionalauthors => [
426                 {       key => 'biblionumber',
427                         foreigntable => 'biblio',
428                         foreignkey => 'biblionumber',
429                         onUpdate => 'CASCADE',
430                         onDelete => 'CASCADE',
431                 },
432         ],
433         bibliosubject => [
434                 {       key => 'biblionumber',
435                         foreigntable => 'biblio',
436                         foreignkey => 'biblionumber',
437                         onUpdate => 'CASCADE',
438                         onDelete => 'CASCADE',
439                 },
440         ],
441         aqbasket => [
442                 {       key => 'booksellerid',
443                         foreigntable => 'aqbooksellers',
444                         foreignkey => 'id',
445                         onUpdate => 'CASCADE',
446                         onDelete => 'RESTRICT',
447                 },
448 #               {       key => 'booksellerid',
449 #                       foreigntable => 'aqbooksellers',
450 #                       foreignkey => 'id',
451 #                       onUpdate => 'CASCADE',
452 #                       onDelete => 'RESTRICT',
453 #               },
454         ],
455         aqorders => [
456                 {       key => 'basketno',
457                         foreigntable => 'aqbasket',
458                         foreignkey => 'basketno',
459                         onUpdate => 'CASCADE',
460                         onDelete => 'CASCADE',
461                 },
462         ],
463         aqorderbreakdown => [
464                 {       key => 'ordernumber',
465                         foreigntable => 'aqorders',
466                         foreignkey => 'ordernumber',
467                         onUpdate => 'CASCADE',
468                         onDelete => 'CASCADE',
469                 },
470         ],
471 );
472
473 #-------------------
474 # Initialize
475
476 # Start checking
477
478 # Get version of MySQL database engine.
479 my $mysqlversion = `mysqld --version`;
480 $mysqlversion =~ /Ver (\S*) /;
481 $mysqlversion = $1;
482 if ( $mysqlversion ge '3.23' ) {
483     print "Could convert to MyISAM database tables...\n" unless $silent;
484 }
485
486 #---------------------------------
487 # Tables
488
489 # Collect all tables into a list
490 $sth = $dbh->prepare("show tables");
491 $sth->execute;
492 while ( my ($table) = $sth->fetchrow ) {
493     $existingtables{$table} = 1;
494 }
495
496
497 # Now add any missing tables
498 foreach $table ( keys %requiretables ) {
499     unless ( $existingtables{$table} ) {
500         print "Adding $table table...\n" unless $silent;
501         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
502         $sth->execute;
503         if ( $sth->err ) {
504             print "Error : $sth->errstr \n";
505             $sth->finish;
506         }    # if error
507     }    # unless exists
508 }    # foreach
509
510 # now drop useless tables
511 foreach $table ( keys %dropable_table ) {
512         if ( $existingtables{$table} ) {
513                 print "Dropping unused table $table\n" if $debug and not $silent;
514                 $dbh->do("drop table $table");
515                 if ( $dbh->err ) {
516                         print "Error : $dbh->errstr \n";
517                 }
518         }
519 }
520
521 #---------------------------------
522 # Columns
523
524 foreach $table ( keys %requirefields ) {
525     print "Check table $table\n" if $debug and not $silent;
526     $sth = $dbh->prepare("show columns from $table");
527     $sth->execute();
528     undef %types;
529     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
530     {
531         $types{$column} = $type;
532     }    # while
533     foreach $column ( keys %{ $requirefields{$table} } ) {
534         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
535         if ( !$types{$column} ) {
536
537             # column doesn't exist
538             print "Adding $column field to $table table...\n" unless $silent;
539             $query = "alter table $table
540                         add column $column " . $requirefields{$table}->{$column};
541             print "Execute: $query\n" if $debug;
542             my $sti = $dbh->prepare($query);
543             $sti->execute;
544             if ( $sti->err ) {
545                 print "**Error : $sti->errstr \n";
546                 $sti->finish;
547             }    # if error
548         }    # if column
549     }    # foreach column
550 }    # foreach table
551
552 foreach $table ( keys %fielddefinitions ) {
553         print "Check table $table\n" if $debug;
554         $sth = $dbh->prepare("show columns from $table");
555         $sth->execute();
556         my $definitions;
557         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
558         {
559                 $definitions->{$column}->{type}    = $type;
560                 $definitions->{$column}->{null}    = $null;
561                 $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
562                 $definitions->{$column}->{key}     = $key;
563                 $definitions->{$column}->{default} = $default;
564                 $definitions->{$column}->{extra}   = $extra;
565         }    # while
566         my $fieldrow = $fielddefinitions{$table};
567         foreach my $row (@$fieldrow) {
568                 my $field   = $row->{field};
569                 my $type    = $row->{type};
570                 my $null    = $row->{null};
571 #               $null    = 'YES' if $row->{null} eq 'NULL';
572                 my $key     = $row->{key};
573                 my $default = $row->{default};
574                 my $null    = $row->{null};
575 #               $default="''" unless $default;
576                 my $extra   = $row->{extra};
577                 my $def     = $definitions->{$field};
578
579                 unless ( $type eq $def->{type}
580                         && $null eq $def->{null}
581                         && $key eq $def->{key}
582                         && $extra eq $def->{extra} )
583                 {
584                         if ( $null eq '' ) {
585                                 $null = 'NOT NULL';
586                         }
587                         if ( $key eq 'PRI' ) {
588                                 $key = 'PRIMARY KEY';
589                         }
590                         unless ( $extra eq 'auto_increment' ) {
591                                 $extra = '';
592                         }
593
594                         # if it's a new column use "add", if it's an old one, use "change".
595                         my $action;
596                         if ($definitions->{$field}->{type}) {
597                                 $action="change $field"
598                         } else {
599                                 $action="add";
600                         }
601 # if it's a primary key, drop the previous pk, before altering the table
602                         my $sth;
603                         if ($key ne 'PRIMARY KEY') {
604                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ?");
605                         } else {
606                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ?");
607                         }
608                         $sth->execute($default);
609                         print "  Alter $field in $table\n" unless $silent;
610                 }
611         }
612 }
613
614
615 # Populate tables with required data
616
617
618 # synch table and deletedtable.
619 foreach my $table (('borrowers','items','biblio','biblioitems')) {
620         my %deletedborrowers;
621         print "synch'ing $table\n";
622         $sth = $dbh->prepare("show columns from deleted$table");
623         $sth->execute;
624         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
625                 $deletedborrowers{$column}=1;
626         }
627         $sth = $dbh->prepare("show columns from $table");
628         $sth->execute;
629         my $previous;
630         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
631                 unless ($deletedborrowers{$column}) {
632                         my $newcol="alter table deleted$table add $column $type";
633                         if ($null eq 'YES') {
634                                 $newcol .= " NULL ";
635                         } else {
636                                 $newcol .= " NOT NULL ";
637                         }
638                         $newcol .= "default $default" if $default;
639                         $newcol .= " after $previous" if $previous;
640                         $previous=$column;
641                         print "creating column $column\n";
642                         $dbh->do($newcol);
643                 }
644         }
645 }
646
647 foreach my $table ( keys %tabledata ) {
648     print "Checking for data required in table $table...\n" unless $silent;
649     my $tablerows = $tabledata{$table};
650     foreach my $row (@$tablerows) {
651         my $uniquefieldrequired = $row->{uniquefieldrequired};
652         my $uniquevalue         = $row->{$uniquefieldrequired};
653         my $forceupdate         = $row->{forceupdate};
654         my $sth                 =
655           $dbh->prepare(
656 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
657         );
658         $sth->execute($uniquevalue);
659                 if ($sth->rows) {
660                         foreach my $field (keys %$forceupdate) {
661                                 if ($forceupdate->{$field}) {
662                                         my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
663                                         $sth->execute($row->{$field}, $uniquevalue);
664                                 }
665                 }
666                 } else {
667                         print "Adding row to $table: " unless $silent;
668                         my @values;
669                         my $fieldlist;
670                         my $placeholders;
671                         foreach my $field ( keys %$row ) {
672                                 next if $field eq 'uniquefieldrequired';
673                                 next if $field eq 'forceupdate';
674                                 my $value = $row->{$field};
675                                 push @values, $value;
676                                 print "  $field => $value" unless $silent;
677                                 $fieldlist .= "$field,";
678                                 $placeholders .= "?,";
679                         }
680                         print "\n" unless $silent;
681                         $fieldlist    =~ s/,$//;
682                         $placeholders =~ s/,$//;
683                         my $sth =
684                         $dbh->prepare(
685                                 "insert into $table ($fieldlist) values ($placeholders)");
686                         $sth->execute(@values);
687                 }
688         }
689 }
690
691 #
692 # check indexes and create them when needed
693 #
694 print "Checking for index required...\n" unless $silent;
695 foreach my $table ( keys %indexes ) {
696         #
697         # read all indexes from $table
698         #
699         $sth = $dbh->prepare("show index from $table");
700         $sth->execute;
701         my %existingindexes;
702         while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow ) {
703                 $existingindexes{$key_name} = 1;
704         }
705         # read indexes to check
706         my $tablerows = $indexes{$table};
707         foreach my $row (@$tablerows) {
708                 my $key_name=$row->{indexname};
709                 if ($existingindexes{$key_name} eq 1) {
710 #                       print "$key_name existing";
711                 } else {
712                         print "Creating $key_name in $table\n";
713                         my $sql;
714                         if ($row->{indexname} eq 'PRIMARY') {
715                                 $sql = "alter table $table ADD PRIMARY KEY ($row->{content})";
716                         } else {
717                                 $sql = "alter table $table ADD INDEX $key_name ($row->{content}) $row->{type}";
718                         }
719                         $dbh->do($sql);
720             print "Error $sql : $dbh->err \n" if $dbh->err;
721                 }
722         }
723 }
724
725 #
726 # check foreign keys and create them when needed
727 #
728 print "Checking for foreign keys required...\n" unless $silent;
729 foreach my $table ( keys %foreign_keys ) {
730         #
731         # read all indexes from $table
732         #
733         $sth = $dbh->prepare("show table status like '$table'");
734         $sth->execute;
735         my $stat = $sth->fetchrow_hashref;
736         # read indexes to check
737         my $tablerows = $foreign_keys{$table};
738         foreach my $row (@$tablerows) {
739                 my $foreign_table=$row->{foreigntable};
740                 if ($stat->{'Comment'} =~/$foreign_table/) {
741 #                       print "$foreign_table existing\n";
742                 } else {
743                         print "Creating $foreign_table in $table\n";
744                         # first, drop any orphan value in child table
745                         my $sql = "delete from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})";
746                         $dbh->do($sql);
747             print "SQL ERROR: $sql : $dbh->err \n" if $dbh->err;
748                         $sql="alter table $table ADD FOREIGN KEY $row->{key} ($row->{key}) REFERENCES $row->{foreigntable} ($row->{foreignkey})";
749                         $sql .= " on update ".$row->{onUpdate} if $row->{onUpdate};
750                         $sql .= " on delete ".$row->{onDelete} if $row->{onDelete};
751                         $dbh->do($sql);
752             print "SQL ERROR: $sql : $dbh->errstr \n" if $dbh->err;
753                 }
754         }
755 }
756
757 #
758 # SPECIFIC STUFF
759 #
760 #
761 # create frameworkcode row in biblio table & fill it with marc_biblio.frameworkcode.
762 #
763
764 # 1st, get how many biblio we will have to do...
765 $sth = $dbh->prepare('select count(*) from marc_biblio');
766 $sth->execute;
767 my ($totaltodo) = $sth->fetchrow;
768
769 $sth = $dbh->prepare("show columns from biblio");
770 $sth->execute();
771 my $definitions;
772 my $bibliofwexist=0;
773 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
774         $bibliofwexist=1 if $column eq 'frameworkcode';
775 }
776 unless ($bibliofwexist) {
777         print "moving biblioframework to biblio table\n";
778         $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
779         $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
780         $sth->execute;
781         my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
782         my $totaldone=0;
783         while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
784                 $sth_update->execute($frameworkcode,$biblionumber);
785                 $totaldone++;
786                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
787         }
788         print "\rdone\n";
789 }
790
791 #
792 # moving MARC data from marc_subfield_table to biblioitems.marc
793 #
794 $sth = $dbh->prepare("show columns from biblioitems");
795 $sth->execute();
796 my $definitions;
797 my $marcdone=0;
798 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
799         $marcdone=1 if ($type eq 'blob' && $column eq 'marc') ;
800 }
801 unless ($marcdone) {
802         print "moving MARC record to biblioitems table\n";
803         # changing marc field type
804         $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` BLOB NULL DEFAULT NULL ');
805         # adding marc xml, just for convenience
806         $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` TEXT NOT NULL');
807         # moving data from marc_subfield_value to biblio
808         $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio');
809         $sth->execute;
810         my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?');
811         my $totaldone=0;
812         while (my ($bibid,$biblionumber) = $sth->fetchrow) {
813                 my $record = MARCgetbiblio($dbh,$bibid);
814                 $sth_update->execute($record->as_usmarc(),$record->as_xml(),$biblionumber);
815                 $totaldone++;
816                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
817         }
818         print "\rdone\n";
819 }
820
821 # MOVE all tables TO UTF-8 and innoDB
822 $sth = $dbh->prepare("show table status");
823 $sth->execute;
824 while ( my $table = $sth->fetchrow_hashref ) {
825         if ($table->{Engine} ne 'InnoDB') {
826                 $dbh->do("ALTER TABLE $table->{Name} TYPE = innodb");
827                 print "moving $table->{Name} to InnoDB\n";
828         }
829         unless ($table->{Collation} =~ /^utf8/) {
830                 $dbh->do("ALTER TABLE $table->{Name} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
831                 # FIXME : maybe a ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 would be better, def char set seems to work fine. If any problem encountered, let's try with convert !
832                 print "moving $table->{Name} to utf8\n";
833         } else {
834         }
835 }
836
837 # at last, remove useless fields
838 foreach $table ( keys %uselessfields ) {
839         my @fields = split /,/,$uselessfields{$table};
840         my $fields;
841         my $exists;
842         foreach my $fieldtodrop (@fields) {
843                 $fieldtodrop =~ s/\t//g;
844                 $fieldtodrop =~ s/\n//g;
845                 $exists =0;
846                 $sth = $dbh->prepare("show columns from $table");
847                 $sth->execute;
848                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
849                 {
850                         $exists =1 if ($column eq $fieldtodrop);
851                 }
852                 if ($exists) {
853                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
854                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
855                         $sth->execute;
856                 }
857         }
858 }    # foreach
859
860
861 $sth->finish;
862
863 #
864 # those 2 subs are a copy of Biblio.pm, version 2.2.4
865 # they are useful only once, for moving from 2.2 to 3.0
866 # the MARCgetbiblio & MARCgetitem subs in Biblio.pm
867 # are still here, but uses other tables
868 # (the ones that are filled by updatedatabase !)
869 #
870 sub MARCgetbiblio {
871
872     # Returns MARC::Record of the biblio passed in parameter.
873     my ( $dbh, $bibid ) = @_;
874     my $record = MARC::Record->new();
875 #       warn "". $bidid;
876
877     my $sth =
878       $dbh->prepare(
879 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
880                                  from marc_subfield_table
881                                  where bibid=? order by tag,tagorder,subfieldorder
882                          "
883     );
884     my $sth2 =
885       $dbh->prepare(
886         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
887     $sth->execute($bibid);
888     my $prevtagorder = 1;
889     my $prevtag      = 'XXX';
890     my $previndicator;
891     my $field;        # for >=10 tags
892     my $prevvalue;    # for <10 tags
893     while ( my $row = $sth->fetchrow_hashref ) {
894
895         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
896             $sth2->execute( $row->{'valuebloblink'} );
897             my $row2 = $sth2->fetchrow_hashref;
898             $sth2->finish;
899             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
900         }
901         if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
902             $previndicator .= "  ";
903             if ( $prevtag < 10 ) {
904                                 if ($prevtag ne '000') {
905                         $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
906                                 } else {
907                                         $record->leader(sprintf("%24s",$prevvalue));
908                                 }
909             }
910             else {
911                 $record->add_fields($field) unless $prevtag eq "XXX";
912             }
913             undef $field;
914             $prevtagorder  = $row->{tagorder};
915             $prevtag       = $row->{tag};
916             $previndicator = $row->{tag_indicator};
917             if ( $row->{tag} < 10 ) {
918                 $prevvalue = $row->{subfieldvalue};
919             }
920             else {
921                 $field = MARC::Field->new(
922                     ( sprintf "%03s", $prevtag ),
923                     substr( $row->{tag_indicator} . '  ', 0, 1 ),
924                     substr( $row->{tag_indicator} . '  ', 1, 1 ),
925                     $row->{'subfieldcode'},
926                     $row->{'subfieldvalue'}
927                 );
928             }
929         }
930         else {
931             if ( $row->{tag} < 10 ) {
932                 $record->add_fields( ( sprintf "%03s", $row->{tag} ),
933                     $row->{'subfieldvalue'} );
934             }
935             else {
936                 $field->add_subfields( $row->{'subfieldcode'},
937                     $row->{'subfieldvalue'} );
938             }
939             $prevtag       = $row->{tag};
940             $previndicator = $row->{tag_indicator};
941         }
942     }
943
944     # the last has not been included inside the loop... do it now !
945     if ( $prevtag ne "XXX" )
946     { # check that we have found something. Otherwise, prevtag is still XXX and we
947          # must return an empty record, not make MARC::Record fail because we try to
948          # create a record with XXX as field :-(
949         if ( $prevtag < 10 ) {
950             $record->add_fields( $prevtag, $prevvalue );
951         }
952         else {
953
954             #           my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
955             $record->add_fields($field);
956         }
957     }
958     return $record;
959 }
960
961 sub MARCgetitem {
962
963     # Returns MARC::Record of the biblio passed in parameter.
964     my ( $dbh, $bibid, $itemnumber ) = @_;
965     my $record = MARC::Record->new();
966
967     # search MARC tagorder
968     my $sth2 =
969       $dbh->prepare(
970 "select tagorder from marc_subfield_table,marc_subfield_structure where marc_subfield_table.tag=marc_subfield_structure.tagfield and marc_subfield_table.subfieldcode=marc_subfield_structure.tagsubfield and bibid=? and kohafield='items.itemnumber' and subfieldvalue=?"
971     );
972     $sth2->execute( $bibid, $itemnumber );
973     my ($tagorder) = $sth2->fetchrow_array();
974
975     #---- TODO : the leader is missing
976     my $sth =
977       $dbh->prepare(
978 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
979                                  from marc_subfield_table
980                                  where bibid=? and tagorder=? order by subfieldcode,subfieldorder
981                          "
982     );
983     $sth2 =
984       $dbh->prepare(
985         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
986     $sth->execute( $bibid, $tagorder );
987     while ( my $row = $sth->fetchrow_hashref ) {
988         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
989             $sth2->execute( $row->{'valuebloblink'} );
990             my $row2 = $sth2->fetchrow_hashref;
991             $sth2->finish;
992             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
993         }
994         if ( $record->field( $row->{'tag'} ) ) {
995             my $field;
996
997 #--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
998             #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
999             if ( length( $row->{'tag'} ) < 3 ) {
1000                 $row->{'tag'} = "0" . $row->{'tag'};
1001             }
1002             $field = $record->field( $row->{'tag'} );
1003             if ($field) {
1004                 my $x =
1005                   $field->add_subfields( $row->{'subfieldcode'},
1006                     $row->{'subfieldvalue'} );
1007                 $record->delete_field($field);
1008                 $record->add_fields($field);
1009             }
1010         }
1011         else {
1012             if ( length( $row->{'tag'} ) < 3 ) {
1013                 $row->{'tag'} = "0" . $row->{'tag'};
1014             }
1015             my $temp =
1016               MARC::Field->new( $row->{'tag'}, " ", " ",
1017                 $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
1018             $record->add_fields($temp);
1019         }
1020
1021     }
1022     return $record;
1023 }
1024
1025
1026 exit;
1027
1028 # $Log$
1029 # Revision 1.127  2006/01/24 17:57:17  tipaul
1030 # DB improvements : adding foreign keys on some tables. partial stuff done.
1031 #
1032 # Revision 1.126  2006/01/06 16:39:42  tipaul
1033 # synch'ing head and rel_2_2 (from 2.2.5, including npl templates)
1034 # Seems not to break too many things, but i'm probably wrong here.
1035 # at least, new features/bugfixes from 2.2.5 are here (tested on some features on my head local copy)
1036 #
1037 # - removing useless directories (koha-html and koha-plucene)
1038 #
1039 # Revision 1.125  2006/01/04 15:54:55  tipaul
1040 # utf8 is a : go for beta test in HEAD.
1041 # some explanations :
1042 # - updater/updatedatabase => will transform all tables in innoDB (not related to utf8, just to warn you) AND collate them in utf8 / utf8_general_ci. The SQL command is : ALTER TABLE tablename DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci.
1043 # - *-top.inc will show the pages in utf8
1044 # - THE HARD THING : for me, mysql-client and mysql-server were set up to communicate in iso8859-1, whatever the mysql collation ! Thus, pages were improperly shown, as datas were transmitted in iso8859-1 format ! After a full day of investigation, someone on usenet pointed "set NAMES 'utf8'" to explain that I wanted utf8. I could put this in my.cnf, but if I do that, ALL databases will "speak" in utf8, that's not what we want. Thus, I added a line in Context.pm : everytime a DB handle is opened, the communication is set to utf8.
1045 # - using marcxml field and no more the iso2709 raw marc biblioitems.marc field.
1046 #
1047 # Revision 1.124  2005/10/27 12:09:05  tipaul
1048 # new features for serial module :
1049 # - the last 5 issues are now shown, and their status can be changed (but not reverted to "waited", as there can be only one "waited")
1050 # - the library can create a "distribution list". this paper contains a list of borrowers (selected from the borrower list, or manually entered), and print it for a given issue. once printed, the sheet can be put on the issue and distributed to every reader on the list (one by one).
1051 #
1052 # Revision 1.123  2005/10/26 09:13:37  tipaul
1053 # big commit, still breaking things...
1054 #
1055 # * synch with rel_2_2. Probably the last non manual synch, as rel_2_2 should not be modified deeply.
1056 # * code cleaning (cleaning warnings from perl -w) continued
1057 #
1058 # Revision 1.122  2005/09/02 14:18:38  tipaul
1059 # new feature : image for itemtypes.
1060 #
1061 # * run updater/updatedatabase to create imageurl field in itemtypes.
1062 # * go to Koha >> parameters >> itemtypes >> modify (or add) an itemtype. You will see around 20 nice images to choose between (thanks to owen). If you prefer your own image, you also can type a complete url (http://www.myserver.lib/path/to/my/image.gif)
1063 # * go to OPAC, and search something. In the result list, you now have the picture instead of the text itemtype.
1064 #
1065 # Revision 1.121  2005/08/24 08:49:03  hdl
1066 # Adding a note field in serial table.
1067 # This will allow librarian to mention a note on a peculiar waiting serial number.
1068 #
1069 # Revision 1.120  2005/08/09 14:10:32  tipaul
1070 # 1st commit to go to zebra.
1071 # don't update your cvs if you want to have a working head...
1072 #
1073 # this commit contains :
1074 # * updater/updatedatabase : get rid with marc_* tables, but DON'T remove them. As a lot of things uses them, it would not be a good idea for instance to drop them. If you really want to play, you can rename them to test head without them but being still able to reintroduce them...
1075 # * Biblio.pm : modify MARCgetbiblio to find the raw marc record in biblioitems.marc field, not from marc_subfield_table, modify MARCfindframeworkcode to find frameworkcode in biblio.frameworkcode, modify some other subs to use biblio.biblionumber & get rid of bibid.
1076 # * other files : get rid of bibid and use biblionumber instead.
1077 #
1078 # What is broken :
1079 # * does not do anything on zebra yet.
1080 # * if you rename marc_subfield_table, you can't search anymore.
1081 # * you can view a biblio & bibliodetails, go to MARC editor, but NOT save any modif.
1082 # * don't try to add a biblio, it would add data poorly... (don't try to delete either, it may work, but that would be a surprise ;-) )
1083 #
1084 # IMPORTANT NOTE : you need MARC::XML package (http://search.cpan.org/~esummers/MARC-XML-0.7/lib/MARC/File/XML.pm), that requires a recent version of MARC::Record
1085 # Updatedatabase stores the iso2709 data in biblioitems.marc field & an xml version in biblioitems.marcxml Not sure we will keep it when releasing the stable version, but I think it's a good idea to have something readable in sql, at least for development stage.
1086 #
1087 # Revision 1.119  2005/08/04 16:07:58  tipaul
1088 # Synch really broke this script...
1089 #
1090 # Revision 1.118  2005/08/04 16:02:55  tipaul
1091 # oops... error in synch between 2.2 and head
1092 #
1093 # Revision 1.117  2005/08/04 14:24:39  tipaul
1094 # synch'ing 2.2 and head
1095 #
1096 # Revision 1.116  2005/08/04 08:55:54  tipaul
1097 # Letters / alert system, continuing...
1098 #
1099 # * adding a package Letters.pm, that manages Letters & alerts.
1100 # * adding feature : it's now possible to define a "letter" for any subscription created. If a letter is defined, users in OPAC can put an alert on the subscription. When an issue is marked "arrived", all users in the alert will recieve a mail (as defined in the "letter"). This last part (= send the mail) is not yet developped. (Should be done this week)
1101 # * adding feature : it's now possible to "put to an alert" in OPAC, for any serial subscription. The alert is stored in a new table, called alert. An alert can be put only if the librarian has activated them in subscription (and they activate it just by choosing a "letter" to sent to borrowers on new issues)
1102 # * adding feature : librarian can see in borrower detail which alerts they have put, and a user can see in opac-detail which alert they have put too.
1103 #
1104 # Note that the system should be generic enough to manage any type of alert.
1105 # I plan to extend it soon to virtual shelves : a borrower will be able to put an alert on a virtual shelf, to be warned when something is changed in the virtual shelf (mail being sent once a day by cron, or manually by the shelf owner. Anyway, a mail won't be sent on every change, users would be spammed by Koha ;-) )
1106 #
1107 # Revision 1.115  2005/08/02 16:15:34  tipaul
1108 # adding 2 fields to letter system :
1109 # * module (acquisition, catalogue...) : it will be usefull to show the librarian only letters he may be interested by.
1110 # * title, that will be used as mail subject.
1111 #
1112 # Revision 1.114  2005/07/28 15:10:13  tipaul
1113 # Introducing new "Letters" system : Letters will be used everytime you want to sent something to someone (through mail or paper). For example, sending a mail for overdues use letter that you can put as parameters. Sending a mail to a borrower when a suggestion is validated uses a letter too.
1114 # the letter table contains 3 fields :
1115 # * code => the code of the letter
1116 # * name => the complete name of the letter
1117 # * content => the complete text. It's a TEXT field type, so has no limits.
1118 #
1119 # My next goal now is to work on point 2-I "serial issue alert"
1120 # With this feature, in serials, a user can subscribe the "issue alert". For every issue arrived/missing, a mail is sent to all subscribers of this list. The mail warns the user that the issue is arrive or missing. Will be in head.
1121 # (see mail on koha-devel, 2005/04/07)
1122 #
1123 # The "serial issue alert" will be the 1st to use this letter system that probably needs some tweaking ;-)
1124 #
1125 # Once it will be stabilised default letters (in any languages) could be added during installer to help the library begin with this new feature.
1126 #
1127 # Revision 1.113  2005/07/28 08:38:41  tipaul
1128 # For instance, the return date does not rely on the borrower expiration date. A systempref will be added in Koha, to modify return date calculation schema :
1129 # * ReturnBeforeExpiry = yes => return date can't be after expiry date
1130 # * ReturnBeforeExpiry = no  => return date can be after expiry date
1131 #
1132 # Revision 1.112  2005/07/26 08:19:47  hdl
1133 # Adding IndependantBranches System preference variable in order to manage Branch independancy.
1134 #
1135 # Revision 1.111  2005/07/25 15:35:38  tipaul
1136 # we have decided that moving to Koha 3.0 requires being already in Koha 2.2.x
1137 # So, the updatedatabase script can highly be cleaned (90% removed).
1138 # Let's play with the new Koha DB structure now ;-)
1139 #