fixing a bug that occured when adding a field into a table.
[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
16 use strict;
17
18 # CPAN modules
19 use DBI;
20
21 # Koha modules
22 use C4::Context;
23
24 # FIXME - The user might be installing a new database, so can't rely
25 # on /etc/koha.conf anyway.
26
27 my $debug = 1;
28
29 my (
30     $sth, $sti,
31     $query,
32     %existingtables,    # tables already in database
33     %types,
34     $table,
35     $column,
36     $type, $null, $key, $default, $extra,
37     $prefitem,          # preference item in systempreferences table
38 );
39
40 my $dbh = C4::Context->dbh;
41
42 #-------------------
43 # Defines
44
45 # Tables to add if they don't exist
46 my %requiretables = (
47     shelfcontents => "( shelfnumber int not null,
48                                                         itemnumber int not null,
49                                                         flags int)",
50     bookshelf => "( shelfnumber int auto_increment primary key,
51                                                 shelfname char(255))",
52     z3950queue => "( id int auto_increment primary key,
53                                                 term text,
54                                                 type char(10),
55                                                 startdate int,
56                                                 enddate int,
57                                                 done smallint,
58                                                 results longblob,
59                                                 numrecords int,
60                                                 servers text,
61                                                 identifier char(30))",
62     z3950results => "( id int auto_increment primary key,
63                                                 queryid int,
64                                                 server char(255),
65                                                 startdate int,
66                                                 enddate int,
67                                                 results longblob,
68                                                 numrecords int,
69                                                 numdownloaded int,
70                                                 highestseen int,
71                                                 active smallint)",
72     branchrelations => "( branchcode varchar(4),
73                                                         categorycode varchar(4))",
74     websites => "( websitenumber int(11) NOT NULL auto_increment,
75                                                 biblionumber int(11) NOT NULL default '0',
76                                                 title text,
77                                                 description text,
78                                                 url varchar(255),
79                                                 PRIMARY KEY (websitenumber) )",
80     marcrecorddone => "( isbn char(40),
81                                                                 issn char(40),
82                                                                 lccn char(40),
83                                                                 controlnumber char(40))",
84     uploadedmarc => "( id int(11) NOT NULL auto_increment PRIMARY KEY,
85                                                         marc longblob,
86                                                         hidden smallint(6) default NULL,
87                                                         name varchar(255) default NULL)",
88     ethnicity => "( code varchar(10) NOT NULL default '',
89                                         name varchar(255) default NULL,
90                                         PRIMARY KEY  (code)   )",
91     sessions => "( sessionID varchar(255) NOT NULL default '',
92                                                 userid varchar(255) default NULL,
93                                                 ip varchar(16) default NULL,
94                                                 lasttime int,
95                                                 PRIMARY KEY (sessionID)   )",
96     sessionqueries => "( sessionID varchar(255) NOT NULL default '',
97                                                                 userid char(100) NOT NULL default '',
98                                                                 ip char(18) NOT NULL default '',
99                                                                 url text NOT NULL default ''  )",
100     bibliothesaurus => "( id bigint(20) NOT NULL auto_increment,
101                                                         freelib char(255) NOT NULL default '',
102                                                         stdlib char(255) NOT NULL default '',
103                                                         category char(10) NOT NULL default '',
104                                                         level tinyint(4) NOT NULL default '1',
105                                                         hierarchy char(80) NOT NULL default '',
106                                                         father char(80) NOT NULL default '',
107                                                         PRIMARY KEY  (id),
108                                                         KEY freelib (freelib),
109                                                         KEY stdlib (stdlib),
110                                                         KEY category (category),
111                                                         KEY hierarchy (hierarchy)
112                                                         )",
113     marc_biblio => "(
114                                                 bibid bigint(20) unsigned NOT NULL auto_increment,
115                                                 biblionumber int(11) NOT NULL default '0',
116                                                 datecreated date NOT NULL default '0000-00-00',
117                                                 datemodified date default NULL,
118                                                 origincode char(20) default NULL,
119                                                 PRIMARY KEY  (bibid),
120                                                 KEY origincode (origincode),
121                                                 KEY biblionumber (biblionumber)
122                                                 ) ",
123     marc_blob_subfield => "(
124                                         blobidlink bigint(20) NOT NULL auto_increment,
125                                         subfieldvalue longtext NOT NULL,
126                                         PRIMARY KEY  (blobidlink)
127                                         ) ",
128     marc_subfield_structure => "(
129                                                 tagfield char(3) NOT NULL default '',
130                                                 tagsubfield char(1) NOT NULL default '',
131                                                 liblibrarian char(255) NOT NULL default '',
132                                                 libopac char(255) NOT NULL default '',
133                                                 repeatable tinyint(4) NOT NULL default '0',
134                                                 mandatory tinyint(4) NOT NULL default '0',
135                                                 kohafield char(40)  default NULL,
136                                                 tab tinyint(1) default NULL,
137                                                 authorised_value char(10) default NULL,
138                                                 thesaurus_category char(10) default NULL,
139                                                 value_builder char(80) default NULL,
140                                                 PRIMARY KEY  (tagfield,tagsubfield),
141                                                 KEY kohafield (kohafield),
142                                                 KEY tab (tab)
143                                                 )",
144     marc_subfield_table => "(
145                                                 subfieldid bigint(20) unsigned NOT NULL auto_increment,
146                                                 bibid bigint(20) unsigned NOT NULL default '0',
147                                                 tag char(3) NOT NULL default '',
148                                                 tagorder tinyint(4) NOT NULL default '1',
149                                                 tag_indicator char(2) NOT NULL default '',
150                                                 subfieldcode char(1) NOT NULL default '',
151                                                 subfieldorder tinyint(4) NOT NULL default '1',
152                                                 subfieldvalue varchar(255) default NULL,
153                                                 valuebloblink bigint(20) default NULL,
154                                                 PRIMARY KEY  (subfieldid),
155                                                 KEY bibid (bibid),
156                                                 KEY tag (tag),
157                                                 KEY tag_indicator (tag_indicator),
158                                                 KEY subfieldorder (subfieldorder),
159                                                 KEY subfieldcode (subfieldcode),
160                                                 KEY subfieldvalue (subfieldvalue),
161                                                 KEY tagorder (tagorder)
162                                         )",
163     marc_tag_structure => "(
164                                         tagfield char(3) NOT NULL default '',
165                                         liblibrarian char(255) NOT NULL default '',
166                                         libopac char(255) NOT NULL default '',
167                                         repeatable tinyint(4) NOT NULL default '0',
168                                         mandatory tinyint(4) NOT NULL default '0',
169                                         authorised_value char(10) default NULL,
170                                         PRIMARY KEY  (tagfield)
171                                         )",
172     marc_word => "(
173                                 bibid bigint(20) NOT NULL default '0',
174                                 tag char(3) NOT NULL default '',
175                                 tagorder tinyint(4) NOT NULL default '1',
176                                 subfieldid char(1) NOT NULL default '',
177                                 subfieldorder tinyint(4) NOT NULL default '1',
178                                 word varchar(255) NOT NULL default '',
179                                 sndx_word varchar(255) NOT NULL default '',
180                                 KEY bibid (bibid),
181                                 KEY tag (tag),
182                                 KEY tagorder (tagorder),
183                                 KEY subfieldid (subfieldid),
184                                 KEY subfieldorder (subfieldorder),
185                                 KEY word (word),
186                                 KEY sndx_word (sndx_word)
187                         )",
188     marc_breeding => "(  id bigint(20) NOT NULL auto_increment,
189                                 file varchar(80) NOT NULL default '',
190                                 isbn varchar(10) NOT NULL default '',
191                                 title varchar(128) default NULL,
192                                 author varchar(80) default NULL,
193                                 marc text NOT NULL,
194                                 encoding varchar(40) default NULL,
195                                 PRIMARY KEY  (id),
196                                 KEY title (title),
197                                 KEY isbn (isbn)
198                         )",
199     authorised_values => "(id int(11) NOT NULL auto_increment,
200                                 category char(10) NOT NULL default '',
201                                 authorised_value char(80) NOT NULL default '',
202                                 lib char(80) NULL,
203                                 PRIMARY KEY  (id),
204                                 KEY name (category)
205                         )",
206     userflags => "( bit int(11) NOT NULL default '0',
207                                 flag char(30), flagdesc char(255),
208                                 defaulton int(11)
209                         )",
210 );
211
212 my %requirefields = (
213     biblio        => { 'abstract' => 'text' },
214     deletedbiblio => { 'abstract' => 'text' },
215     biblioitems   => {
216         'lccn' => 'char(25)',
217         'url'  => 'varchar(255)',
218         'marc' => 'text'
219     },
220     deletedbiblioitems => {
221         'lccn' => 'char(25)',
222         'url'  => 'varchar(255)',
223         'marc' => 'text'
224     },
225     branchtransfers => { 'datearrived'    => 'datetime' },
226     statistics      => { 'borrowernumber' => 'int(11)' },
227     aqbooksellers   => {
228         'invoicedisc' => 'float(6,4)',
229         'nocalc'      => 'int(11)'
230     },
231     borrowers => {
232         'userid'        => 'char(30)',
233         'password'      => 'char(30)',
234         'flags'         => 'int(11)',
235         'textmessaging' => 'varchar(30)',
236            'zipcode' => 'varchar(25)',
237                         'homezipcode' => 'varchar(25)',
238     },
239     aqorders => { 'budgetdate' => 'date' },
240     aqbudget => {'aqbudgetid' => 'tinyint(4) auto_increment primary key'},
241
242     #added so that reference items are not available for reserves...
243     itemtypes         => { 'notforloan'  => 'smallint(6)' },
244     systempreferences => { 'explanation' => 'char(80)',
245                            'type' => 'char(20)',
246                            'options' => 'text' },
247     z3950servers      => { 'syntax'      => 'char(80)' },
248 );
249
250 my %dropable_table = (
251     classification => 'classification',
252     multipart      => 'multipart',
253     multivolume    => 'multivolume',
254     newitems       => 'newitems',
255     procedures     => 'procedures',
256     publisher      => 'publisher',
257     searchstats    => 'searchstats',
258     serialissues   => 'serialissues',
259 );
260
261 # The tabledata hash contains data that should be in the tables.
262 # The uniquefieldrequired hash entry is used to determine which (if any) fields
263 # must not exist in the table for this row to be inserted.  If the
264 # uniquefieldrequired entry is already in the table, the existing data is not
265 # modified, unless the forceupdate hash entry is also set.  Fields in the
266 # anonymous "forceupdate" hash will be forced to be updated to the default
267 # values given in the %tabledata hash.
268
269 my %tabledata = (
270     userflags => [
271         {
272             uniquefieldrequired => 'bit',
273             bit                 => 0,
274             flag                => 'superlibrarian',
275             flagdesc            => 'Access to all librarian functions',
276             defaulton           => 0
277         },
278         {
279             uniquefieldrequired => 'bit',
280             bit                 => 1,
281             flag                => 'circulate',
282             flagdesc            => 'Circulate books',
283             defaulton           => 0
284         },
285         {
286             uniquefieldrequired => 'bit',
287             bit                 => 2,
288             flag                => 'catalogue',
289             flagdesc            => 'View Catalogue (Librarian Interface)',
290             defaulton           => 0
291         },
292         {
293             uniquefieldrequired => 'bit',
294             bit                 => 3,
295             flag                => 'parameters',
296             flagdesc            => 'Set Koha system paramters',
297             defaulton           => 0
298         },
299         {
300             uniquefieldrequired => 'bit',
301             bit                 => 4,
302             flag                => 'borrowers',
303             flagdesc            => 'Add or modify borrowers',
304             defaulton           => 0
305         },
306         {
307             uniquefieldrequired => 'bit',
308             bit                 => 5,
309             flag                => 'permissions',
310             flagdesc            => 'Set user permissions',
311             defaulton           => 0
312         },
313         {
314             uniquefieldrequired => 'bit',
315             bit                 => 6,
316             flag                => 'reserveforothers',
317             flagdesc            => 'Reserve books for patrons',
318             defaulton           => 0
319         },
320         {
321             uniquefieldrequired => 'bit',
322             bit                 => 7,
323             flag                => 'borrow',
324             flagdesc            => 'Borrow books',
325             defaulton           => 1
326         },
327         {
328             uniquefieldrequired => 'bit',
329             bit                 => 8,
330             flag                => 'reserveforself',
331             flagdesc            => 'Reserve books for self',
332             defaulton           => 0
333         },
334         {
335             uniquefieldrequired => 'bit',
336             bit                 => 9,
337             flag                => 'editcatalogue',
338             flagdesc  => 'Edit Catalogue (Modify bibliographic/holdings data)',
339             defaulton => 0
340         },
341         {
342             uniquefieldrequired => 'bit',
343             bit                 => 10,
344             flag                => 'updatecharges',
345             flagdesc            => 'Update borrower charges',
346             defaulton           => 0
347         },
348     ],
349     systempreferences => [
350         {
351             uniquefieldrequired => 'variable',
352             forceupdate         => { 'explanation' => 1,
353                                      'type' => 1 },
354             variable            => 'autoMemberNum',
355             value               => '1',
356             explanation         => 'Member number is auto-calculated',
357             type                => 'YesNo'
358
359         },
360         {
361             uniquefieldrequired => 'variable',
362             forceupdate         => { 'explanation' => 1,
363                                      'type' => 1,
364                                      'options' => 1 },
365             variable            => 'acquisitions',
366             value               => 'simple',
367             explanation         =>
368 'Normal, budget-based acquisitions, or Simple bibliographic-data acquisitions',
369             type                => 'Choice',
370             options             => 'simple|normal'
371         },
372         {
373             uniquefieldrequired => 'variable',
374             forceupdate         => { 'explanation' => 1,
375                                      'type' => 1,
376                                      'options' => 1 },
377             variable            => 'dateformat',
378             value               => 'metric',
379             explanation         =>
380             'date format (US mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy/mm/dd)',
381             type                => 'Choice',
382             options             => 'metric|us|iso'
383         },
384         {
385             uniquefieldrequired => 'variable',
386             variable            => 'template',
387             forceupdate         => { 'explanation' => 1,
388                                      'type' => 1 },
389             value               => 'default',
390             explanation         => 'Preference order for intranet interface templates',
391             type                => 'Themes'
392         },
393         {
394             uniquefieldrequired => 'variable',
395             variable            => 'autoBarcode',
396             forceupdate         => { 'explanation' => 1,
397                                      'type' => 1 },
398             value               => 'yes',
399             explanation         => 'Barcode is auto-calculated',
400             type                => 'YesNo'
401         },
402         {
403             uniquefieldrequired => 'variable',
404             variable            => 'insecure',
405             forceupdate         => { 'explanation' => 1,
406                                      'type' => 1 },
407             value               => 'no',
408             explanation         =>
409 'If YES, no auth at all is needed. Be careful if you set this to yes!',
410             type                => 'YesNo'
411         },
412         {
413             uniquefieldrequired => 'variable',
414             variable            => 'authoritysep',
415             forceupdate         => { 'explanation' => 1,
416                                      'type' => 1,
417                                      'options' => 1 },
418             value               => '--',
419             explanation         =>
420             'the separator used in authority/thesaurus. Usually --',
421             type                => 'free',
422             options             => '10'
423         },
424         {
425             uniquefieldrequired => 'variable',
426             variable            => 'opaclanguages',
427             forceupdate         => { 'explanation' => 1,
428                                      'type' => 1 },
429             value               => 'en',
430             explanation         => 'Set the preferred order for translations.  The top language will be tried first.',
431             type                => 'Languages'
432         },
433         {
434             uniquefieldrequired => 'variable',
435             variable            => 'opacthemes',
436             forceupdate         => { 'explanation' => 1,
437                                      'type' => 1 },
438             value               => 'default',
439             explanation         => 'Set the preferred order for themes.  The top theme will be tried first.',
440             type                => 'Themes'
441         },
442         {
443             uniquefieldrequired => 'variable',
444             variable            => 'timeout',
445             forceupdate         => { 'explanation' => 1,
446                                      'type' => 1 },
447             value               => '1200',
448             explanation         => 'Inactivity timeout for cookies authentication (in seconds)',
449             type                => 'Integer'
450         },
451         {
452             uniquefieldrequired => 'variable',
453             variable            => 'marc',
454             forceupdate         => { 'explanation' => 1,
455                                      'type' => 1 },
456             value               => 'yes',
457             explanation         => 'Turn on MARC support',
458             type                => 'YesNo'
459         },
460         {
461             uniquefieldrequired => 'variable',
462             variable            => 'marcflavour',
463             forceupdate         => { 'explanation' => 1,
464                                      'type' => 1,
465                                      'options' => 1},
466             value               => 'MARC21',
467             explanation         =>
468             'your MARC flavor (MARC21 or UNIMARC) used for character encoding',
469             type                => 'Choice',
470             options             => 'MARC21|UNIMARC'
471         },
472         {
473             uniquefieldrequired => 'variable',
474             variable            => 'checkdigit',
475             value               => 'none',
476             forceupdate         => { 'explanation' => 1,
477                                      'type' => 1,
478                                      'options' => 1},
479             explanation         => 'Validity checks on membership number: none or "Katipo" style checks',
480             type                => 'Choice',
481             options             => 'none|katipo'
482         },
483         {
484             uniquefieldrequired => 'variable',
485             variable            => 'maxoutstanding',
486             forceupdate         => { 'explanation' => 1,
487                                      'type' => 1 },
488             value               => '5',
489             explanation         =>
490             'maximum amount withstanding to be able make reserves ',
491             type                => 'Integer'
492         },
493         {
494             uniquefieldrequired => 'variable',
495             variable            => 'maxreserves',
496             forceupdate         => { 'explanation' => 1,
497                                      'type' => 1 },
498             value               => '5',
499             explanation         =>
500             'maximum number of reserves a member can make',
501             type                => 'Integer'
502
503         },
504         {
505             uniquefieldrequired => 'variable',
506             variable            => 'noissuescharge',
507             forceupdate         => { 'explanation' => 1,
508                                      'type' => 1 },
509             value               => '5',
510             explanation         =>
511             'maximum amount withstanding to be able to check out an item',
512             type                => 'Integer'
513
514         },
515         {
516             uniquefieldrequired => 'variable',
517             variable            => 'KohaAdminEmailAddress',
518             forceupdate         => { 'explanation' => 1,
519                                      'type' => 1 },
520             value               => 'your.mail@here',
521             explanation => 'the email adress where borrowers modifs are sent',
522             type                => 'free'
523         },
524         {
525             uniquefieldrequired => 'variable',
526             variable            => 'gist',
527             forceupdate         => { 'explanation' => 1,
528                                      'type' => 1 },
529             value               => '0.125',
530             explanation => 'the gist rate. NOT in %, but in numeric form (0.12 for 12%)',
531             type                => 'free'
532         },
533     ],
534
535 );
536
537 my %fielddefinitions = (
538     printers => [
539         {
540             field   => 'printername',
541             type    => 'char(40)',
542             null    => '',
543             key     => 'PRI',
544             default => ''
545         },
546     ],
547     aqbookfund => [
548         {
549             field   => 'bookfundid',
550             type    => 'char(5)',
551             null    => '',
552             key     => 'PRI',
553             default => ''
554         },
555     ],
556     aqbudget => [
557         {
558             field   => 'aqbudgetid',
559             type    => 'tinyint(4)',
560             null    => '',
561             key     => 'PRI',
562                   default =>'',
563             extra => 'auto_increment'
564         },
565     ],
566     z3950servers => [
567         {
568             field   => 'id',
569             type    => 'int',
570             null    => '',
571             key     => 'PRI',
572             default => '',
573             extra   => 'auto_increment'
574         },
575     ],
576         marc_breeding => [
577         {
578             field   => 'z3950random',
579             type    => 'varchar(40)',
580             null    => '',
581             key     => '',
582             default => '',
583             extra   => ''
584         },
585         {
586             field   => 'encoding',
587             type    => 'varchar(40)',
588             null    => '',
589             key     => '',
590             default => '',
591             extra   => ''
592         },
593     ],
594 );
595
596 #-------------------
597 # Initialize
598
599 # Start checking
600
601 # Get version of MySQL database engine.
602 my $mysqlversion = `mysqld --version`;
603 $mysqlversion =~ /Ver (\S*) /;
604 $mysqlversion = $1;
605 if ( $mysqlversion ge '3.23' ) {
606     print "Could convert to MyISAM database tables...\n";
607 }
608
609 #---------------------------------
610 # Tables
611
612 # Collect all tables into a list
613 $sth = $dbh->prepare("show tables");
614 $sth->execute;
615 while ( my ($table) = $sth->fetchrow ) {
616     $existingtables{$table} = 1;
617 }
618
619 # Now add any missing tables
620 foreach $table ( keys %requiretables ) {
621     print "Checking $table table...\n" if $debug;
622     unless ( $existingtables{$table} ) {
623         print "Adding $table table...\n";
624         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
625         $sth->execute;
626         if ( $sth->err ) {
627             print "Error : $sth->errstr \n";
628             $sth->finish;
629         }    # if error
630     }    # unless exists
631 }    # foreach
632
633 # now drop useless tables
634 foreach $table ( keys %dropable_table ) {
635     print "Dropping unused tables...\n" if $debug;
636     if ( $existingtables{$table} ) {
637         $dbh->do("drop table $table");
638         if ( $dbh->err ) {
639             print "Error : $dbh->errstr \n";
640         }
641     }
642 }
643 unless ( $existingtables{'z3950servers'} ) {
644     print "Adding z3950servers table...\n";
645     my $sti = $dbh->prepare( "create table z3950servers (
646                                                                                 host char(255),
647                                                                                 port int,
648                                                                                 db char(255),
649                                                                                 userid char(255),
650                                                                                 password char(255),
651                                                                                 name text,
652                                                                                 id int,
653                                                                                 checked smallint,
654                                                                                 rank int)"
655     );
656     $sti->execute;
657     $sti = $dbh->prepare( "insert into z3950servers
658                                                                 values ('z3950.loc.gov',
659                                                                 7090,
660                                                                 'voyager',
661                                                                 '', '',
662                                                                 'Library of Congress',
663                                                                 1, 1, 1)"
664     );
665     $sti->execute;
666 }
667
668 #---------------------------------
669 # Columns
670
671 foreach $table ( keys %requirefields ) {
672     print "Check table $table\n" if $debug;
673     $sth = $dbh->prepare("show columns from $table");
674     $sth->execute();
675     undef %types;
676     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
677     {
678         $types{$column} = $type;
679     }    # while
680     foreach $column ( keys %{ $requirefields{$table} } ) {
681         print "  Check column $column  [$types{$column}]\n" if $debug;
682         if ( !$types{$column} ) {
683
684             # column doesn't exist
685             print "Adding $column field to $table table...\n";
686             $query = "alter table $table
687                         add column $column " . $requirefields{$table}->{$column};
688             print "Execute: $query\n" if $debug;
689             my $sti = $dbh->prepare($query);
690             $sti->execute;
691             if ( $sti->err ) {
692                 print "**Error : $sti->errstr \n";
693                 $sti->finish;
694             }    # if error
695         }    # if column
696     }    # foreach column
697 }    # foreach table
698
699 foreach $table ( keys %fielddefinitions ) {
700         print "Check table $table\n" if $debug;
701         $sth = $dbh->prepare("show columns from $table");
702         $sth->execute();
703         my $definitions;
704         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
705         {
706                 $definitions->{$column}->{type}    = $type;
707                 $definitions->{$column}->{null}    = $null;
708                 $definitions->{$column}->{key}     = $key;
709                 $definitions->{$column}->{default} = $default;
710                 $definitions->{$column}->{extra}   = $extra;
711         }    # while
712         my $fieldrow = $fielddefinitions{$table};
713         foreach my $row (@$fieldrow) {
714                 my $field   = $row->{field};
715                 my $type    = $row->{type};
716                 my $null    = $row->{null};
717                 my $key     = $row->{key};
718                 my $default = $row->{default};
719                 $default="''" unless $default;
720                 my $extra   = $row->{extra};
721                 my $def     = $definitions->{$field};
722                 unless ( $type eq $def->{type}
723                         && $null eq $def->{null}
724                         && $key eq $def->{key}
725                         && $default eq $def->{default}
726                         && $extra eq $def->{extra} )
727                 {
728
729                         if ( $null eq '' ) {
730                                 $null = 'NOT NULL';
731                         }
732                         if ( $key eq 'PRI' ) {
733                                 $key = 'PRIMARY KEY';
734                         }
735                         unless ( $extra eq 'auto_increment' ) {
736                                 $extra = '';
737                         }
738                         # if it's a new column use "add", if it's an old one, use "change".
739                         my $action;
740                         if ($definitions->{$field}->{type}) {
741                                 $action="change $field"
742                         } else {
743                                 $action="add";
744                         }
745 # if it's a primary key, drop the previous pk, before altering the table
746                         my $sth;
747                         if ($key ne 'PRIMARY KEY') {
748                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ?");
749                         } else {
750                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ?");
751                         }
752                         $sth->execute($default);
753                         print "  Alter $field in $table\n";
754                 }
755         }
756 }
757
758 # Get list of columns from items table
759 my %itemtypes;
760
761 $sth = $dbh->prepare("show columns from items");
762 $sth->execute;
763 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
764 {
765     $itemtypes{$column} = $type;
766 }
767
768 unless ( $itemtypes{'barcode'} eq 'varchar(20)' ) {
769     $itemtypes{'barcode'} =~ /varchar\((\d+)\)/;
770     my $oldlength = $1;
771     if ( $oldlength < 20 ) {
772         print "Setting maximum barcode length to 20 (was $oldlength).\n";
773         my $sti =
774           $dbh->prepare(
775             "alter table items change barcode barcode varchar(20) not null");
776         $sti->execute;
777     }
778 }
779
780 # extending the timestamp in branchtransfers...
781 my %branchtransfers;
782
783 $sth = $dbh->prepare("show columns from branchtransfers");
784 $sth->execute;
785 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
786 {
787     $branchtransfers{$column} = $type;
788 }
789
790 unless ( $branchtransfers{'datesent'} eq 'datetime' ) {
791     print "Setting type of datesent in branchtransfers to datetime.\n";
792     my $sti =
793       $dbh->prepare(
794         "alter table branchtransfers change datesent datesent datetime");
795     $sti->execute;
796 }
797
798 unless ( $branchtransfers{'datearrived'} eq 'datetime' ) {
799     print "Setting type of datearrived in branchtransfers to datetime.\n";
800     my $sti =
801       $dbh->prepare(
802         "alter table branchtransfers change datearrived datearrived datetime");
803     $sti->execute;
804 }
805
806 # changing the branchcategories table around...
807 my %branchcategories;
808
809 $sth = $dbh->prepare("show columns from branchcategories");
810 $sth->execute;
811 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
812 {
813     $branchcategories{$column} = $type;
814 }
815
816 unless ( $branchcategories{'categorycode'} eq 'varchar(4)' ) {
817     print
818 "Setting type of categorycode in branchcategories to varchar(4),\n and making the primary key.\n";
819     my $sti =
820       $dbh->prepare(
821 "alter table branchcategories change categorycode categorycode varchar(4) not null"
822     );
823     $sti->execute;
824     $sti =
825       $dbh->prepare(
826         "alter table branchcategories add primary key (categorycode)");
827     $sti->execute;
828 }
829
830 unless ( $branchcategories{'categoryname'} eq 'text' ) {
831     print "Changing branchcode in branchcategories to categoryname text.\n";
832     my $sth =
833       $dbh->prepare(
834         "alter table branchcategories change branchcode categoryname text");
835     $sth->execute;
836 }
837
838 unless ( $branchcategories{'codedescription'} eq 'text' ) {
839     print
840 "Replacing branchholding in branchcategories with codedescription text.\n";
841     my $sth =
842       $dbh->prepare(
843         "alter table branchcategories change branchholding codedescription text"
844     );
845     $sth->execute;
846 }
847
848 # Populate tables with required data
849
850 foreach my $table ( keys %tabledata ) {
851     print "Checking for data required in table $table...\n";
852     my $tablerows = $tabledata{$table};
853     foreach my $row (@$tablerows) {
854         my $uniquefieldrequired = $row->{uniquefieldrequired};
855         my $uniquevalue         = $row->{$uniquefieldrequired};
856         my $forceupdate         = $row->{forceupdate};
857         my $sth                 =
858           $dbh->prepare(
859 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
860         );
861         $sth->execute($uniquevalue);
862         if ($sth->rows) {
863             foreach my $field (keys %$forceupdate) {
864                 if ($forceupdate->{$field}) {
865                     my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
866                     $sth->execute($row->{$field}, $uniquevalue);
867                 }
868             }
869         } else {
870             print "Adding row to $table: ";
871             my @values;
872             my $fieldlist;
873             my $placeholders;
874             foreach my $field ( keys %$row ) {
875                 next if $field eq 'uniquefieldrequired';
876                 next if $field eq 'forceupdate';
877                 my $value = $row->{$field};
878                 push @values, $value;
879                 print "  $field => $value";
880                 $fieldlist .= "$field,";
881                 $placeholders .= "?,";
882             }
883             print "\n";
884             $fieldlist    =~ s/,$//;
885             $placeholders =~ s/,$//;
886             my $sth =
887               $dbh->prepare(
888                 "insert into $table ($fieldlist) values ($placeholders)");
889             $sth->execute(@values);
890         }
891     }
892 }
893
894 $sth->finish;
895
896 exit;
897
898 # $Log$
899 # Revision 1.57  2003/07/11 11:50:29  tipaul
900 # fixing a bug that occured when adding a field into a table.
901 #
902 # Revision 1.56  2003/07/07 15:37:20  tipaul
903 # *** empty log message ***
904 #
905 # Revision 1.53  2003/07/07 14:11:16  tipaul
906 # fixing bug #526 : gst rate is now calculated through systempref gist entry.
907 # Before this fix :
908 # * was harcoded to 12,5%
909 # * some bugs in template parameters prevented the javascript to work.
910 # * some bugs prevented some calculations to be done properly.
911 #
912 # Revision 1.52  2003/06/23 15:54:32  tipaul
913 # *** empty log message ***
914 #
915 # Revision 1.51  2003/06/23 11:27:29  tipaul
916 # *** empty log message ***
917 #
918 # Revision 1.50  2003/06/11 21:28:22  tonnesen
919 # Added modifications required to the systempreferences table by the new
920 # systempreferences.pl script.  The systempreferences.pl script will not work
921 # properly until this table is updated.
922 #
923 # Revision 1.49  2003/05/26 10:41:53  tipaul
924 # bugfix : borrowers modifs overwritten by stupid hash entry existing twice.
925 #
926 # Revision 1.48  2003/05/20 19:50:45  slef
927 # Initial fix to bug 456: hardwired paths
928 #
929 # Revision 1.47  2003/05/15 12:23:33  tipaul
930 # adding zipcode and homezipcode into borrowers table (bug #246
931 #
932 # Revision 1.46  2003/05/08 12:48:24  wolfpac444
933 # Added "noissuescharge" parameter
934 #
935 # Revision 1.45  2003/05/08 12:26:16  wolfpac444
936 # Bug fixes
937 #
938 # Revision 1.44  2003/05/03 05:39:57  rangi
939 # Fixing bug 429
940 # (Wording changes in the explanation fields in system preferences)
941 #
942 # Revision 1.43  2003/05/02 23:01:09  rangi
943 # Adding the textmessaging column to the borrowers table.
944 # insertdata.pl is expecting this to exist, and hence modifying/adding
945 # borrowers was broken.
946 #
947 # Also ran they script thru perltidy
948 #
949 # Revision 1.42  2003/04/29 16:53:25  tipaul
950 # really proud of this commit :-)
951 # z3950 search and import seems to works fine.
952 # Let me explain how :
953 # * a "search z3950" button is added in the addbiblio template.
954 # * when clicked, a popup appears and z3950/search.pl is called
955 # * z3950/search.pl calls addz3950search in the DB
956 # * the z3950 daemon retrieve the records and stores them in z3950results AND in marc_breeding table.
957 # * as long as there as searches pending, the popup auto refresh every 2 seconds, and says how many searches are pending.
958 # * when the user clicks on a z3950 result => the parent popup is called with the requested biblio, and auto-filled
959 #
960 # Note :
961 # * character encoding support : (It's a nightmare...) In the z3950servers table, a "encoding" column has been added. You can put "UNIMARC" or "USMARC" in this column. Depending on this, the char_decode in C4::Biblio.pm replaces marc-char-encode by an iso 8859-1 encoding. Note that in the breeding import this value has been added too, for a better support.
962 # * the marc_breeding and z3950* tables have been modified : they have an encoding column and the random z3950 number is stored too for convenience => it's the key I use to list only requested biblios in the popup.
963 #
964 # Revision 1.41  2003/04/29 08:09:44  tipaul
965 # z3950 support is coming...
966 # * adding a syntax column in z3950 table = this column will say wether the z3950 must be called with PerferedRecordsyntax => USMARC or PerferedRecordsyntax => UNIMARC. I tried some french UNIMARC z3950 servers, and some only send USMARC, some only UNIMARC, some can answer with both.
967 # Note this is a 1st draft. More to follow (today ? I hope).
968 #
969 # Revision 1.40  2003/04/22 10:48:27  wolfpac444
970 # Added "father" column to bibliothesaurus table
971 #
972 # Revision 1.39  2003/04/04 08:45:00  tipaul
973 # last commits before 1.9.1
974 #
975 # Revision 1.38  2003/03/18 10:58:19  tipaul
976 # adding checkdigit parameter that choose how to check the members cardnumber.
977 # At the moment :
978 # * none = no checking
979 # * katipo = checked as before
980 #
981 # Revision 1.37  2003/01/30 01:47:48  acli
982 # Corrected syntax error reported by Benedict
983 #
984 # Made the indentation somewhat easier to read; the messiness probably caused
985 # the original syntax error.
986 #
987 # Revision 1.36  2003/01/28 15:13:30  tipaul
988 # userflag table now created in upgrade script (bugfix #171)
989 #
990 # Revision 1.35  2003/01/27 03:12:49  acli
991 # Reworded the description for "acquisitions" to make it fit on the screen
992 #
993 # Added "iso" to dateformat, since dateformat is not yet being used anyway
994 #
995 # Revision 1.34  2003/01/23 12:30:02  tipaul
996 # introducint marcflavour in systempref file : used for character decoding
997 #
998 # Revision 1.33  2003/01/21 09:03:27  tipaul
999 # bugfix (NOTE : this bugs makes installation of the 1.3.3 a little fuzzy. Please fix your DB if you installed 1.3.3)
1000 #
1001 # Revision 1.32  2003/01/16 10:29:45  tipaul
1002 # adding a MARC parameter in systempref ( which is ON or OFF)
1003 # the search will be a marc search if MARC=ON
1004 # and a standard (v1.2) search if MARC=OFF
1005 #
1006 # Revision 1.31  2003/01/06 13:32:43  tipaul
1007 # *** empty log message ***
1008 #
1009 # Revision 1.29  2003/01/06 11:14:11  tipaul
1010 # last bugfixes before 1.3.3 : systempref table correctly filled
1011 #
1012 # Revision 1.28  2002/12/10 13:27:47  tipaul
1013 # bugfixes (davide mails in koha-dev)
1014 #
1015 # Revision 1.27  2002/11/26 15:04:54  tipaul
1016 # road to 1.3.2. Updating db structure during installation
1017 #
1018 # Revision 1.26  2002/11/12 17:42:40  tonnesen
1019 # Merged some features over from rel-1-2, including primary key checking.
1020 #
1021 # Revision 1.25  2002/11/12 16:44:38  tipaul
1022 # road to 1.3.2 :
1023 # * many bugfixes
1024 # * adding value_builder : you can map a subfield in the marc_subfield_structure to a sub stored in "value_builder" directory. In this directory you can create screen used to build values with any method. In this commit is a 1st draft of the builder for 100$a unimarc french subfield, which is composed of 35 digits, with 12 differents values (only the 4th first are provided for instance)
1025 #
1026 # Revision 1.24  2002/10/30 14:00:23  arensb
1027 # (bug fix): Fixed typo.
1028 #
1029 # Revision 1.23  2002/10/25 10:55:46  tipaul
1030 # Road to 1.3.2
1031 # * bugfixes and improvements
1032 # * manage mandatory MARC subfields
1033 # * new table : authorised_values. this table contains categories and authorised values for the category. On MARC management, you can map a subfield to a authorised_values category. If you do this, the subfield can only be filled with a authorised_value of the selected category.
1034 # this submit contains everything needed :
1035 # * updatedatabase
1036 # * admin screens
1037 # * "links" management
1038 # * creation of a html-list if a subfield is mapped to an authorised value.
1039 #
1040 # Note this is different from authorities support, which will come soon.
1041 # The authorised_values is supposed to contains a "small" number of authorised values for a category (less than 50-100). If you enter more authorised values than this, it should be hard to find what you want in a BIG list...
1042 #
1043 # Revision 1.22  2002/10/15 10:08:19  tipaul
1044 # fixme corrected, re-indent and adding the marc_breeding table (see commit of marcimport.pl for more explanations about breeding)
1045 #
1046 # Revision 1.21  2002/10/14 11:48:59  tipaul
1047 # bugfix
1048 #
1049 # Revision 1.20  2002/10/10 04:49:41  arensb
1050 # Added some FIXME comments.
1051 #
1052 # Revision 1.19  2002/10/05 10:17:17  arensb
1053 # Merged with arensb-context branch: use C4::Context->dbh instead of
1054 # &C4Connect, and generally prefer C4::Context over C4::Database.
1055 #
1056 # Revision 1.18.2.2  2002/10/05 06:18:43  arensb
1057 # Added a whole mess of FIXME comments.
1058 #
1059 # Revision 1.18.2.1  2002/10/04 02:46:00  arensb
1060 # Use C4::Connect instead of C4::Database, C4::Connect->dbh instead
1061 # C4Connect.
1062 #
1063 # Revision 1.18  2002/09/24 13:50:55  tipaul
1064 # long WAS the road to 1.3.0...
1065 # coming VERY SOON NOW...
1066 # modifying installer and buildrelease to update the DB
1067 #
1068 # Revision 1.17  2002/09/24 12:57:35  tipaul
1069 # long WAS the road to 1.3.0...
1070 # coming VERY SOON NOW...
1071 # modifying installer and buildrelease to update the DB
1072 #
1073 # Revision 1.16  2002/07/31 02:34:27  finlayt
1074 #
1075 # added "notforloan" field to the itemtypes table.
1076 #
1077 # Revision 1.15  2002/07/20 22:30:06  rangi
1078 # Making sure fix makes it into the main branch as well
1079 # Fix for bug 69
1080 #
1081 # Revision 1.14  2002/07/08 16:20:26  tonnesen
1082 # Added sessionqueries table and password/userid fields to borrowers table
1083 #
1084 # Revision 1.13  2002/07/04 18:05:36  tonnesen
1085 # bug fix
1086 #
1087 # Revision 1.12  2002/07/04 16:41:06  tonnesen
1088 # Merged changes from rel-1-2.  Abstracted table structure changes by alan.
1089 #