Added new fields to auth_header and auth_subfield_table to allow ZEBRA use of authori...
[koha.git] / updater / updatedatabase
1 #!/usr/bin/perl
2
3 # $Id$
4
5 # Database Updater
6 # This script checks for required updates to the database.
7
8 # Part of the Koha Library Software www.koha.org
9 # Licensed under the GPL.
10
11 # Bugs/ToDo:
12 # - Would also be a good idea to offer to do a backup at this time...
13
14 # NOTE:  If you do something more than once in here, make it table driven.
15 use strict;
16
17 # CPAN modules
18 use DBI;
19 use Getopt::Long;
20 # Koha modules
21 use C4::Context;
22
23 use MARC::Record;
24 use MARC::File::XML ( BinaryEncoding => 'utf8' );
25  
26 # FIXME - The user might be installing a new database, so can't rely
27 # on /etc/koha.conf anyway.
28
29 my $debug = 0;
30
31 my (
32     $sth, $sti,
33     $query,
34     %existingtables,    # tables already in database
35     %types,
36     $table,
37     $column,
38     $type, $null, $key, $default, $extra,
39     $prefitem,          # preference item in systempreferences table
40 );
41
42 my $silent;
43 GetOptions(
44         's' =>\$silent
45         );
46 my $dbh = C4::Context->dbh;
47 print "connected to your DB. Checking & modifying it\n" unless $silent;
48 $|=1; # flushes output
49
50 #-------------------
51 # Defines
52
53 # Tables to add if they don't exist
54 my %requiretables = (
55     categorytable       => "(categorycode char(5) NOT NULL default '',
56                              description text default '',
57                              itemtypecodes text default '',
58                              PRIMARY KEY (categorycode)
59                             )",
60     subcategorytable       => "(subcategorycode char(5) NOT NULL default '',
61                              description text default '',
62                              itemtypecodes text default '',
63                              PRIMARY KEY (subcategorycode)
64                             )",
65     mediatypetable       => "(mediatypecode char(5) NOT NULL default '',
66                              description text default '',
67                              itemtypecodes text default '',
68                              PRIMARY KEY (mediatypecode)
69                             )",
70     action_logs         => "(
71                                     `timestamp` TIMESTAMP NOT NULL ,
72                                     `user` INT( 11 ) NOT NULL ,
73                                     `module` TEXT default '',
74                                     `action` TEXT default '' ,
75                                     `object` INT(11) default '' ,
76                                     `info` TEXT default '' ,
77                                     PRIMARY KEY ( `timestamp` , `user` )
78                             )",
79         letter          => "(
80                                         module varchar(20) NOT NULL default '',
81                                         code varchar(20) NOT NULL default '',
82                                         name varchar(100) NOT NULL default '',
83                                         title varchar(200) NOT NULL default '',
84                                         content text,
85                                         PRIMARY KEY  (module,code)
86                                 )",
87         alert           =>"(
88                                         alertid int(11) NOT NULL auto_increment,
89                                         borrowernumber int(11) NOT NULL default '0',
90                                         type varchar(10) NOT NULL default '',
91                                         externalid varchar(20) NOT NULL default '',
92                                         PRIMARY KEY  (alertid),
93                                         KEY borrowernumber (borrowernumber),
94                                         KEY type (type,externalid)
95                                 )",
96         opac_news => "(
97                                 `idnew` int(10) unsigned NOT NULL auto_increment,
98                                 `title` varchar(250) NOT NULL default '',
99                                 `new` text NOT NULL,
100                                 `lang` varchar(4) NOT NULL default '',
101                                 `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP,
102                                 PRIMARY KEY  (`idnew`)
103                                 )",
104         repeatable_holidays => "(
105                                 `id` int(11) NOT NULL auto_increment,
106                                 `branchcode` varchar(4) NOT NULL default '',
107                                 `weekday` smallint(6) default NULL,
108                                 `day` smallint(6) default NULL,
109                                 `month` smallint(6) default NULL,
110                                 `title` varchar(50) NOT NULL default '',
111                                 `description` text NOT NULL,
112                                 PRIMARY KEY  (`id`)
113                                 )",
114         special_holidays => "(
115                                 `id` int(11) NOT NULL auto_increment,
116                                 `branchcode` varchar(4) NOT NULL default '',
117                                 `day` smallint(6) NOT NULL default '0',
118                                 `month` smallint(6) NOT NULL default '0',
119                                 `year` smallint(6) NOT NULL default '0',
120                                 `isexception` smallint(1) NOT NULL default '1',
121                                 `title` varchar(50) NOT NULL default '',
122                                 `description` text NOT NULL,
123                                 PRIMARY KEY  (`id`)
124                                 )",
125         overduerules    =>"(`branchcode` varchar(255) NOT NULL default '',
126                                         `categorycode` char(2) NOT NULL default '',
127                                         `delay1` int(4) default '0',
128                                         `letter1` varchar(20) default NULL,
129                                         `debarred1` char(1) default '0',
130                                         `delay2` int(4) default '0',
131                                         `debarred2` char(1) default '0',
132                                         `letter2` varchar(20) default NULL,
133                                         `delay3` int(4) default '0',
134                                         `letter3` varchar(20) default NULL,
135                                         `debarred3` int(1) default '0',
136                                         PRIMARY KEY  (`branchcode`,`categorycode`)
137                                         )",
138         cities                  => "(`cityid` int auto_increment,
139                                                 `city_name` char(100) NOT NULL,
140                                                 `city_zipcode` char(20),
141                                                 PRIMARY KEY (`cityid`)
142                                         )",
143         roadtype                        => "(`roadtypeid` int auto_increment,
144                                                 `road_type` char(100) NOT NULL,
145                                                 PRIMARY KEY (`roadtypeid`)
146                                         )",
147
148         labels                     => "(
149                                 labelid int(11) NOT NULL auto_increment,
150                                 itemnumber varchar(100) NOT NULL default '',
151                                 timestamp timestamp(14) NOT NULL,
152                                 PRIMARY KEY  (labelid)
153                                 )",
154
155         labels_conf                => "(
156                                 id int(4) NOT NULL auto_increment,
157                                 barcodetype char(100) default '',
158                                 title tinyint(1) default '0',
159                                 isbn tinyint(1) default '0',
160                                 itemtype tinyint(1) default '0',
161                                 barcode tinyint(1) default '0',
162                                 dewey tinyint(1) default '0',
163                                 class tinyint(1) default '0',
164                                 author tinyint(1) default '0',
165                                 papertype char(100) default '',
166                                 startrow int(2) default NULL,
167                                 PRIMARY KEY  (id)
168                                 )",
169
170 );
171
172 my %requirefields = (
173         subscription => { 'letter' => 'char(20) NULL', 'distributedto' => 'text NULL'},
174         itemtypes => { 'imageurl' => 'char(200) NULL'},
175         aqbookfund => { 'branchcode' => 'varchar(4) NULL'},
176         aqbudget => { 'branchcode' => 'varchar(4) NULL'},
177         auth_header => { 'marc' => 'BLOB NOT NULL', 'linkid' => 'BIGINT(20) NULL'},
178         auth_subfield_structure =>{ 'hidden' => 'TINYINT(3) NOT NULL UNSIGNED ZEROFILL', 'kohafield' => 'VARCHAR(45) NOT NULL', 'linkid' =>  'TINYINT(1) NOT NULL UNSIGNED', 'isurl' => 'TINYINT(1) UNSIGNED'},
179 #    tablename        => { 'field' => 'fieldtype' },
180 );
181
182 my %dropable_table = (
183         sessionqueries  => 'sessionqueries',
184         marcrecorddone  => 'marcrecorddone',
185         users                   => 'users',
186         itemsprices             => 'itemsprices',
187         biblioanalysis  => 'biblioanalysis',
188         borexp                  => 'borexp',
189 # tablename => 'tablename',
190 );
191
192 my %uselessfields = (
193 # tablename => "field1,field2",
194         borrowers => "suburb,altstreetaddress,altsuburb,altcity,studentnumber,school,area,preferredcont,altcp",
195         );
196 # the other hash contains other actions that can't be done elsewhere. they are done
197 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
198
199 # The tabledata hash contains data that should be in the tables.
200 # The uniquefieldrequired hash entry is used to determine which (if any) fields
201 # must not exist in the table for this row to be inserted.  If the
202 # uniquefieldrequired entry is already in the table, the existing data is not
203 # modified, unless the forceupdate hash entry is also set.  Fields in the
204 # anonymous "forceupdate" hash will be forced to be updated to the default
205 # values given in the %tabledata hash.
206
207 my %tabledata = (
208 # tablename => [
209 #       {       uniquefielrequired => 'fieldname', # the primary key in the table
210 #               fieldname => fieldvalue,
211 #               fieldname2 => fieldvalue2,
212 #       },
213 # ],
214     systempreferences => [
215                 {
216             uniquefieldrequired => 'variable',
217             variable            => 'Activate_Log',
218             value               => 'On',
219             forceupdate         => { 'explanation' => 1,
220                                      'type' => 1},
221             explanation         => 'Turn Log Actions on DB On an Off',
222             type                => 'YesNo',
223         },
224         {
225             uniquefieldrequired => 'variable',
226             variable            => 'IndependantBranches',
227             value               => 0,
228             forceupdate         => { 'explanation' => 1,
229                                      'type' => 1},
230             explanation         => 'Turn Branch independancy management On an Off',
231             type                => 'YesNo',
232         },
233                 {
234             uniquefieldrequired => 'variable',
235             variable            => 'ReturnBeforeExpiry',
236             value               => 'Off',
237             forceupdate         => { 'explanation' => 1,
238                                      'type' => 1},
239             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
240             type                => 'YesNo',
241         },
242         {
243             uniquefieldrequired => 'variable',
244             variable            => 'opacstylesheet',
245             value               => '',
246             forceupdate         => { 'explanation' => 1,
247                                      'type' => 1},
248             explanation         => 'Enter a complete URL to use an alternate stylesheet in OPAC',
249             type                => 'free',
250         },
251         {
252             uniquefieldrequired => 'variable',
253             variable            => 'opacsmallimage',
254             value               => '',
255             forceupdate         => { 'explanation' => 1,
256                                      'type' => 1},
257             explanation         => 'Enter a complete URL to an image, will be on top/left instead of the Koha logo',
258             type                => 'free',
259         },
260         {
261             uniquefieldrequired => 'variable',
262             variable            => 'opaclargeimage',
263             value               => '',
264             forceupdate         => { 'explanation' => 1,
265                                      'type' => 1},
266             explanation         => 'Enter a complete URL to an image, will be on the main page, instead of the Koha logo',
267             type                => 'free',
268         },
269         {
270             uniquefieldrequired => 'variable',
271             variable            => 'delimiter',
272             value               => ';',
273             forceupdate         => { 'explanation' => 1,
274                                      'type' => 1},
275             explanation         => 'separator for reports exported to spreadsheet',
276             type                => 'free',
277         },
278         {
279             uniquefieldrequired => 'variable',
280             variable            => 'MIME',
281             value               => 'OPENOFFICE.ORG',
282             forceupdate         => { 'explanation' => 1,
283                                      'type' => 1,
284                                      'options' => 1},
285             explanation         => 'Define the default application for report exportations into files',
286                 type            => 'Choice',
287                 options         => 'EXCEL|OPENOFFICE.ORG'
288         },
289         {
290             uniquefieldrequired => 'variable',
291             variable            => 'Delimiter',
292             value               => ';',
293                 forceupdate             => { 'explanation' => 1,
294                                      'type' => 1,
295                                      'options' => 1},
296             explanation         => 'Define the default separator character for report exportations into files',
297                 type            => 'Choice',
298                 options         => ';|tabulation|,|/|\|#'
299         },
300         {
301             uniquefieldrequired => 'variable',
302             variable            => 'SubscriptionHistory',
303             value               => ';',
304                 forceupdate             => { 'explanation' => 1,
305                                      'type' => 1,
306                                      'options' => 1},
307             explanation         => 'Define the information level for serials history in OPAC',
308                 type            => 'Choice',
309                 options         => 'simplified|full'
310         },
311         {
312             uniquefieldrequired => 'variable',
313             variable            => 'hidelostitems',
314             value               => 'No',
315             forceupdate         => { 'explanation' => 1,
316                                      'type' => 1},
317             explanation         => 'show or hide "lost" items in OPAC.',
318             type                => 'YesNo',
319         },
320                  {
321             uniquefieldrequired => 'variable',
322             variable            => 'IndependantBranches',
323             value               => '0',
324             forceupdate         => { 'explanation' => 1,
325                                      'type' => 1},
326             explanation         => 'Turn Branch independancy management On an Off',
327             type                => 'YesNo',
328         },
329                 {
330             uniquefieldrequired => 'variable',
331             variable            => 'ReturnBeforeExpiry',
332             value               => '0',
333             forceupdate         => { 'explanation' => 1,
334                                      'type' => 1},
335             explanation         => 'If Yes, Returndate on issuing can\'t be after borrower card expiry',
336             type                => 'YesNo',
337         },
338         {
339             uniquefieldrequired => 'variable',
340             variable            => 'Disable_Dictionary',
341             value               => '0',
342             forceupdate         => { 'explanation' => 1,
343                                      'type' => 1},
344             explanation         => 'Disables Dictionary buttons if set to yes',
345             type                => 'YesNo',
346         },
347         {
348             uniquefieldrequired => 'variable',
349             variable            => 'hide_marc',
350             value               => '0',
351             forceupdate         => { 'explanation' => 1,
352                                      'type' => 1},
353             explanation         => 'hide marc specific datas like subfield code & indicators to library',
354             type                => 'YesNo',
355         },
356         {
357             uniquefieldrequired => 'variable',
358             variable            => 'NotifyBorrowerDeparture',
359             value               => '0',
360             forceupdate         => { 'explanation' => 1,
361                                      'type' => 1},
362             explanation         => 'Delay before expiry where a notice is sent when issuing',
363             type                => 'Integer',
364         },
365         {
366             uniquefieldrequired => 'variable',
367             variable            => 'OpacPasswordChange',
368             value               => '1',
369             forceupdate         => { 'explanation' => 1,
370                                      'type' => 1},
371             explanation         => 'Enable/Disable password change in OPAC (disable it when using LDAP auth)',
372             type                => 'YesNo',
373         },
374         {
375             uniquefieldrequired => 'variable',
376             variable            => 'useDaysMode',
377             value               => 'Calendar',
378             forceupdate         => { 'explanation' => 1,
379                                      'type' => 1},
380             explanation                 => 'How to calculate return dates : Calendar means holidays will be controled, Days means the return date don\'t depend on holidays',
381                 type            => 'Choice',
382                 options         => 'Calendar|Days'
383         },
384         {
385             uniquefieldrequired => 'variable',
386             variable            => 'borrowerMandatoryField',
387             value               => 'zipcode|surname',
388             forceupdate         => { 'explanation' => 1,
389                                      'type' => 1},
390             explanation         => 'List all mandatory fields for borrowers',
391             type                => 'free',
392         },
393         {
394             uniquefieldrequired => 'variable',
395             variable            => 'borrowerRelationship',
396             value               => 'father|mother,grand-mother',
397             forceupdate         => { 'explanation' => 1,
398                                      'type' => 1},
399             explanation         => 'The relationships between a guarantor & a guarantee (separated by | or ,)',
400             type                => 'free',
401         },
402         {
403             uniquefieldrequired => 'variable',
404             variable            => 'ReservesMaxPickUpDelay',
405             value               => '10',
406             forceupdate         => { 'explanation' => 1,
407                                      'type' => 1},
408             explanation         => 'Maximum delay to pick up a reserved document',
409             type                => 'free',
410         },
411         {
412             uniquefieldrequired => 'variable',
413             variable            => 'TransfersMaxDaysWarning',
414             value               => '3',
415             forceupdate         => { 'explanation' => 1,
416                                      'type' => 1},
417             explanation         => 'Max delay before considering the transfer has potentialy a problem',
418             type                => 'free',
419         },
420     ],
421
422 );
423
424 my %fielddefinitions = (
425 # fieldname => [
426 #       {                 field => 'fieldname',
427 #             type    => 'fieldtype',
428 #             null    => '',
429 #             key     => '',
430 #             default => ''
431 #         },
432 #     ],
433         serial => [
434         {
435             field   => 'notes',
436             type    => 'TEXT',
437             null    => 'NULL',
438             key     => '',
439             default => '',
440             extra   => ''
441         },
442     ],
443         aqbasket =>  [
444                 {
445                         field   => 'booksellerid',
446                         type    => 'int(11)',
447                         null    => 'NOT NULL',
448                         key             => '',
449                         default => '1',
450                         extra   => '',
451                 },
452         ],
453         aqbooksellers =>  [
454                 {
455                         field   => 'listprice',
456                         type    => 'varchar(10)',
457                         null    => 'NULL',
458                         key             => '',
459                         default => '',
460                         extra   => '',
461                 },
462                 {
463                         field   => 'invoiceprice',
464                         type    => 'varchar(10)',
465                         null    => 'NULL',
466                         key             => '',
467                         default => '',
468                         extra   => '',
469                 },
470         ],
471         issues =>  [
472                 {
473                         field   => 'borrowernumber',
474                         type    => 'int(11)',
475                         null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
476                         key             => '',
477                         default => '',
478                         extra   => '',
479                 },
480                 {
481                         field   => 'itemnumber',
482                         type    => 'int(11)',
483                         null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
484                         key             => '',
485                         default => '',
486                         extra   => '',
487                 },
488         ],
489         borrowers => [
490                 {       field => 'B_email',
491                         type => 'text',
492                         null => 'NULL',
493                         after => 'B_zipcode',
494                  },
495                  {
496                         field => 'streetnumber', # street number (hidden if streettable table is empty)
497                         type => 'char(10)',
498                         null => 'NULL',
499                         after => 'initials',
500                 },
501                 {
502                         field => 'streettype', # street table, list builded from a system table
503                         type => 'char(50)',
504                         null => 'NULL',
505                         after => 'streetnumber',
506                 },
507                  {
508                         field => 'B_streetnumber', # street number (hidden if streettable table is empty)
509                         type => 'char(10)',
510                         null => 'NULL',
511                         after => 'fax',
512                 },
513                 {
514                         field => 'B_streettype', # street table, list builded from a system table
515                         type => 'char(50)',
516                         null => 'NULL',
517                         after => 'B_streetnumber',
518                 },
519                 {
520                         field => 'phonepro',
521                         type => 'text',
522                         null => 'NULL',
523                         after => 'fax',
524                 },
525                 {
526                         field => 'address2', # complement address
527                         type => 'text',
528                         null => 'NULL',
529                         after => 'address',
530                 },
531                 {
532                         field => 'emailpro',
533                         type => 'text',
534                         null => 'NULL',
535                         after => 'fax',
536                 },
537                 {
538                         field => 'contactfirstname', # contact's firstname
539                         type => 'text',
540                         null => 'NULL',
541                         after => 'contactname',
542                 },
543                 {
544                         field => 'contacttitle', # contact's title
545                         type => 'text',
546                         null => 'NULL',
547                         after => 'contactfirstname',
548                 },
549         ],
550         
551         branches =>  [
552                 {
553                         field   => 'branchip',
554                         type    => 'varchar(15)',
555                         null    => 'NULL',
556                         key             => '',
557                         default => '',
558                         extra   => '',
559                 },
560                 {
561                         field   => 'branchprinter',
562                         type    => 'varchar(100)',
563                         null    => 'NULL',
564                         key             => '',
565                         default => '',
566                         extra   => '',
567                 },
568         ],
569         categories =>  [
570                 {
571                         field   => 'category_type',
572                         type    => 'char(1)',
573                         null    => 'NOT NULL',
574                         key             => '',
575                         default => 'A',
576                         extra   => '',
577                 },
578         ],
579         reserves =>  [
580                 {
581                         field   => 'waitingdate',
582                         type    => 'date',
583                         null    => 'NULL',
584                         key             => '',
585                         default => '',
586                         extra   => '',
587                 },
588         ],
589 );
590
591 my %indexes = (
592 #       table => [
593 #               {       indexname => 'index detail'
594 #               }
595 #       ],
596         shelfcontents => [
597                 {       indexname => 'shelfnumber',
598                         content => 'shelfnumber',
599                 },
600                 {       indexname => 'itemnumber',
601                         content => 'itemnumber',
602                 }
603         ],
604         bibliosubject => [
605                 {       indexname => 'biblionumber',
606                         content => 'biblionumber',
607                 }
608         ],
609         items => [
610                 {       indexname => 'homebranch',
611                         content => 'homebranch',
612                 },
613                 {       indexname => 'holdingbranch',
614                         content => 'holdingbranch',
615                 }
616         ],
617         aqbooksellers => [
618                 {       indexname => 'PRIMARY',
619                         content => 'id',
620                         type => 'PRIMARY',
621                 }
622         ],
623         aqbasket => [
624                 {       indexname => 'booksellerid',
625                         content => 'booksellerid',
626                 },
627         ],
628         aqorders => [
629                 {       indexname => 'basketno',
630                         content => 'basketno',
631                 },
632         ],
633         aqorderbreakdown => [
634                 {       indexname => 'ordernumber',
635                         content => 'ordernumber',
636                 },
637                 {       indexname => 'bookfundid',
638                         content => 'bookfundid',
639                 },
640         ],
641         currency => [
642                 {       indexname => 'PRIMARY',
643                         content => 'currency',
644                         type => 'PRIMARY',
645                 }
646         ],
647 );
648
649 my %foreign_keys = (
650 #       table => [
651 #               {       key => 'the key in table' (must be indexed)
652 #                       foreigntable => 'the foreigntable name', # (the parent)
653 #                       foreignkey => 'the foreign key column(s)' # (in the parent)
654 #                       onUpdate => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
655 #                       onDelete => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
656 #               }
657 #       ],
658         shelfcontents => [
659                 {       key => 'shelfnumber',
660                         foreigntable => 'bookshelf',
661                         foreignkey => 'shelfnumber',
662                         onUpdate => 'CASCADE',
663                         onDelete => 'CASCADE',
664                 },
665                 {       key => 'itemnumber',
666                         foreigntable => 'items',
667                         foreignkey => 'itemnumber',
668                         onUpdate => 'CASCADE',
669                         onDelete => 'CASCADE',
670                 },
671         ],
672         # onDelete is RESTRICT on reference tables (branches, itemtype) as we don't want items to be 
673         # easily deleted, but branches/itemtype not too easy to empty...
674         biblioitems => [
675                 {       key => 'biblionumber',
676                         foreigntable => 'biblio',
677                         foreignkey => 'biblionumber',
678                         onUpdate => 'CASCADE',
679                         onDelete => 'CASCADE',
680                 },
681                 {       key => 'itemtype',
682                         foreigntable => 'itemtypes',
683                         foreignkey => 'itemtype',
684                         onUpdate => 'CASCADE',
685                         onDelete => 'RESTRICT',
686                 },
687         ],
688         items => [
689                 {       key => 'biblioitemnumber',
690                         foreigntable => 'biblioitems',
691                         foreignkey => 'biblioitemnumber',
692                         onUpdate => 'CASCADE',
693                         onDelete => 'CASCADE',
694                 },
695                 {       key => 'homebranch',
696                         foreigntable => 'branches',
697                         foreignkey => 'branchcode',
698                         onUpdate => 'CASCADE',
699                         onDelete => 'RESTRICT',
700                 },
701                 {       key => 'holdingbranch',
702                         foreigntable => 'branches',
703                         foreignkey => 'branchcode',
704                         onUpdate => 'CASCADE',
705                         onDelete => 'RESTRICT',
706                 },
707         ],
708         additionalauthors => [
709                 {       key => 'biblionumber',
710                         foreigntable => 'biblio',
711                         foreignkey => 'biblionumber',
712                         onUpdate => 'CASCADE',
713                         onDelete => 'CASCADE',
714                 },
715         ],
716         bibliosubject => [
717                 {       key => 'biblionumber',
718                         foreigntable => 'biblio',
719                         foreignkey => 'biblionumber',
720                         onUpdate => 'CASCADE',
721                         onDelete => 'CASCADE',
722                 },
723         ],
724         aqbasket => [
725                 {       key => 'booksellerid',
726                         foreigntable => 'aqbooksellers',
727                         foreignkey => 'id',
728                         onUpdate => 'CASCADE',
729                         onDelete => 'RESTRICT',
730                 },
731         ],
732         aqorders => [
733                 {       key => 'basketno',
734                         foreigntable => 'aqbasket',
735                         foreignkey => 'basketno',
736                         onUpdate => 'CASCADE',
737                         onDelete => 'CASCADE',
738                 },
739                 {       key => 'biblionumber',
740                         foreigntable => 'biblio',
741                         foreignkey => 'biblionumber',
742                         onUpdate => 'SET NULL',
743                         onDelete => 'SET NULL',
744                 },
745         ],
746         aqbooksellers => [
747                 {       key => 'listprice',
748                         foreigntable => 'currency',
749                         foreignkey => 'currency',
750                         onUpdate => 'CASCADE',
751                         onDelete => 'CASCADE',
752                 },
753                 {       key => 'invoiceprice',
754                         foreigntable => 'currency',
755                         foreignkey => 'currency',
756                         onUpdate => 'CASCADE',
757                         onDelete => 'CASCADE',
758                 },
759         ],
760         aqorderbreakdown => [
761                 {       key => 'ordernumber',
762                         foreigntable => 'aqorders',
763                         foreignkey => 'ordernumber',
764                         onUpdate => 'CASCADE',
765                         onDelete => 'CASCADE',
766                 },
767                 {       key => 'bookfundid',
768                         foreigntable => 'aqbookfund',
769                         foreignkey => 'bookfundid',
770                         onUpdate => 'CASCADE',
771                         onDelete => 'CASCADE',
772                 },
773         ],
774         branchtransfers => [
775                 {       key => 'frombranch',
776                         foreigntable => 'branches',
777                         foreignkey => 'branchcode',
778                         onUpdate => 'CASCADE',
779                         onDelete => 'CASCADE',
780                 },
781                 {       key => 'tobranch',
782                         foreigntable => 'branches',
783                         foreignkey => 'branchcode',
784                         onUpdate => 'CASCADE',
785                         onDelete => 'CASCADE',
786                 },
787                 {       key => 'itemnumber',
788                         foreigntable => 'items',
789                         foreignkey => 'itemnumber',
790                         onUpdate => 'CASCADE',
791                         onDelete => 'CASCADE',
792                 },
793         ],
794         issuingrules => [
795                 {       key => 'categorycode',
796                         foreigntable => 'categories',
797                         foreignkey => 'categorycode',
798                         onUpdate => 'CASCADE',
799                         onDelete => 'CASCADE',
800                 },
801                 {       key => 'itemtype',
802                         foreigntable => 'itemtypes',
803                         foreignkey => 'itemtype',
804                         onUpdate => 'CASCADE',
805                         onDelete => 'CASCADE',
806                 },
807         ],
808         issues => [     # constraint is SET NULL : when a borrower or an item is deleted, we keep the issuing record
809         # for stat purposes
810                 {       key => 'borrowernumber',
811                         foreigntable => 'borrowers',
812                         foreignkey => 'borrowernumber',
813                         onUpdate => 'SET NULL',
814                         onDelete => 'SET NULL',
815                 },
816                 {       key => 'itemnumber',
817                         foreigntable => 'items',
818                         foreignkey => 'itemnumber',
819                         onUpdate => 'SET NULL',
820                         onDelete => 'SET NULL',
821                 },
822         ],
823         reserves => [
824                 {       key => 'borrowernumber',
825                         foreigntable => 'borrowers',
826                         foreignkey => 'borrowernumber',
827                         onUpdate => 'CASCADE',
828                         onDelete => 'CASCADE',
829                 },
830                 {       key => 'biblionumber',
831                         foreigntable => 'biblio',
832                         foreignkey => 'biblionumber',
833                         onUpdate => 'CASCADE',
834                         onDelete => 'CASCADE',
835                 },
836                 {       key => 'itemnumber',
837                         foreigntable => 'items',
838                         foreignkey => 'itemnumber',
839                         onUpdate => 'CASCADE',
840                         onDelete => 'CASCADE',
841                 },
842                 {       key => 'branchcode',
843                         foreigntable => 'branches',
844                         foreignkey => 'branchcode',
845                         onUpdate => 'CASCADE',
846                         onDelete => 'CASCADE',
847                 },
848         ],
849         borrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
850         # but prevent deleting a branch as soon as it has 1 borrower !
851                 {       key => 'categorycode',
852                         foreigntable => 'categories',
853                         foreignkey => 'categorycode',
854                         onUpdate => 'RESTRICT',
855                         onDelete => 'RESTRICT',
856                 },
857                 {       key => 'branchcode',
858                         foreigntable => 'branches',
859                         foreignkey => 'branchcode',
860                         onUpdate => 'RESTRICT',
861                         onDelete => 'RESTRICT',
862                 },
863         ],
864         accountlines => [
865                 {       key => 'borrowernumber',
866                         foreigntable => 'borrowers',
867                         foreignkey => 'borrowernumber',
868                         onUpdate => 'CASCADE',
869                         onDelete => 'CASCADE',
870                 },
871                 {       key => 'itemnumber',
872                         foreigntable => 'items',
873                         foreignkey => 'itemnumber',
874                         onUpdate => 'SET NULL',
875                         onDelete => 'SET NULL',
876                 },
877         ],
878         auth_tag_structure => [
879                 {       key => 'authtypecode',
880                         foreigntable => 'auth_types',
881                         foreignkey => 'authtypecode',
882                         onUpdate => 'CASCADE',
883                         onDelete => 'CASCADE',
884                 },
885         ],
886         # FIXME : don't constraint auth_*_table and auth_word, as they may be replaced by zebra
887 );
888
889
890 # column changes
891 my %column_change = (
892         # table
893         borrowers => [
894                                 {
895                                         from => 'emailaddress',
896                                         to => 'email',
897                                         after => 'city',
898                                 },
899                                 {
900                                         from => 'streetaddress',
901                                         to => 'address',
902                                         after => 'initials',
903                                 },
904                                 {
905                                         from => 'faxnumber',
906                                         to => 'fax',
907                                         after => 'phone',
908                                 },
909                                 {
910                                         from => 'textmessaging',
911                                         to => 'opacnote',
912                                         after => 'userid',
913                                 },
914                                 {
915                                         from => 'altnotes',
916                                         to => 'contactnote',
917                                         after => 'opacnote',
918                                 },
919                                 {
920                                         from => 'physstreet',
921                                         to => 'B_address',
922                                         after => 'fax',
923                                 },
924                                 {
925                                         from => 'streetcity',
926                                         to => 'B_city',
927                                         after => 'B_address',
928                                 },
929                                 {
930                                         from => 'phoneday',
931                                         to => 'mobile',
932                                         after => 'phone',
933                                 },
934                                 {
935                                         from => 'zipcode',
936                                         to => 'zipcode',
937                                         after => 'city',
938                                 },
939                                 {
940                                         from => 'homezipcode',
941                                         to => 'B_zipcode',
942                                         after => 'B_city',
943                                 },
944                                 {
945                                         from => 'altphone',
946                                         to => 'B_phone',
947                                         after => 'B_zipcode',
948                                 },
949                                 {
950                                         from => 'expiry',
951                                         to => 'dateexpiry',
952                                         after => 'dateenrolled',
953                                 },
954                                 {
955                                         from => 'guarantor',
956                                         to => 'guarantorid',
957                                         after => 'contactname',
958                                 },
959                                 {
960                                         from => 'textmessaging',
961                                         to => 'opacnotes',
962                                         after => 'flags',
963                                 },
964                                 {
965                                         from => 'altnotes',
966                                         to => 'contactnotes',
967                                         after => 'opacnotes',
968                                 },
969                                 {
970                                         from => 'altrelationship',
971                                         to => 'relationship',
972                                         after => 'borrowernotes',
973                                 },
974                         ],
975                 );
976                 
977 foreach my $table (keys %column_change) {
978         $sth = $dbh->prepare("show columns from $table");
979         $sth->execute();
980         undef %types;
981         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
982         {
983                 $types{$column}->{type} ="$type";
984                 $types{$column}->{null} = "$null";
985                 $types{$column}->{key} = "$key";
986                 $types{$column}->{default} = "$default";
987                 $types{$column}->{extra} = "$extra";
988         }    # while
989         my $tablerows = $column_change{$table};
990         foreach my $row ( @$tablerows ) {
991                 if ($types{$row->{from}}->{type}) {
992                         print "altering $table $row->{from} to $row->{to}\n";
993                         # ALTER TABLE `borrowers` CHANGE `faxnumber` `fax` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL 
994 #                       alter table `borrowers` change `faxnumber` `fax` type text  null after phone
995                         my $sql = 
996                                 "alter table `$table` change `$row->{from}` `$row->{to}` $types{$row->{from}}->{type} ".
997                                 ($types{$row->{from}}->{null} eq 'YES'?" NULL":" NOT NULL").
998                                 ($types{$row->{from}}->{default}?" default ".$types{$row->{from}}->{default}:"").
999                                 "$types{$row->{from}}->{extra} after $row->{after} ";
1000 #                       print "$sql";
1001                         $dbh->do($sql);
1002                 }
1003         }
1004 }
1005
1006 #-------------------
1007 # Initialize
1008
1009 # Start checking
1010
1011 # Get version of MySQL database engine.
1012 my $mysqlversion = `mysqld --version`;
1013 $mysqlversion =~ /Ver (\S*) /;
1014 $mysqlversion = $1;
1015 if ( $mysqlversion ge '3.23' ) {
1016     print "Could convert to MyISAM database tables...\n" unless $silent;
1017 }
1018
1019 #---------------------------------
1020 # Tables
1021
1022 # Collect all tables into a list
1023 $sth = $dbh->prepare("show tables");
1024 $sth->execute;
1025 while ( my ($table) = $sth->fetchrow ) {
1026     $existingtables{$table} = 1;
1027 }
1028
1029
1030 # Now add any missing tables
1031 foreach $table ( keys %requiretables ) {
1032     unless ( $existingtables{$table} ) {
1033         print "Adding $table table...\n" unless $silent;
1034         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
1035         $sth->execute;
1036         if ( $sth->err ) {
1037             print "Error : $sth->errstr \n";
1038             $sth->finish;
1039         }    # if error
1040     }    # unless exists
1041 }    # foreach
1042
1043 # now drop useless tables
1044 foreach $table ( keys %dropable_table ) {
1045         if ( $existingtables{$table} ) {
1046                 print "Dropping unused table $table\n" if $debug and not $silent;
1047                 $dbh->do("drop table $table");
1048                 if ( $dbh->err ) {
1049                         print "Error : $dbh->errstr \n";
1050                 }
1051         }
1052 }
1053
1054 #---------------------------------
1055 # Columns
1056
1057 foreach $table ( keys %requirefields ) {
1058     print "Check table $table\n" if $debug and not $silent;
1059     $sth = $dbh->prepare("show columns from $table");
1060     $sth->execute();
1061     undef %types;
1062     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1063     {
1064         $types{$column} = $type;
1065     }    # while
1066     foreach $column ( keys %{ $requirefields{$table} } ) {
1067         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
1068         if ( !$types{$column} ) {
1069
1070             # column doesn't exist
1071             print "Adding $column field to $table table...\n" unless $silent;
1072             $query = "alter table $table
1073                         add column $column " . $requirefields{$table}->{$column};
1074             print "Execute: $query\n" if $debug;
1075             my $sti = $dbh->prepare($query);
1076             $sti->execute;
1077             if ( $sti->err ) {
1078                 print "**Error : $sti->errstr \n";
1079                 $sti->finish;
1080             }    # if error
1081         }    # if column
1082     }    # foreach column
1083 }    # foreach table
1084
1085 foreach $table ( keys %fielddefinitions ) {
1086         print "Check table $table\n" if $debug;
1087         $sth = $dbh->prepare("show columns from $table");
1088         $sth->execute();
1089         my $definitions;
1090         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1091         {
1092                 $definitions->{$column}->{type}    = $type;
1093                 $definitions->{$column}->{null}    = $null;
1094                 $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
1095                 $definitions->{$column}->{key}     = $key;
1096                 $definitions->{$column}->{default} = $default;
1097                 $definitions->{$column}->{extra}   = $extra;
1098         }    # while
1099         my $fieldrow = $fielddefinitions{$table};
1100         foreach my $row (@$fieldrow) {
1101                 my $field   = $row->{field};
1102                 my $type    = $row->{type};
1103                 my $null    = $row->{null};
1104 #               $null    = 'YES' if $row->{null} eq 'NULL';
1105                 my $key     = $row->{key};
1106                 my $default = $row->{default};
1107                 my $null    = $row->{null};
1108 #               $default="''" unless $default;
1109                 my $extra   = $row->{extra};
1110                 my $def     = $definitions->{$field};
1111                 my $after       = ($row->{after}?" after ".$row->{after}:"");
1112
1113                 unless ( $type eq $def->{type}
1114                         && $null eq $def->{null}
1115                         && $key eq $def->{key}
1116                         && $extra eq $def->{extra} )
1117                 {
1118                         if ( $null eq '' ) {
1119                                 $null = 'NOT NULL';
1120                         }
1121                         if ( $key eq 'PRI' ) {
1122                                 $key = 'PRIMARY KEY';
1123                         }
1124                         unless ( $extra eq 'auto_increment' ) {
1125                                 $extra = '';
1126                         }
1127
1128                         # if it's a new column use "add", if it's an old one, use "change".
1129                         my $action;
1130                         if ($definitions->{$field}->{type}) {
1131                                 $action="change $field"
1132                         } else {
1133                                 $action="add";
1134                         }
1135 # if it's a primary key, drop the previous pk, before altering the table
1136                         my $sth;
1137                         if ($key ne 'PRIMARY KEY') {
1138                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ? $after");
1139                         } else {
1140                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ? $after");
1141                         }
1142                         $sth->execute($default);
1143                         print "  alter or create $field in $table\n" unless $silent;
1144                 }
1145         }
1146 }
1147
1148 # Populate tables with required data
1149
1150
1151 # synch table and deletedtable.
1152 foreach my $table (('borrowers','items','biblio','biblioitems')) {
1153         my %deletedborrowers;
1154         print "synch'ing $table\n";
1155         $sth = $dbh->prepare("show columns from deleted$table");
1156         $sth->execute;
1157         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
1158                 $deletedborrowers{$column}=1;
1159         }
1160         $sth = $dbh->prepare("show columns from $table");
1161         $sth->execute;
1162         my $previous;
1163         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
1164                 unless ($deletedborrowers{$column}) {
1165                         my $newcol="alter table deleted$table add $column $type";
1166                         if ($null eq 'YES') {
1167                                 $newcol .= " NULL ";
1168                         } else {
1169                                 $newcol .= " NOT NULL ";
1170                         }
1171                         $newcol .= "default $default" if $default;
1172                         $newcol .= " after $previous" if $previous;
1173                         $previous=$column;
1174                         print "creating column $column\n";
1175                         $dbh->do($newcol);
1176                 }
1177         }
1178 }
1179
1180 foreach my $table ( keys %tabledata ) {
1181     print "Checking for data required in table $table...\n" unless $silent;
1182     my $tablerows = $tabledata{$table};
1183     foreach my $row (@$tablerows) {
1184         my $uniquefieldrequired = $row->{uniquefieldrequired};
1185         my $uniquevalue         = $row->{$uniquefieldrequired};
1186         my $forceupdate         = $row->{forceupdate};
1187         my $sth                 =
1188           $dbh->prepare(
1189 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
1190         );
1191         $sth->execute($uniquevalue);
1192                 if ($sth->rows) {
1193                         foreach my $field (keys %$forceupdate) {
1194                                 if ($forceupdate->{$field}) {
1195                                         my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
1196                                         $sth->execute($row->{$field}, $uniquevalue);
1197                                 }
1198                 }
1199                 } else {
1200                         print "Adding row to $table: " unless $silent;
1201                         my @values;
1202                         my $fieldlist;
1203                         my $placeholders;
1204                         foreach my $field ( keys %$row ) {
1205                                 next if $field eq 'uniquefieldrequired';
1206                                 next if $field eq 'forceupdate';
1207                                 my $value = $row->{$field};
1208                                 push @values, $value;
1209                                 print "  $field => $value" unless $silent;
1210                                 $fieldlist .= "$field,";
1211                                 $placeholders .= "?,";
1212                         }
1213                         print "\n" unless $silent;
1214                         $fieldlist    =~ s/,$//;
1215                         $placeholders =~ s/,$//;
1216                         my $sth =
1217                         $dbh->prepare(
1218                                 "insert into $table ($fieldlist) values ($placeholders)");
1219                         $sth->execute(@values);
1220                 }
1221         }
1222 }
1223
1224 #
1225 # check indexes and create them when needed
1226 #
1227 print "Checking for index required...\n" unless $silent;
1228 foreach my $table ( keys %indexes ) {
1229         #
1230         # read all indexes from $table
1231         #
1232         $sth = $dbh->prepare("show index from $table");
1233         $sth->execute;
1234         my %existingindexes;
1235         while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow ) {
1236                 $existingindexes{$key_name} = 1;
1237         }
1238         # read indexes to check
1239         my $tablerows = $indexes{$table};
1240         foreach my $row (@$tablerows) {
1241                 my $key_name=$row->{indexname};
1242                 if ($existingindexes{$key_name} eq 1) {
1243 #                       print "$key_name existing";
1244                 } else {
1245                         print "\tCreating index $key_name in $table\n";
1246                         my $sql;
1247                         if ($row->{indexname} eq 'PRIMARY') {
1248                                 $sql = "alter table $table ADD PRIMARY KEY ($row->{content})";
1249                         } else {
1250                                 $sql = "alter table $table ADD INDEX $key_name ($row->{content}) $row->{type}";
1251                         }
1252                         $dbh->do($sql);
1253             print "Error $sql : $dbh->err \n" if $dbh->err;
1254                 }
1255         }
1256 }
1257
1258 #
1259 # check foreign keys and create them when needed
1260 #
1261 print "Checking for foreign keys required...\n" unless $silent;
1262 foreach my $table ( keys %foreign_keys ) {
1263         #
1264         # read all indexes from $table
1265         #
1266         $sth = $dbh->prepare("show table status like '$table'");
1267         $sth->execute;
1268         my $stat = $sth->fetchrow_hashref;
1269         # read indexes to check
1270         my $tablerows = $foreign_keys{$table};
1271         foreach my $row (@$tablerows) {
1272                 my $foreign_table=$row->{foreigntable};
1273                 if ($stat->{'Comment'} =~/$foreign_table/) {
1274 #                       print "$foreign_table existing\n";
1275                 } else {
1276                         print "\tCreating foreign key $foreign_table in $table\n";
1277                         # first, drop any orphan value in child table
1278                         if ($row->{onDelete} ne "RESTRICT") {
1279                                 my $sql = "delete from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})";
1280                                 $dbh->do($sql);
1281                                 print "SQL ERROR: $sql : $dbh->err \n" if $dbh->err;
1282                         }
1283                         my $sql="alter table $table ADD FOREIGN KEY $row->{key} ($row->{key}) REFERENCES $row->{foreigntable} ($row->{foreignkey})";
1284                         $sql .= " on update ".$row->{onUpdate} if $row->{onUpdate};
1285                         $sql .= " on delete ".$row->{onDelete} if $row->{onDelete};
1286                         $dbh->do($sql);
1287                         if ($dbh->err) {
1288                                 print "====================
1289 An error occured during :
1290 \t$sql
1291 It probably means there is something wrong in your DB : a row ($table.$row->{key}) refers to a value in $row->{foreigntable}.$row->{foreignkey} that does not exist. solve the problem and run updater again (or just the previous SQL statement).
1292 You can find those values with select
1293 \t$table.* from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})
1294 ====================\n
1295 ";
1296                         }
1297                 }
1298         }
1299 }
1300
1301 #
1302 # SPECIFIC STUFF
1303 #
1304 #
1305 # create frameworkcode row in biblio table & fill it with marc_biblio.frameworkcode.
1306 #
1307
1308 # 1st, get how many biblio we will have to do...
1309 $sth = $dbh->prepare('select count(*) from marc_biblio');
1310 $sth->execute;
1311 my ($totaltodo) = $sth->fetchrow;
1312
1313 $sth = $dbh->prepare("show columns from biblio");
1314 $sth->execute();
1315 my $definitions;
1316 my $bibliofwexist=0;
1317 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
1318         $bibliofwexist=1 if $column eq 'frameworkcode';
1319 }
1320 unless ($bibliofwexist) {
1321         print "moving biblioframework to biblio table\n";
1322         $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
1323         $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
1324         $sth->execute;
1325         my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
1326         my $totaldone=0;
1327         while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
1328                 $sth_update->execute($frameworkcode,$biblionumber);
1329                 $totaldone++;
1330                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
1331         }
1332         print "\rdone\n";
1333 }
1334
1335 #
1336 # moving MARC data from marc_subfield_table to biblioitems.marc
1337 #
1338 $sth = $dbh->prepare("show columns from biblioitems");
1339 $sth->execute();
1340 my $definitions;
1341 my $marcdone=0;
1342 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
1343         $marcdone=1 if ($type eq 'blob' && $column eq 'marc') ;
1344 }
1345 unless ($marcdone) {
1346         print "moving MARC record to biblioitems table\n";
1347         # changing marc field type
1348         $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` BLOB NULL DEFAULT NULL ');
1349         # adding marc xml, just for convenience
1350         $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ');
1351         # moving data from marc_subfield_value to biblio
1352         $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio');
1353         $sth->execute;
1354         my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?');
1355         my $totaldone=0;
1356         while (my ($bibid,$biblionumber) = $sth->fetchrow) {
1357                 my $record = MARCgetbiblio($dbh,$bibid);
1358         #Force UTF-8 in record leader
1359                 $record->encoding('UTF-8');
1360                 print $record->as_formatted if ($biblionumber==3902);
1361                 $sth_update->execute($record->as_usmarc(),$record->as_xml_record(),$biblionumber);
1362                 $totaldone++;
1363                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
1364         }
1365         print "\rdone\n";
1366 }
1367
1368
1369 # at last, remove useless fields
1370 foreach $table ( keys %uselessfields ) {
1371         my @fields = split /,/,$uselessfields{$table};
1372         my $fields;
1373         my $exists;
1374         foreach my $fieldtodrop (@fields) {
1375                 $fieldtodrop =~ s/\t//g;
1376                 $fieldtodrop =~ s/\n//g;
1377                 $exists =0;
1378                 $sth = $dbh->prepare("show columns from $table");
1379                 $sth->execute;
1380                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1381                 {
1382                         $exists =1 if ($column eq $fieldtodrop);
1383                 }
1384                 if ($exists) {
1385                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
1386                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
1387                         $sth->execute;
1388                 }
1389         }
1390 }    # foreach
1391
1392
1393 # MOVE all tables TO UTF-8 and innoDB
1394 $sth = $dbh->prepare("show table status");
1395 $sth->execute;
1396 while ( my $table = $sth->fetchrow_hashref ) {
1397 #       if ($table->{Engine} ne 'InnoDB') {
1398 #               $dbh->do("ALTER TABLE $table->{Name} TYPE = innodb");
1399 #               print "moving $table->{Name} to InnoDB\n";
1400 #       }
1401         unless ($table->{Collation} =~ /^utf8/) {
1402                 $dbh->do("ALTER TABLE $table->{Name} CONVERT TO CHARACTER SET utf8");
1403                 $dbh->do("ALTER TABLE $table->{Name} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
1404                 # FIXME : maybe a ALTER TABLE tbl_name CONVERT TO CHARACTER SET utf8 would be better, def char set seems to work fine. If any problem encountered, let's try with convert !
1405                 print "moving $table->{Name} to utf8\n";
1406         } else {
1407         }
1408 }
1409
1410 $sth->finish;
1411
1412 #
1413 # those 2 subs are a copy of Biblio.pm, version 2.2.4
1414 # they are useful only once, for moving from 2.2 to 3.0
1415 # the MARCgetbiblio & MARCgetitem subs in Biblio.pm
1416 # are still here, but uses other tables
1417 # (the ones that are filled by updatedatabase !)
1418 #
1419
1420 sub MARCgetbiblio {
1421
1422     # Returns MARC::Record of the biblio passed in parameter.
1423     my ( $dbh, $bibid ) = @_;
1424     my $record = MARC::Record->new();
1425 #       warn "". $bidid;
1426
1427     my $sth =
1428       $dbh->prepare(
1429 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
1430                                  from marc_subfield_table
1431                                  where bibid=? order by tag,tagorder,subfieldorder
1432                          "
1433     );
1434     my $sth2 =
1435       $dbh->prepare(
1436         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
1437     $sth->execute($bibid);
1438     my $prevtagorder = 1;
1439     my $prevtag      = 'XXX';
1440     my $previndicator;
1441     my $field;        # for >=10 tags
1442     my $prevvalue;    # for <10 tags
1443     while ( my $row = $sth->fetchrow_hashref ) {
1444
1445         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
1446             $sth2->execute( $row->{'valuebloblink'} );
1447             my $row2 = $sth2->fetchrow_hashref;
1448             $sth2->finish;
1449             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
1450         }
1451         if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
1452             $previndicator .= "  ";
1453             if ( $prevtag < 10 ) {
1454                                 if ($prevtag ne '000') {
1455                         $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
1456                                 } else {
1457                                         $record->leader(sprintf("%24s",$prevvalue));
1458                                 }
1459             }
1460             else {
1461                 $record->add_fields($field) unless $prevtag eq "XXX";
1462             }
1463             undef $field;
1464             $prevtagorder  = $row->{tagorder};
1465             $prevtag       = $row->{tag};
1466             $previndicator = $row->{tag_indicator};
1467             if ( $row->{tag} < 10 ) {
1468                 $prevvalue = $row->{subfieldvalue};
1469             }
1470             else {
1471                 $field = MARC::Field->new(
1472                     ( sprintf "%03s", $prevtag ),
1473                     substr( $row->{tag_indicator} . '  ', 0, 1 ),
1474                     substr( $row->{tag_indicator} . '  ', 1, 1 ),
1475                     $row->{'subfieldcode'},
1476                     $row->{'subfieldvalue'}
1477                 );
1478             }
1479         }
1480         else {
1481             if ( $row->{tag} < 10 ) {
1482                 $record->add_fields( ( sprintf "%03s", $row->{tag} ),
1483                     $row->{'subfieldvalue'} );
1484             }
1485             else {
1486                 $field->add_subfields( $row->{'subfieldcode'},
1487                     $row->{'subfieldvalue'} );
1488             }
1489             $prevtag       = $row->{tag};
1490             $previndicator = $row->{tag_indicator};
1491         }
1492     }
1493
1494     # the last has not been included inside the loop... do it now !
1495     if ( $prevtag ne "XXX" )
1496     { # check that we have found something. Otherwise, prevtag is still XXX and we
1497          # must return an empty record, not make MARC::Record fail because we try to
1498          # create a record with XXX as field :-(
1499         if ( $prevtag < 10 ) {
1500             $record->add_fields( $prevtag, $prevvalue );
1501         }
1502         else {
1503
1504             #           my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
1505             $record->add_fields($field);
1506         }
1507     }
1508     return $record;
1509 }
1510
1511 sub MARCgetitem {
1512
1513     # Returns MARC::Record of the biblio passed in parameter.
1514     my ( $dbh, $bibid, $itemnumber ) = @_;
1515     my $record = MARC::Record->new();
1516
1517     # search MARC tagorder
1518     my $sth2 =
1519       $dbh->prepare(
1520 "select tagorder from marc_subfield_table,marc_subfield_structure where marc_subfield_table.tag=marc_subfield_structure.tagfield and marc_subfield_table.subfieldcode=marc_subfield_structure.tagsubfield and bibid=? and kohafield='items.itemnumber' and subfieldvalue=?"
1521     );
1522     $sth2->execute( $bibid, $itemnumber );
1523     my ($tagorder) = $sth2->fetchrow_array();
1524
1525     #---- TODO : the leader is missing
1526     my $sth =
1527       $dbh->prepare(
1528 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
1529                                  from marc_subfield_table
1530                                  where bibid=? and tagorder=? order by subfieldcode,subfieldorder
1531                          "
1532     );
1533     $sth2 =
1534       $dbh->prepare(
1535         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
1536     $sth->execute( $bibid, $tagorder );
1537     while ( my $row = $sth->fetchrow_hashref ) {
1538         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
1539             $sth2->execute( $row->{'valuebloblink'} );
1540             my $row2 = $sth2->fetchrow_hashref;
1541             $sth2->finish;
1542             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
1543         }
1544         if ( $record->field( $row->{'tag'} ) ) {
1545             my $field;
1546
1547 #--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
1548             #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
1549             if ( length( $row->{'tag'} ) < 3 ) {
1550                 $row->{'tag'} = "0" . $row->{'tag'};
1551             }
1552             $field = $record->field( $row->{'tag'} );
1553             if ($field) {
1554                 my $x =
1555                   $field->add_subfields( $row->{'subfieldcode'},
1556                     $row->{'subfieldvalue'} );
1557                 $record->delete_field($field);
1558                 $record->add_fields($field);
1559             }
1560         }
1561         else {
1562             if ( length( $row->{'tag'} ) < 3 ) {
1563                 $row->{'tag'} = "0" . $row->{'tag'};
1564             }
1565             my $temp =
1566               MARC::Field->new( $row->{'tag'}, " ", " ",
1567                 $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
1568             $record->add_fields($temp);
1569         }
1570
1571     }
1572     return $record;
1573 }
1574
1575
1576 exit;
1577
1578 # $Log$
1579 # Revision 1.139  2006/05/19 19:31:29  tgarip1957
1580 # Added new fields to auth_header and auth_subfield_table to allow ZEBRA use of authorities and new MARC framework like structure.
1581 # Authority tables are modified to be compatible with new MARC frameworks. This change is part of Authority Linking & Zebra authorities. Requires change in Mysql database. It will break head unless all changes regarding this is implemented. This warning will take place on all commits regarding this
1582 #
1583 # Revision 1.138  2006/05/19 16:51:44  alaurin
1584 # update database for :
1585 # - new feature ip and printer management
1586 # adding two fields in branches table (branchip,branchprinter)
1587 #
1588 # - waiting date : adding one field in reserves table(waiting date) to calculate the Maximum delay to pick up a reserved document when it's available
1589 #
1590 # new system preference :
1591 # - ReservesMaxPickUpDelay : Maximum delay to pick up a reserved document
1592 # TransfersMaxDaysWarning : Max delay before considering the transfer as potentialy a problem
1593 #
1594 # Revision 1.137  2006/04/18 09:36:36  plg
1595 # bug fixed: typo fixed in labels and labels_conf tables creation query.
1596 #
1597 # Revision 1.136  2006/04/17 21:55:33  sushi
1598 # Added 'labels' and 'labels_conf' tables, for spine lable tool.
1599 #
1600 # Revision 1.135  2006/04/15 02:37:03  tgarip1957
1601 # Marc record should be set to UTF-8 in leader.Force it.
1602 # XML should be with<record> wrappers
1603 #
1604 # Revision 1.134  2006/04/14 09:37:29  tipaul
1605 # improvements from SAN Ouest Provence :
1606 # * introducing a category_type into categories. It can be A (adult), C (children), P (Professionnal), I (institution/organisation).
1607 # * each category_type has it's own forms to create members.
1608 # * the borrowers table has been heavily modified (many fields changed), to get something more logic & readable
1609 # * reintroducing guarantor/guanrantee system that is now independant from hardcoded C/A for categories
1610 # * updating templates to fit template rules
1611 #
1612 # (see mail feb, 17 on koha-devel "new features for borrowers" for more details)
1613 #
1614 # Revision 1.133  2006/04/13 08:36:42  plg
1615 # new: function C4::Date::get_date_format_string_for_DHTMLcalendar based on
1616 # the system preference prefered date format.
1617 #
1618 # improvement: book fund list and budget list screen redesigned. Filters on
1619 # each field. Columns are not sortable yet. Using DHTML Calendar to fill date
1620 # fields instead of manual filling. Pagination system. From the book fund
1621 # list, you can reach the budget list, filtered on a book fund, or not. A
1622 # budget can be added only from book fund list screen.
1623 #
1624 # bug fixed: branchcode was missing in table aqbudget.
1625 #
1626 # bug fixed: when setting a branchcode to a book fund, all associated budgets
1627 # move to this branchcode.
1628 #
1629 # modification: when adding/modifying budget/fund, MySQL specific "REPLACE..."
1630 # statements replaced by standard SQL compliant statement.
1631 #
1632 # bug fixed: when adding/modifying a budget, if the book fund is associated to
1633 # a branch, the branch selection is disabled and set to the book fund branch.
1634 #
1635 # Revision 1.132  2006/04/06 12:37:05  hdl
1636 # Bugfixing : aqbookfund needed a field.
1637 #
1638 # Revision 1.131  2006/03/03 17:02:22  tipaul
1639 # commit for holidays and news management.
1640 # (some forgotten files)
1641 #
1642 # Revision 1.130  2006/03/03 16:35:21  tipaul
1643 # commit for holidays and news management.
1644 #
1645 # Contrib from Tümer Garip (from Turkey) :
1646 # * holiday :
1647 # in /tools/ the holiday.pl script let you define holidays (days where the library is closed), branch by branch. You can define 3 types of holidays :
1648 # - single day : only this day is closed
1649 # - repet weekly (like "sunday") : the day is holiday every week
1650 # - repet yearly (like "July, 4") : this day is closed every year.
1651 #
1652 # You can also put exception :
1653 # - sunday is holiday, but "2006 March, 5th" the library will be open
1654 #
1655 # The holidays are used for return date calculation : the return date is set to the next date where the library is open. A systempreference (useDaysMode) set ON (Calendar) or OFF (Normal) the calendar calculation.
1656 #
1657 # Revision 1.129  2006/02/27 18:19:33  hdl
1658 # New table used in overduerules.pl tools page.
1659 #
1660 # Revision 1.128  2006/01/25 15:16:06  tipaul
1661 # updating DB :
1662 # * removing useless tables
1663 # * adding useful indexes
1664 # * altering some columns definitions
1665 # * The goal being to have updater working fine for foreign keys.
1666 #
1667 # For me it's done, let me know if it works for you. You can see an updated schema of the DB (with constraints) on the wiki
1668 #
1669 # Revision 1.127  2006/01/24 17:57:17  tipaul
1670 # DB improvements : adding foreign keys on some tables. partial stuff done.
1671 #
1672 # Revision 1.126  2006/01/06 16:39:42  tipaul
1673 # synch'ing head and rel_2_2 (from 2.2.5, including npl templates)
1674 # Seems not to break too many things, but i'm probably wrong here.
1675 # at least, new features/bugfixes from 2.2.5 are here (tested on some features on my head local copy)
1676 #
1677 # - removing useless directories (koha-html and koha-plucene)
1678 #
1679 # Revision 1.125  2006/01/04 15:54:55  tipaul
1680 # utf8 is a : go for beta test in HEAD.
1681 # some explanations :
1682 # - updater/updatedatabase => will transform all tables in innoDB (not related to utf8, just to warn you) AND collate them in utf8 / utf8_general_ci. The SQL command is : ALTER TABLE tablename DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci.
1683 # - *-top.inc will show the pages in utf8
1684 # - THE HARD THING : for me, mysql-client and mysql-server were set up to communicate in iso8859-1, whatever the mysql collation ! Thus, pages were improperly shown, as datas were transmitted in iso8859-1 format ! After a full day of investigation, someone on usenet pointed "set NAMES 'utf8'" to explain that I wanted utf8. I could put this in my.cnf, but if I do that, ALL databases will "speak" in utf8, that's not what we want. Thus, I added a line in Context.pm : everytime a DB handle is opened, the communication is set to utf8.
1685 # - using marcxml field and no more the iso2709 raw marc biblioitems.marc field.
1686 #
1687 # Revision 1.124  2005/10/27 12:09:05  tipaul
1688 # new features for serial module :
1689 # - the last 5 issues are now shown, and their status can be changed (but not reverted to "waited", as there can be only one "waited")
1690 # - the library can create a "distribution list". this paper contains a list of borrowers (selected from the borrower list, or manually entered), and print it for a given issue. once printed, the sheet can be put on the issue and distributed to every reader on the list (one by one).
1691 #
1692 # Revision 1.123  2005/10/26 09:13:37  tipaul
1693 # big commit, still breaking things...
1694 #
1695 # * synch with rel_2_2. Probably the last non manual synch, as rel_2_2 should not be modified deeply.
1696 # * code cleaning (cleaning warnings from perl -w) continued
1697 #
1698 # Revision 1.122  2005/09/02 14:18:38  tipaul
1699 # new feature : image for itemtypes.
1700 #
1701 # * run updater/updatedatabase to create imageurl field in itemtypes.
1702 # * go to Koha >> parameters >> itemtypes >> modify (or add) an itemtype. You will see around 20 nice images to choose between (thanks to owen). If you prefer your own image, you also can type a complete url (http://www.myserver.lib/path/to/my/image.gif)
1703 # * go to OPAC, and search something. In the result list, you now have the picture instead of the text itemtype.
1704 #
1705 # Revision 1.121  2005/08/24 08:49:03  hdl
1706 # Adding a note field in serial table.
1707 # This will allow librarian to mention a note on a peculiar waiting serial number.
1708 #
1709 # Revision 1.120  2005/08/09 14:10:32  tipaul
1710 # 1st commit to go to zebra.
1711 # don't update your cvs if you want to have a working head...
1712 #
1713 # this commit contains :
1714 # * updater/updatedatabase : get rid with marc_* tables, but DON'T remove them. As a lot of things uses them, it would not be a good idea for instance to drop them. If you really want to play, you can rename them to test head without them but being still able to reintroduce them...
1715 # * Biblio.pm : modify MARCgetbiblio to find the raw marc record in biblioitems.marc field, not from marc_subfield_table, modify MARCfindframeworkcode to find frameworkcode in biblio.frameworkcode, modify some other subs to use biblio.biblionumber & get rid of bibid.
1716 # * other files : get rid of bibid and use biblionumber instead.
1717 #
1718 # What is broken :
1719 # * does not do anything on zebra yet.
1720 # * if you rename marc_subfield_table, you can't search anymore.
1721 # * you can view a biblio & bibliodetails, go to MARC editor, but NOT save any modif.
1722 # * don't try to add a biblio, it would add data poorly... (don't try to delete either, it may work, but that would be a surprise ;-) )
1723 #
1724 # IMPORTANT NOTE : you need MARC::XML package (http://search.cpan.org/~esummers/MARC-XML-0.7/lib/MARC/File/XML.pm), that requires a recent version of MARC::Record
1725 # Updatedatabase stores the iso2709 data in biblioitems.marc field & an xml version in biblioitems.marcxml Not sure we will keep it when releasing the stable version, but I think it's a good idea to have something readable in sql, at least for development stage.
1726 #
1727 # Revision 1.119  2005/08/04 16:07:58  tipaul
1728 # Synch really broke this script...
1729 #
1730 # Revision 1.118  2005/08/04 16:02:55  tipaul
1731 # oops... error in synch between 2.2 and head
1732 #
1733 # Revision 1.117  2005/08/04 14:24:39  tipaul
1734 # synch'ing 2.2 and head
1735 #
1736 # Revision 1.116  2005/08/04 08:55:54  tipaul
1737 # Letters / alert system, continuing...
1738 #
1739 # * adding a package Letters.pm, that manages Letters & alerts.
1740 # * adding feature : it's now possible to define a "letter" for any subscription created. If a letter is defined, users in OPAC can put an alert on the subscription. When an issue is marked "arrived", all users in the alert will recieve a mail (as defined in the "letter"). This last part (= send the mail) is not yet developped. (Should be done this week)
1741 # * adding feature : it's now possible to "put to an alert" in OPAC, for any serial subscription. The alert is stored in a new table, called alert. An alert can be put only if the librarian has activated them in subscription (and they activate it just by choosing a "letter" to sent to borrowers on new issues)
1742 # * adding feature : librarian can see in borrower detail which alerts they have put, and a user can see in opac-detail which alert they have put too.
1743 #
1744 # Note that the system should be generic enough to manage any type of alert.
1745 # I plan to extend it soon to virtual shelves : a borrower will be able to put an alert on a virtual shelf, to be warned when something is changed in the virtual shelf (mail being sent once a day by cron, or manually by the shelf owner. Anyway, a mail won't be sent on every change, users would be spammed by Koha ;-) )
1746 #
1747 # Revision 1.115  2005/08/02 16:15:34  tipaul
1748 # adding 2 fields to letter system :
1749 # * module (acquisition, catalogue...) : it will be usefull to show the librarian only letters he may be interested by.
1750 # * title, that will be used as mail subject.
1751 #
1752 # Revision 1.114  2005/07/28 15:10:13  tipaul
1753 # Introducing new "Letters" system : Letters will be used everytime you want to sent something to someone (through mail or paper). For example, sending a mail for overdues use letter that you can put as parameters. Sending a mail to a borrower when a suggestion is validated uses a letter too.
1754 # the letter table contains 3 fields :
1755 # * code => the code of the letter
1756 # * name => the complete name of the letter
1757 # * content => the complete text. It's a TEXT field type, so has no limits.
1758 #
1759 # My next goal now is to work on point 2-I "serial issue alert"
1760 # With this feature, in serials, a user can subscribe the "issue alert". For every issue arrived/missing, a mail is sent to all subscribers of this list. The mail warns the user that the issue is arrive or missing. Will be in head.
1761 # (see mail on koha-devel, 2005/04/07)
1762 #
1763 # The "serial issue alert" will be the 1st to use this letter system that probably needs some tweaking ;-)
1764 #
1765 # Once it will be stabilised default letters (in any languages) could be added during installer to help the library begin with this new feature.
1766 #
1767 # Revision 1.113  2005/07/28 08:38:41  tipaul
1768 # For instance, the return date does not rely on the borrower expiration date. A systempref will be added in Koha, to modify return date calculation schema :
1769 # * ReturnBeforeExpiry = yes => return date can't be after expiry date
1770 # * ReturnBeforeExpiry = no  => return date can be after expiry date
1771 #
1772 # Revision 1.112  2005/07/26 08:19:47  hdl
1773 # Adding IndependantBranches System preference variable in order to manage Branch independancy.
1774 #
1775 # Revision 1.111  2005/07/25 15:35:38  tipaul
1776 # we have decided that moving to Koha 3.0 requires being already in Koha 2.2.x
1777 # So, the updatedatabase script can highly be cleaned (90% removed).
1778 # Let's play with the new Koha DB structure now ;-)
1779 #