Omitted annotation added. Closes: 624
[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 other hash contains other actions that can't be done elsewhere. they are done
262 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
263
264 # The tabledata hash contains data that should be in the tables.
265 # The uniquefieldrequired hash entry is used to determine which (if any) fields
266 # must not exist in the table for this row to be inserted.  If the
267 # uniquefieldrequired entry is already in the table, the existing data is not
268 # modified, unless the forceupdate hash entry is also set.  Fields in the
269 # anonymous "forceupdate" hash will be forced to be updated to the default
270 # values given in the %tabledata hash.
271
272 my %tabledata = (
273     userflags => [
274         {
275             uniquefieldrequired => 'bit',
276             bit                 => 0,
277             flag                => 'superlibrarian',
278             flagdesc            => 'Access to all librarian functions',
279             defaulton           => 0
280         },
281         {
282             uniquefieldrequired => 'bit',
283             bit                 => 1,
284             flag                => 'circulate',
285             flagdesc            => 'Circulate books',
286             defaulton           => 0
287         },
288         {
289             uniquefieldrequired => 'bit',
290             bit                 => 2,
291             flag                => 'catalogue',
292             flagdesc            => 'View Catalogue (Librarian Interface)',
293             defaulton           => 0
294         },
295         {
296             uniquefieldrequired => 'bit',
297             bit                 => 3,
298             flag                => 'parameters',
299             flagdesc            => 'Set Koha system paramters',
300             defaulton           => 0
301         },
302         {
303             uniquefieldrequired => 'bit',
304             bit                 => 4,
305             flag                => 'borrowers',
306             flagdesc            => 'Add or modify borrowers',
307             defaulton           => 0
308         },
309         {
310             uniquefieldrequired => 'bit',
311             bit                 => 5,
312             flag                => 'permissions',
313             flagdesc            => 'Set user permissions',
314             defaulton           => 0
315         },
316         {
317             uniquefieldrequired => 'bit',
318             bit                 => 6,
319             flag                => 'reserveforothers',
320             flagdesc            => 'Reserve books for patrons',
321             defaulton           => 0
322         },
323         {
324             uniquefieldrequired => 'bit',
325             bit                 => 7,
326             flag                => 'borrow',
327             flagdesc            => 'Borrow books',
328             defaulton           => 1
329         },
330         {
331             uniquefieldrequired => 'bit',
332             bit                 => 8,
333             flag                => 'reserveforself',
334             flagdesc            => 'Reserve books for self',
335             defaulton           => 0
336         },
337         {
338             uniquefieldrequired => 'bit',
339             bit                 => 9,
340             flag                => 'editcatalogue',
341             flagdesc  => 'Edit Catalogue (Modify bibliographic/holdings data)',
342             defaulton => 0
343         },
344         {
345             uniquefieldrequired => 'bit',
346             bit                 => 10,
347             flag                => 'updatecharges',
348             flagdesc            => 'Update borrower charges',
349             defaulton           => 0
350         },
351     ],
352     systempreferences => [
353         {
354             uniquefieldrequired => 'variable',
355             forceupdate         => { 'explanation' => 1,
356                                      'type' => 1 },
357             variable            => 'autoMemberNum',
358             value               => '1',
359             explanation         => 'Member number is auto-calculated',
360             type                => 'YesNo'
361
362         },
363         {
364             uniquefieldrequired => 'variable',
365             forceupdate         => { 'explanation' => 1,
366                                      'type' => 1,
367                                      'options' => 1 },
368             variable            => 'acquisitions',
369             value               => 'simple',
370             explanation         =>
371 'Normal, budget-based acquisitions, or Simple bibliographic-data acquisitions',
372             type                => 'Choice',
373             options             => 'simple|normal'
374         },
375         {
376             uniquefieldrequired => 'variable',
377             forceupdate         => { 'explanation' => 1,
378                                      'type' => 1,
379                                      'options' => 1 },
380             variable            => 'dateformat',
381             value               => 'metric',
382             explanation         =>
383             'date format (US mm/dd/yyyy, metric dd/mm/yyy, ISO yyyy/mm/dd)',
384             type                => 'Choice',
385             options             => 'metric|us|iso'
386         },
387         {
388             uniquefieldrequired => 'variable',
389             variable            => 'template',
390             forceupdate         => { 'explanation' => 1,
391                                      'type' => 1 },
392             value               => 'default',
393             explanation         => 'Preference order for intranet interface templates',
394             type                => 'Themes'
395         },
396         {
397             uniquefieldrequired => 'variable',
398             variable            => 'autoBarcode',
399             forceupdate         => { 'explanation' => 1,
400                                      'type' => 1 },
401             value               => 'yes',
402             explanation         => 'Barcode is auto-calculated',
403             type                => 'YesNo'
404         },
405         {
406             uniquefieldrequired => 'variable',
407             variable            => 'insecure',
408             forceupdate         => { 'explanation' => 1,
409                                      'type' => 1 },
410             value               => 'no',
411             explanation         =>
412 'If YES, no auth at all is needed. Be careful if you set this to yes!',
413             type                => 'YesNo'
414         },
415         {
416             uniquefieldrequired => 'variable',
417             variable            => 'authoritysep',
418             forceupdate         => { 'explanation' => 1,
419                                      'type' => 1,
420                                      'options' => 1 },
421             value               => '--',
422             explanation         =>
423             'the separator used in authority/thesaurus. Usually --',
424             type                => 'free',
425             options             => '10'
426         },
427         {
428             uniquefieldrequired => 'variable',
429             variable            => 'opaclanguages',
430             forceupdate         => { 'explanation' => 1,
431                                      'type' => 1 },
432             value               => 'en',
433             explanation         => 'Set the preferred order for translations.  The top language will be tried first.',
434             type                => 'Languages'
435         },
436         {
437             uniquefieldrequired => 'variable',
438             variable            => 'opacthemes',
439             forceupdate         => { 'explanation' => 1,
440                                      'type' => 1 },
441             value               => 'default',
442             explanation         => 'Set the preferred order for themes.  The top theme will be tried first.',
443             type                => 'Themes'
444         },
445         {
446             uniquefieldrequired => 'variable',
447             variable            => 'timeout',
448             forceupdate         => { 'explanation' => 1,
449                                      'type' => 1 },
450             value               => '1200',
451             explanation         => 'Inactivity timeout for cookies authentication (in seconds)',
452             type                => 'Integer'
453         },
454         {
455             uniquefieldrequired => 'variable',
456             variable            => 'marc',
457             forceupdate         => { 'explanation' => 1,
458                                      'type' => 1 },
459             value               => 'yes',
460             explanation         => 'Turn on MARC support',
461             type                => 'YesNo'
462         },
463         {
464             uniquefieldrequired => 'variable',
465             variable            => 'marcflavour',
466             forceupdate         => { 'explanation' => 1,
467                                      'type' => 1,
468                                      'options' => 1},
469             value               => 'MARC21',
470             explanation         =>
471             'your MARC flavor (MARC21 or UNIMARC) used for character encoding',
472             type                => 'Choice',
473             options             => 'MARC21|UNIMARC'
474         },
475         {
476             uniquefieldrequired => 'variable',
477             variable            => 'checkdigit',
478             value               => 'none',
479             forceupdate         => { 'explanation' => 1,
480                                      'type' => 1,
481                                      'options' => 1},
482             explanation         => 'Validity checks on membership number: none or "Katipo" style checks',
483             type                => 'Choice',
484             options             => 'none|katipo'
485         },
486         {
487             uniquefieldrequired => 'variable',
488             variable            => 'maxoutstanding',
489             forceupdate         => { 'explanation' => 1,
490                                      'type' => 1 },
491             value               => '5',
492             explanation         =>
493             'maximum amount withstanding to be able make reserves ',
494             type                => 'Integer'
495         },
496         {
497             uniquefieldrequired => 'variable',
498             variable            => 'maxreserves',
499             forceupdate         => { 'explanation' => 1,
500                                      'type' => 1 },
501             value               => '5',
502             explanation         =>
503             'maximum number of reserves a member can make',
504             type                => 'Integer'
505
506         },
507         {
508             uniquefieldrequired => 'variable',
509             variable            => 'noissuescharge',
510             forceupdate         => { 'explanation' => 1,
511                                      'type' => 1 },
512             value               => '5',
513             explanation         =>
514             'maximum amount withstanding to be able to check out an item',
515             type                => 'Integer'
516
517         },
518         {
519             uniquefieldrequired => 'variable',
520             variable            => 'KohaAdminEmailAddress',
521             forceupdate         => { 'explanation' => 1,
522                                      'type' => 1 },
523             value               => 'your.mail@here',
524             explanation => 'the email address where borrowers modifs are sent',
525             type                => 'free'
526         },
527         {
528             uniquefieldrequired => 'variable',
529             variable            => 'gist',
530             forceupdate         => { 'explanation' => 1,
531                                      'type' => 1 },
532             value               => '0.125',
533             explanation => 'the gist rate. NOT in %, but in numeric form (0.12 for 12%)',
534             type                => 'free'
535         },
536     ],
537
538 );
539
540 my %fielddefinitions = (
541     printers => [
542         {
543             field   => 'printername',
544             type    => 'char(40)',
545             null    => '',
546             key     => 'PRI',
547             default => ''
548         },
549     ],
550     aqbookfund => [
551         {
552             field   => 'bookfundid',
553             type    => 'char(5)',
554             null    => '',
555             key     => 'PRI',
556             default => ''
557         },
558     ],
559     aqbudget => [
560         {
561             field   => 'aqbudgetid',
562             type    => 'tinyint(4)',
563             null    => '',
564             key     => 'PRI',
565                   default =>'',
566             extra => 'auto_increment'
567         },
568     ],
569     z3950servers => [
570         {
571             field   => 'id',
572             type    => 'int',
573             null    => '',
574             key     => 'PRI',
575             default => '',
576             extra   => 'auto_increment'
577         },
578     ],
579         marc_breeding => [
580         {
581             field   => 'z3950random',
582             type    => 'varchar(40)',
583             null    => 'NULL',
584             key     => '',
585             default => '',
586             extra   => ''
587         },
588         {
589             field   => 'encoding',
590             type    => 'varchar(40)',
591             null    => '',
592             key     => '',
593             default => '',
594             extra   => ''
595         },
596     ],
597 );
598
599 #-------------------
600 # Initialize
601
602 # Start checking
603
604 # Get version of MySQL database engine.
605 my $mysqlversion = `mysqld --version`;
606 $mysqlversion =~ /Ver (\S*) /;
607 $mysqlversion = $1;
608 if ( $mysqlversion ge '3.23' ) {
609     print "Could convert to MyISAM database tables...\n";
610 }
611
612 #---------------------------------
613 # Tables
614
615 # Collect all tables into a list
616 $sth = $dbh->prepare("show tables");
617 $sth->execute;
618 while ( my ($table) = $sth->fetchrow ) {
619     $existingtables{$table} = 1;
620 }
621
622
623 # Now add any missing tables
624 foreach $table ( keys %requiretables ) {
625     print "Checking $table table...\n" if $debug;
626     unless ( $existingtables{$table} ) {
627         print "Adding $table table...\n";
628         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
629         $sth->execute;
630         if ( $sth->err ) {
631             print "Error : $sth->errstr \n";
632             $sth->finish;
633         }    # if error
634     }    # unless exists
635 }    # foreach
636
637 # now drop useless tables
638 foreach $table ( keys %dropable_table ) {
639     print "Dropping unused tables...\n" if $debug;
640     if ( $existingtables{$table} ) {
641         $dbh->do("drop table $table");
642         if ( $dbh->err ) {
643             print "Error : $dbh->errstr \n";
644         }
645     }
646 }
647 unless ( $existingtables{'z3950servers'} ) {
648         #MJR: added syntax entries to close bug 624
649     print "Adding z3950servers table...\n";
650     my $sti = $dbh->prepare( "create table z3950servers (
651                                                                                 host char(255),
652                                                                                 port int,
653                                                                                 db char(255),
654                                                                                 userid char(255),
655                                                                                 password char(255),
656                                                                                 name text,
657                                                                                 id int,
658                                                                                 checked smallint,
659                                                                                 rank int,
660                                                                                 syntax char(80))"
661     );
662     $sti->execute;
663     $sti = $dbh->prepare( "insert into z3950servers
664                                                                 values ('z3950.loc.gov',
665                                                                 7090,
666                                                                 'voyager',
667                                                                 '', '',
668                                                                 'Library of Congress',
669                                                                 1, 1, 1, 'USMARC')"
670     );
671     $sti->execute;
672 }
673
674 #---------------------------------
675 # Columns
676
677 foreach $table ( keys %requirefields ) {
678     print "Check table $table\n" if $debug;
679     $sth = $dbh->prepare("show columns from $table");
680     $sth->execute();
681     undef %types;
682     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
683     {
684         $types{$column} = $type;
685     }    # while
686     foreach $column ( keys %{ $requirefields{$table} } ) {
687         print "  Check column $column  [$types{$column}]\n" if $debug;
688         if ( !$types{$column} ) {
689
690             # column doesn't exist
691             print "Adding $column field to $table table...\n";
692             $query = "alter table $table
693                         add column $column " . $requirefields{$table}->{$column};
694             print "Execute: $query\n" if $debug;
695             my $sti = $dbh->prepare($query);
696             $sti->execute;
697             if ( $sti->err ) {
698                 print "**Error : $sti->errstr \n";
699                 $sti->finish;
700             }    # if error
701         }    # if column
702     }    # foreach column
703 }    # foreach table
704
705 foreach $table ( keys %fielddefinitions ) {
706         print "Check table $table\n" if $debug;
707         $sth = $dbh->prepare("show columns from $table");
708         $sth->execute();
709         my $definitions;
710         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
711         {
712                 $definitions->{$column}->{type}    = $type;
713                 $definitions->{$column}->{null}    = $null;
714                 $definitions->{$column}->{key}     = $key;
715                 $definitions->{$column}->{default} = $default;
716                 $definitions->{$column}->{extra}   = $extra;
717         }    # while
718         my $fieldrow = $fielddefinitions{$table};
719         foreach my $row (@$fieldrow) {
720                 my $field   = $row->{field};
721                 my $type    = $row->{type};
722                 my $null    = $row->{null};
723                 my $key     = $row->{key};
724                 my $default = $row->{default};
725                 $default="''" unless $default;
726                 my $extra   = $row->{extra};
727                 my $def     = $definitions->{$field};
728                 unless ( $type eq $def->{type}
729                         && $null eq $def->{null}
730                         && $key eq $def->{key}
731                         && $default eq $def->{default}
732                         && $extra eq $def->{extra} )
733                 {
734
735                         if ( $null eq '' ) {
736                                 $null = 'NOT NULL';
737                         }
738                         if ( $key eq 'PRI' ) {
739                                 $key = 'PRIMARY KEY';
740                         }
741                         unless ( $extra eq 'auto_increment' ) {
742                                 $extra = '';
743                         }
744                         # if it's a new column use "add", if it's an old one, use "change".
745                         my $action;
746                         if ($definitions->{$field}->{type}) {
747                                 $action="change $field"
748                         } else {
749                                 $action="add";
750                         }
751 # if it's a primary key, drop the previous pk, before altering the table
752                         my $sth;
753                         if ($key ne 'PRIMARY KEY') {
754                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ?");
755                         } else {
756                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ?");
757                         }
758                         $sth->execute($default);
759                         print "  Alter $field in $table\n";
760                 }
761         }
762 }
763
764 # Get list of columns from items table
765 my %itemtypes;
766 my %nullenabled;
767 $sth = $dbh->prepare("show columns from items");
768 $sth->execute;
769 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
770 {
771     $itemtypes{$column} = $type;
772     $nullenabled{$column} = $null;
773 }
774
775 unless ( $itemtypes{'barcode'} eq 'varchar(20)' ) {
776     $itemtypes{'barcode'} =~ /varchar\((\d+)\)/;
777     my $oldlength = $1;
778     if ( $oldlength < 20 ) {
779         print "Setting maximum barcode length to 20 (was $oldlength).\n";
780         my $sti =
781           $dbh->prepare(
782             "alter table items change barcode barcode varchar(20)");
783         $sti->execute;
784     }
785 }
786 #
787 # dropping unique barcode index & setting barcode to null allowed.
788 #
789 $sth = $dbh->prepare("show index from items");
790 $sth->execute;
791 while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow )
792 {
793         if ($key_name eq 'barcode' && $non_unique eq 0) {
794                 print "dropping BARCODE index to enable empty barcodes\n";
795                 $dbh->do("ALTER TABLE `items` DROP INDEX `barcode`");
796         }
797 }
798 $dbh->do("ALTER TABLE `items` CHANGE `barcode` `barcode` VARCHAR( 20 )") unless ($nullenabled{barcode} eq 'YES');
799
800 # changing z3950daemon field to NULL in marc_breeding
801 $dbh->do("ALTER TABLE `marc_breeding` CHANGE `z3950random` `z3950random` VARCHAR( 40 )");
802
803 # extending the timestamp in branchtransfers...
804 my %branchtransfers;
805
806 $sth = $dbh->prepare("show columns from branchtransfers");
807 $sth->execute;
808 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
809 {
810     $branchtransfers{$column} = $type;
811 }
812
813 unless ( $branchtransfers{'datesent'} eq 'datetime' ) {
814     print "Setting type of datesent in branchtransfers to datetime.\n";
815     my $sti =
816       $dbh->prepare(
817         "alter table branchtransfers change datesent datesent datetime");
818     $sti->execute;
819 }
820
821 unless ( $branchtransfers{'datearrived'} eq 'datetime' ) {
822     print "Setting type of datearrived in branchtransfers to datetime.\n";
823     my $sti =
824       $dbh->prepare(
825         "alter table branchtransfers change datearrived datearrived datetime");
826     $sti->execute;
827 }
828
829 # changing the branchcategories table around...
830 my %branchcategories;
831
832 $sth = $dbh->prepare("show columns from branchcategories");
833 $sth->execute;
834 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
835 {
836     $branchcategories{$column} = $type;
837 }
838
839 unless ( $branchcategories{'categorycode'} eq 'varchar(4)' ) {
840     print
841 "Setting type of categorycode in branchcategories to varchar(4),\n and making the primary key.\n";
842     my $sti =
843       $dbh->prepare(
844 "alter table branchcategories change categorycode categorycode varchar(4) not null"
845     );
846     $sti->execute;
847     $sti =
848       $dbh->prepare(
849         "alter table branchcategories add primary key (categorycode)");
850     $sti->execute;
851 }
852
853 unless ( $branchcategories{'categoryname'} eq 'text' ) {
854     print "Changing branchcode in branchcategories to categoryname text.\n";
855     my $sth =
856       $dbh->prepare(
857         "alter table branchcategories change branchcode categoryname text");
858     $sth->execute;
859 }
860
861 unless ( $branchcategories{'codedescription'} eq 'text' ) {
862     print
863 "Replacing branchholding in branchcategories with codedescription text.\n";
864     my $sth =
865       $dbh->prepare(
866         "alter table branchcategories change branchholding codedescription text"
867     );
868     $sth->execute;
869 }
870
871 # Populate tables with required data
872
873 foreach my $table ( keys %tabledata ) {
874     print "Checking for data required in table $table...\n";
875     my $tablerows = $tabledata{$table};
876     foreach my $row (@$tablerows) {
877         my $uniquefieldrequired = $row->{uniquefieldrequired};
878         my $uniquevalue         = $row->{$uniquefieldrequired};
879         my $forceupdate         = $row->{forceupdate};
880         my $sth                 =
881           $dbh->prepare(
882 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
883         );
884         $sth->execute($uniquevalue);
885         if ($sth->rows) {
886             foreach my $field (keys %$forceupdate) {
887                 if ($forceupdate->{$field}) {
888                     my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
889                     $sth->execute($row->{$field}, $uniquevalue);
890                 }
891             }
892         } else {
893             print "Adding row to $table: ";
894             my @values;
895             my $fieldlist;
896             my $placeholders;
897             foreach my $field ( keys %$row ) {
898                 next if $field eq 'uniquefieldrequired';
899                 next if $field eq 'forceupdate';
900                 my $value = $row->{$field};
901                 push @values, $value;
902                 print "  $field => $value";
903                 $fieldlist .= "$field,";
904                 $placeholders .= "?,";
905             }
906             print "\n";
907             $fieldlist    =~ s/,$//;
908             $placeholders =~ s/,$//;
909             my $sth =
910               $dbh->prepare(
911                 "insert into $table ($fieldlist) values ($placeholders)");
912             $sth->execute(@values);
913         }
914     }
915 }
916
917 $sth->finish;
918
919 exit;
920
921 # $Log$
922 # Revision 1.63  2003/10/20 16:13:01  slef
923 # Omitted annotation added. Closes: 624
924 #
925 # Revision 1.62  2003/10/20 16:10:19  slef
926 # Adding USMARC to LOC z3950 entry
927 #
928 # Revision 1.61  2003/10/01 15:03:45  tipaul
929 # oups... typo fix in z3950random field definition
930 #
931 # Revision 1.59  2003/09/30 16:22:05  tipaul
932 # adding barcode NOT mandatory feature. Just run updatedatabase to get it.
933 # Note it's impossible to issue an item without barcode, as issue/returns is based on barcode...
934 #
935 # Revision 1.58  2003/07/16 04:08:29  acli
936 # Minor spelling correction
937 #
938 # Revision 1.57  2003/07/11 11:50:29  tipaul
939 # fixing a bug that occured when adding a field into a table.
940 #
941 # Revision 1.56  2003/07/07 15:37:20  tipaul
942 # *** empty log message ***
943 #
944 # Revision 1.53  2003/07/07 14:11:16  tipaul
945 # fixing bug #526 : gst rate is now calculated through systempref gist entry.
946 # Before this fix :
947 # * was harcoded to 12,5%
948 # * some bugs in template parameters prevented the javascript to work.
949 # * some bugs prevented some calculations to be done properly.
950 #
951 # Revision 1.52  2003/06/23 15:54:32  tipaul
952 # *** empty log message ***
953 #
954 # Revision 1.51  2003/06/23 11:27:29  tipaul
955 # *** empty log message ***
956 #
957 # Revision 1.50  2003/06/11 21:28:22  tonnesen
958 # Added modifications required to the systempreferences table by the new
959 # systempreferences.pl script.  The systempreferences.pl script will not work
960 # properly until this table is updated.
961 #
962 # Revision 1.49  2003/05/26 10:41:53  tipaul
963 # bugfix : borrowers modifs overwritten by stupid hash entry existing twice.
964 #
965 # Revision 1.48  2003/05/20 19:50:45  slef
966 # Initial fix to bug 456: hardwired paths
967 #
968 # Revision 1.47  2003/05/15 12:23:33  tipaul
969 # adding zipcode and homezipcode into borrowers table (bug #246
970 #
971 # Revision 1.46  2003/05/08 12:48:24  wolfpac444
972 # Added "noissuescharge" parameter
973 #
974 # Revision 1.45  2003/05/08 12:26:16  wolfpac444
975 # Bug fixes
976 #
977 # Revision 1.44  2003/05/03 05:39:57  rangi
978 # Fixing bug 429
979 # (Wording changes in the explanation fields in system preferences)
980 #
981 # Revision 1.43  2003/05/02 23:01:09  rangi
982 # Adding the textmessaging column to the borrowers table.
983 # insertdata.pl is expecting this to exist, and hence modifying/adding
984 # borrowers was broken.
985 #
986 # Also ran they script thru perltidy
987 #
988 # Revision 1.42  2003/04/29 16:53:25  tipaul
989 # really proud of this commit :-)
990 # z3950 search and import seems to works fine.
991 # Let me explain how :
992 # * a "search z3950" button is added in the addbiblio template.
993 # * when clicked, a popup appears and z3950/search.pl is called
994 # * z3950/search.pl calls addz3950search in the DB
995 # * the z3950 daemon retrieve the records and stores them in z3950results AND in marc_breeding table.
996 # * as long as there as searches pending, the popup auto refresh every 2 seconds, and says how many searches are pending.
997 # * when the user clicks on a z3950 result => the parent popup is called with the requested biblio, and auto-filled
998 #
999 # Note :
1000 # * 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.
1001 # * 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.
1002 #
1003 # Revision 1.41  2003/04/29 08:09:44  tipaul
1004 # z3950 support is coming...
1005 # * 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.
1006 # Note this is a 1st draft. More to follow (today ? I hope).
1007 #
1008 # Revision 1.40  2003/04/22 10:48:27  wolfpac444
1009 # Added "father" column to bibliothesaurus table
1010 #
1011 # Revision 1.39  2003/04/04 08:45:00  tipaul
1012 # last commits before 1.9.1
1013 #
1014 # Revision 1.38  2003/03/18 10:58:19  tipaul
1015 # adding checkdigit parameter that choose how to check the members cardnumber.
1016 # At the moment :
1017 # * none = no checking
1018 # * katipo = checked as before
1019 #
1020 # Revision 1.37  2003/01/30 01:47:48  acli
1021 # Corrected syntax error reported by Benedict
1022 #
1023 # Made the indentation somewhat easier to read; the messiness probably caused
1024 # the original syntax error.
1025 #
1026 # Revision 1.36  2003/01/28 15:13:30  tipaul
1027 # userflag table now created in upgrade script (bugfix #171)
1028 #
1029 # Revision 1.35  2003/01/27 03:12:49  acli
1030 # Reworded the description for "acquisitions" to make it fit on the screen
1031 #
1032 # Added "iso" to dateformat, since dateformat is not yet being used anyway
1033 #
1034 # Revision 1.34  2003/01/23 12:30:02  tipaul
1035 # introducint marcflavour in systempref file : used for character decoding
1036 #
1037 # Revision 1.33  2003/01/21 09:03:27  tipaul
1038 # bugfix (NOTE : this bugs makes installation of the 1.3.3 a little fuzzy. Please fix your DB if you installed 1.3.3)
1039 #
1040 # Revision 1.32  2003/01/16 10:29:45  tipaul
1041 # adding a MARC parameter in systempref ( which is ON or OFF)
1042 # the search will be a marc search if MARC=ON
1043 # and a standard (v1.2) search if MARC=OFF
1044 #
1045 # Revision 1.31  2003/01/06 13:32:43  tipaul
1046 # *** empty log message ***
1047 #
1048 # Revision 1.29  2003/01/06 11:14:11  tipaul
1049 # last bugfixes before 1.3.3 : systempref table correctly filled
1050 #
1051 # Revision 1.28  2002/12/10 13:27:47  tipaul
1052 # bugfixes (davide mails in koha-dev)
1053 #
1054 # Revision 1.27  2002/11/26 15:04:54  tipaul
1055 # road to 1.3.2. Updating db structure during installation
1056 #
1057 # Revision 1.26  2002/11/12 17:42:40  tonnesen
1058 # Merged some features over from rel-1-2, including primary key checking.
1059 #
1060 # Revision 1.25  2002/11/12 16:44:38  tipaul
1061 # road to 1.3.2 :
1062 # * many bugfixes
1063 # * 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)
1064 #
1065 # Revision 1.24  2002/10/30 14:00:23  arensb
1066 # (bug fix): Fixed typo.
1067 #
1068 # Revision 1.23  2002/10/25 10:55:46  tipaul
1069 # Road to 1.3.2
1070 # * bugfixes and improvements
1071 # * manage mandatory MARC subfields
1072 # * 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.
1073 # this submit contains everything needed :
1074 # * updatedatabase
1075 # * admin screens
1076 # * "links" management
1077 # * creation of a html-list if a subfield is mapped to an authorised value.
1078 #
1079 # Note this is different from authorities support, which will come soon.
1080 # 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...
1081 #
1082 # Revision 1.22  2002/10/15 10:08:19  tipaul
1083 # fixme corrected, re-indent and adding the marc_breeding table (see commit of marcimport.pl for more explanations about breeding)
1084 #
1085 # Revision 1.21  2002/10/14 11:48:59  tipaul
1086 # bugfix
1087 #
1088 # Revision 1.20  2002/10/10 04:49:41  arensb
1089 # Added some FIXME comments.
1090 #
1091 # Revision 1.19  2002/10/05 10:17:17  arensb
1092 # Merged with arensb-context branch: use C4::Context->dbh instead of
1093 # &C4Connect, and generally prefer C4::Context over C4::Database.
1094 #
1095 # Revision 1.18.2.2  2002/10/05 06:18:43  arensb
1096 # Added a whole mess of FIXME comments.
1097 #
1098 # Revision 1.18.2.1  2002/10/04 02:46:00  arensb
1099 # Use C4::Connect instead of C4::Database, C4::Connect->dbh instead
1100 # C4Connect.
1101 #
1102 # Revision 1.18  2002/09/24 13:50:55  tipaul
1103 # long WAS the road to 1.3.0...
1104 # coming VERY SOON NOW...
1105 # modifying installer and buildrelease to update the DB
1106 #
1107 # Revision 1.17  2002/09/24 12:57:35  tipaul
1108 # long WAS the road to 1.3.0...
1109 # coming VERY SOON NOW...
1110 # modifying installer and buildrelease to update the DB
1111 #
1112 # Revision 1.16  2002/07/31 02:34:27  finlayt
1113 #
1114 # added "notforloan" field to the itemtypes table.
1115 #
1116 # Revision 1.15  2002/07/20 22:30:06  rangi
1117 # Making sure fix makes it into the main branch as well
1118 # Fix for bug 69
1119 #
1120 # Revision 1.14  2002/07/08 16:20:26  tonnesen
1121 # Added sessionqueries table and password/userid fields to borrowers table
1122 #
1123 # Revision 1.13  2002/07/04 18:05:36  tonnesen
1124 # bug fix
1125 #
1126 # Revision 1.12  2002/07/04 16:41:06  tonnesen
1127 # Merged changes from rel-1-2.  Abstracted table structure changes by alan.
1128 #