Adding new systempreference allowing for the library to add borrowers to institutions...
[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             uniquefieldrequired => 'variable',
422             variable            => 'memberofinstitution',
423             value               => '0',
424             forceupdate         => { 'explanation' => 1,
425                                      'type' => 1},
426             explanation         => 'Are your patrons members of institutions',
427             type                => 'YesNo',
428         },
429     ],
430
431 );
432
433 my %fielddefinitions = (
434 # fieldname => [
435 #       {                 field => 'fieldname',
436 #             type    => 'fieldtype',
437 #             null    => '',
438 #             key     => '',
439 #             default => ''
440 #         },
441 #     ],
442         serial => [
443         {
444             field   => 'notes',
445             type    => 'TEXT',
446             null    => 'NULL',
447             key     => '',
448             default => '',
449             extra   => ''
450         },
451     ],
452         aqbasket =>  [
453                 {
454                         field   => 'booksellerid',
455                         type    => 'int(11)',
456                         null    => 'NOT NULL',
457                         key             => '',
458                         default => '1',
459                         extra   => '',
460                 },
461         ],
462         aqbooksellers =>  [
463                 {
464                         field   => 'listprice',
465                         type    => 'varchar(10)',
466                         null    => 'NULL',
467                         key             => '',
468                         default => '',
469                         extra   => '',
470                 },
471                 {
472                         field   => 'invoiceprice',
473                         type    => 'varchar(10)',
474                         null    => 'NULL',
475                         key             => '',
476                         default => '',
477                         extra   => '',
478                 },
479         ],
480         issues =>  [
481                 {
482                         field   => 'borrowernumber',
483                         type    => 'int(11)',
484                         null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
485                         key             => '',
486                         default => '',
487                         extra   => '',
488                 },
489                 {
490                         field   => 'itemnumber',
491                         type    => 'int(11)',
492                         null    => 'NULL', # can be null when a borrower is deleted and the foreign key rule executed
493                         key             => '',
494                         default => '',
495                         extra   => '',
496                 },
497         ],
498         borrowers => [
499                 {       field => 'B_email',
500                         type => 'text',
501                         null => 'NULL',
502                         after => 'B_zipcode',
503                  },
504                  {
505                         field => 'streetnumber', # street number (hidden if streettable table is empty)
506                         type => 'char(10)',
507                         null => 'NULL',
508                         after => 'initials',
509                 },
510                 {
511                         field => 'streettype', # street table, list builded from a system table
512                         type => 'char(50)',
513                         null => 'NULL',
514                         after => 'streetnumber',
515                 },
516                  {
517                         field => 'B_streetnumber', # street number (hidden if streettable table is empty)
518                         type => 'char(10)',
519                         null => 'NULL',
520                         after => 'fax',
521                 },
522                 {
523                         field => 'B_streettype', # street table, list builded from a system table
524                         type => 'char(50)',
525                         null => 'NULL',
526                         after => 'B_streetnumber',
527                 },
528                 {
529                         field => 'phonepro',
530                         type => 'text',
531                         null => 'NULL',
532                         after => 'fax',
533                 },
534                 {
535                         field => 'address2', # complement address
536                         type => 'text',
537                         null => 'NULL',
538                         after => 'address',
539                 },
540                 {
541                         field => 'emailpro',
542                         type => 'text',
543                         null => 'NULL',
544                         after => 'fax',
545                 },
546                 {
547                         field => 'contactfirstname', # contact's firstname
548                         type => 'text',
549                         null => 'NULL',
550                         after => 'contactname',
551                 },
552                 {
553                         field => 'contacttitle', # contact's title
554                         type => 'text',
555                         null => 'NULL',
556                         after => 'contactfirstname',
557                 },
558         ],
559         
560         branches =>  [
561                 {
562                         field   => 'branchip',
563                         type    => 'varchar(15)',
564                         null    => 'NULL',
565                         key             => '',
566                         default => '',
567                         extra   => '',
568                 },
569                 {
570                         field   => 'branchprinter',
571                         type    => 'varchar(100)',
572                         null    => 'NULL',
573                         key             => '',
574                         default => '',
575                         extra   => '',
576                 },
577         ],
578         categories =>  [
579                 {
580                         field   => 'category_type',
581                         type    => 'char(1)',
582                         null    => 'NOT NULL',
583                         key             => '',
584                         default => 'A',
585                         extra   => '',
586                 },
587         ],
588         reserves =>  [
589                 {
590                         field   => 'waitingdate',
591                         type    => 'date',
592                         null    => 'NULL',
593                         key             => '',
594                         default => '',
595                         extra   => '',
596                 },
597         ],
598 );
599
600 my %indexes = (
601 #       table => [
602 #               {       indexname => 'index detail'
603 #               }
604 #       ],
605         shelfcontents => [
606                 {       indexname => 'shelfnumber',
607                         content => 'shelfnumber',
608                 },
609                 {       indexname => 'itemnumber',
610                         content => 'itemnumber',
611                 }
612         ],
613         bibliosubject => [
614                 {       indexname => 'biblionumber',
615                         content => 'biblionumber',
616                 }
617         ],
618         items => [
619                 {       indexname => 'homebranch',
620                         content => 'homebranch',
621                 },
622                 {       indexname => 'holdingbranch',
623                         content => 'holdingbranch',
624                 }
625         ],
626         aqbooksellers => [
627                 {       indexname => 'PRIMARY',
628                         content => 'id',
629                         type => 'PRIMARY',
630                 }
631         ],
632         aqbasket => [
633                 {       indexname => 'booksellerid',
634                         content => 'booksellerid',
635                 },
636         ],
637         aqorders => [
638                 {       indexname => 'basketno',
639                         content => 'basketno',
640                 },
641         ],
642         aqorderbreakdown => [
643                 {       indexname => 'ordernumber',
644                         content => 'ordernumber',
645                 },
646                 {       indexname => 'bookfundid',
647                         content => 'bookfundid',
648                 },
649         ],
650         currency => [
651                 {       indexname => 'PRIMARY',
652                         content => 'currency',
653                         type => 'PRIMARY',
654                 }
655         ],
656 );
657
658 my %foreign_keys = (
659 #       table => [
660 #               {       key => 'the key in table' (must be indexed)
661 #                       foreigntable => 'the foreigntable name', # (the parent)
662 #                       foreignkey => 'the foreign key column(s)' # (in the parent)
663 #                       onUpdate => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
664 #                       onDelete => 'CASCADE|SET NULL|NO ACTION| RESTRICT',
665 #               }
666 #       ],
667         shelfcontents => [
668                 {       key => 'shelfnumber',
669                         foreigntable => 'bookshelf',
670                         foreignkey => 'shelfnumber',
671                         onUpdate => 'CASCADE',
672                         onDelete => 'CASCADE',
673                 },
674                 {       key => 'itemnumber',
675                         foreigntable => 'items',
676                         foreignkey => 'itemnumber',
677                         onUpdate => 'CASCADE',
678                         onDelete => 'CASCADE',
679                 },
680         ],
681         # onDelete is RESTRICT on reference tables (branches, itemtype) as we don't want items to be 
682         # easily deleted, but branches/itemtype not too easy to empty...
683         biblioitems => [
684                 {       key => 'biblionumber',
685                         foreigntable => 'biblio',
686                         foreignkey => 'biblionumber',
687                         onUpdate => 'CASCADE',
688                         onDelete => 'CASCADE',
689                 },
690                 {       key => 'itemtype',
691                         foreigntable => 'itemtypes',
692                         foreignkey => 'itemtype',
693                         onUpdate => 'CASCADE',
694                         onDelete => 'RESTRICT',
695                 },
696         ],
697         items => [
698                 {       key => 'biblioitemnumber',
699                         foreigntable => 'biblioitems',
700                         foreignkey => 'biblioitemnumber',
701                         onUpdate => 'CASCADE',
702                         onDelete => 'CASCADE',
703                 },
704                 {       key => 'homebranch',
705                         foreigntable => 'branches',
706                         foreignkey => 'branchcode',
707                         onUpdate => 'CASCADE',
708                         onDelete => 'RESTRICT',
709                 },
710                 {       key => 'holdingbranch',
711                         foreigntable => 'branches',
712                         foreignkey => 'branchcode',
713                         onUpdate => 'CASCADE',
714                         onDelete => 'RESTRICT',
715                 },
716         ],
717         additionalauthors => [
718                 {       key => 'biblionumber',
719                         foreigntable => 'biblio',
720                         foreignkey => 'biblionumber',
721                         onUpdate => 'CASCADE',
722                         onDelete => 'CASCADE',
723                 },
724         ],
725         bibliosubject => [
726                 {       key => 'biblionumber',
727                         foreigntable => 'biblio',
728                         foreignkey => 'biblionumber',
729                         onUpdate => 'CASCADE',
730                         onDelete => 'CASCADE',
731                 },
732         ],
733         aqbasket => [
734                 {       key => 'booksellerid',
735                         foreigntable => 'aqbooksellers',
736                         foreignkey => 'id',
737                         onUpdate => 'CASCADE',
738                         onDelete => 'RESTRICT',
739                 },
740         ],
741         aqorders => [
742                 {       key => 'basketno',
743                         foreigntable => 'aqbasket',
744                         foreignkey => 'basketno',
745                         onUpdate => 'CASCADE',
746                         onDelete => 'CASCADE',
747                 },
748                 {       key => 'biblionumber',
749                         foreigntable => 'biblio',
750                         foreignkey => 'biblionumber',
751                         onUpdate => 'SET NULL',
752                         onDelete => 'SET NULL',
753                 },
754         ],
755         aqbooksellers => [
756                 {       key => 'listprice',
757                         foreigntable => 'currency',
758                         foreignkey => 'currency',
759                         onUpdate => 'CASCADE',
760                         onDelete => 'CASCADE',
761                 },
762                 {       key => 'invoiceprice',
763                         foreigntable => 'currency',
764                         foreignkey => 'currency',
765                         onUpdate => 'CASCADE',
766                         onDelete => 'CASCADE',
767                 },
768         ],
769         aqorderbreakdown => [
770                 {       key => 'ordernumber',
771                         foreigntable => 'aqorders',
772                         foreignkey => 'ordernumber',
773                         onUpdate => 'CASCADE',
774                         onDelete => 'CASCADE',
775                 },
776                 {       key => 'bookfundid',
777                         foreigntable => 'aqbookfund',
778                         foreignkey => 'bookfundid',
779                         onUpdate => 'CASCADE',
780                         onDelete => 'CASCADE',
781                 },
782         ],
783         branchtransfers => [
784                 {       key => 'frombranch',
785                         foreigntable => 'branches',
786                         foreignkey => 'branchcode',
787                         onUpdate => 'CASCADE',
788                         onDelete => 'CASCADE',
789                 },
790                 {       key => 'tobranch',
791                         foreigntable => 'branches',
792                         foreignkey => 'branchcode',
793                         onUpdate => 'CASCADE',
794                         onDelete => 'CASCADE',
795                 },
796                 {       key => 'itemnumber',
797                         foreigntable => 'items',
798                         foreignkey => 'itemnumber',
799                         onUpdate => 'CASCADE',
800                         onDelete => 'CASCADE',
801                 },
802         ],
803         issuingrules => [
804                 {       key => 'categorycode',
805                         foreigntable => 'categories',
806                         foreignkey => 'categorycode',
807                         onUpdate => 'CASCADE',
808                         onDelete => 'CASCADE',
809                 },
810                 {       key => 'itemtype',
811                         foreigntable => 'itemtypes',
812                         foreignkey => 'itemtype',
813                         onUpdate => 'CASCADE',
814                         onDelete => 'CASCADE',
815                 },
816         ],
817         issues => [     # constraint is SET NULL : when a borrower or an item is deleted, we keep the issuing record
818         # for stat purposes
819                 {       key => 'borrowernumber',
820                         foreigntable => 'borrowers',
821                         foreignkey => 'borrowernumber',
822                         onUpdate => 'SET NULL',
823                         onDelete => 'SET NULL',
824                 },
825                 {       key => 'itemnumber',
826                         foreigntable => 'items',
827                         foreignkey => 'itemnumber',
828                         onUpdate => 'SET NULL',
829                         onDelete => 'SET NULL',
830                 },
831         ],
832         reserves => [
833                 {       key => 'borrowernumber',
834                         foreigntable => 'borrowers',
835                         foreignkey => 'borrowernumber',
836                         onUpdate => 'CASCADE',
837                         onDelete => 'CASCADE',
838                 },
839                 {       key => 'biblionumber',
840                         foreigntable => 'biblio',
841                         foreignkey => 'biblionumber',
842                         onUpdate => 'CASCADE',
843                         onDelete => 'CASCADE',
844                 },
845                 {       key => 'itemnumber',
846                         foreigntable => 'items',
847                         foreignkey => 'itemnumber',
848                         onUpdate => 'CASCADE',
849                         onDelete => 'CASCADE',
850                 },
851                 {       key => 'branchcode',
852                         foreigntable => 'branches',
853                         foreignkey => 'branchcode',
854                         onUpdate => 'CASCADE',
855                         onDelete => 'CASCADE',
856                 },
857         ],
858         borrowers => [ # foreign keys are RESTRICT as we don't want to delete borrowers when a branch is deleted
859         # but prevent deleting a branch as soon as it has 1 borrower !
860                 {       key => 'categorycode',
861                         foreigntable => 'categories',
862                         foreignkey => 'categorycode',
863                         onUpdate => 'RESTRICT',
864                         onDelete => 'RESTRICT',
865                 },
866                 {       key => 'branchcode',
867                         foreigntable => 'branches',
868                         foreignkey => 'branchcode',
869                         onUpdate => 'RESTRICT',
870                         onDelete => 'RESTRICT',
871                 },
872         ],
873         accountlines => [
874                 {       key => 'borrowernumber',
875                         foreigntable => 'borrowers',
876                         foreignkey => 'borrowernumber',
877                         onUpdate => 'CASCADE',
878                         onDelete => 'CASCADE',
879                 },
880                 {       key => 'itemnumber',
881                         foreigntable => 'items',
882                         foreignkey => 'itemnumber',
883                         onUpdate => 'SET NULL',
884                         onDelete => 'SET NULL',
885                 },
886         ],
887         auth_tag_structure => [
888                 {       key => 'authtypecode',
889                         foreigntable => 'auth_types',
890                         foreignkey => 'authtypecode',
891                         onUpdate => 'CASCADE',
892                         onDelete => 'CASCADE',
893                 },
894         ],
895         # FIXME : don't constraint auth_*_table and auth_word, as they may be replaced by zebra
896 );
897
898
899 # column changes
900 my %column_change = (
901         # table
902         borrowers => [
903                                 {
904                                         from => 'emailaddress',
905                                         to => 'email',
906                                         after => 'city',
907                                 },
908                                 {
909                                         from => 'streetaddress',
910                                         to => 'address',
911                                         after => 'initials',
912                                 },
913                                 {
914                                         from => 'faxnumber',
915                                         to => 'fax',
916                                         after => 'phone',
917                                 },
918                                 {
919                                         from => 'textmessaging',
920                                         to => 'opacnote',
921                                         after => 'userid',
922                                 },
923                                 {
924                                         from => 'altnotes',
925                                         to => 'contactnote',
926                                         after => 'opacnote',
927                                 },
928                                 {
929                                         from => 'physstreet',
930                                         to => 'B_address',
931                                         after => 'fax',
932                                 },
933                                 {
934                                         from => 'streetcity',
935                                         to => 'B_city',
936                                         after => 'B_address',
937                                 },
938                                 {
939                                         from => 'phoneday',
940                                         to => 'mobile',
941                                         after => 'phone',
942                                 },
943                                 {
944                                         from => 'zipcode',
945                                         to => 'zipcode',
946                                         after => 'city',
947                                 },
948                                 {
949                                         from => 'homezipcode',
950                                         to => 'B_zipcode',
951                                         after => 'B_city',
952                                 },
953                                 {
954                                         from => 'altphone',
955                                         to => 'B_phone',
956                                         after => 'B_zipcode',
957                                 },
958                                 {
959                                         from => 'expiry',
960                                         to => 'dateexpiry',
961                                         after => 'dateenrolled',
962                                 },
963                                 {
964                                         from => 'guarantor',
965                                         to => 'guarantorid',
966                                         after => 'contactname',
967                                 },
968                                 {
969                                         from => 'textmessaging',
970                                         to => 'opacnotes',
971                                         after => 'flags',
972                                 },
973                                 {
974                                         from => 'altnotes',
975                                         to => 'contactnotes',
976                                         after => 'opacnotes',
977                                 },
978                                 {
979                                         from => 'altrelationship',
980                                         to => 'relationship',
981                                         after => 'borrowernotes',
982                                 },
983                         ],
984                 );
985                 
986 foreach my $table (keys %column_change) {
987         $sth = $dbh->prepare("show columns from $table");
988         $sth->execute();
989         undef %types;
990         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
991         {
992                 $types{$column}->{type} ="$type";
993                 $types{$column}->{null} = "$null";
994                 $types{$column}->{key} = "$key";
995                 $types{$column}->{default} = "$default";
996                 $types{$column}->{extra} = "$extra";
997         }    # while
998         my $tablerows = $column_change{$table};
999         foreach my $row ( @$tablerows ) {
1000                 if ($types{$row->{from}}->{type}) {
1001                         print "altering $table $row->{from} to $row->{to}\n";
1002                         # ALTER TABLE `borrowers` CHANGE `faxnumber` `fax` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL 
1003 #                       alter table `borrowers` change `faxnumber` `fax` type text  null after phone
1004                         my $sql = 
1005                                 "alter table `$table` change `$row->{from}` `$row->{to}` $types{$row->{from}}->{type} ".
1006                                 ($types{$row->{from}}->{null} eq 'YES'?" NULL":" NOT NULL").
1007                                 ($types{$row->{from}}->{default}?" default ".$types{$row->{from}}->{default}:"").
1008                                 "$types{$row->{from}}->{extra} after $row->{after} ";
1009 #                       print "$sql";
1010                         $dbh->do($sql);
1011                 }
1012         }
1013 }
1014
1015 #-------------------
1016 # Initialize
1017
1018 # Start checking
1019
1020 # Get version of MySQL database engine.
1021 my $mysqlversion = `mysqld --version`;
1022 $mysqlversion =~ /Ver (\S*) /;
1023 $mysqlversion = $1;
1024 if ( $mysqlversion ge '3.23' ) {
1025     print "Could convert to MyISAM database tables...\n" unless $silent;
1026 }
1027
1028 #---------------------------------
1029 # Tables
1030
1031 # Collect all tables into a list
1032 $sth = $dbh->prepare("show tables");
1033 $sth->execute;
1034 while ( my ($table) = $sth->fetchrow ) {
1035     $existingtables{$table} = 1;
1036 }
1037
1038
1039 # Now add any missing tables
1040 foreach $table ( keys %requiretables ) {
1041     unless ( $existingtables{$table} ) {
1042         print "Adding $table table...\n" unless $silent;
1043         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
1044         $sth->execute;
1045         if ( $sth->err ) {
1046             print "Error : $sth->errstr \n";
1047             $sth->finish;
1048         }    # if error
1049     }    # unless exists
1050 }    # foreach
1051
1052 # now drop useless tables
1053 foreach $table ( keys %dropable_table ) {
1054         if ( $existingtables{$table} ) {
1055                 print "Dropping unused table $table\n" if $debug and not $silent;
1056                 $dbh->do("drop table $table");
1057                 if ( $dbh->err ) {
1058                         print "Error : $dbh->errstr \n";
1059                 }
1060         }
1061 }
1062
1063 #---------------------------------
1064 # Columns
1065
1066 foreach $table ( keys %requirefields ) {
1067     print "Check table $table\n" if $debug and not $silent;
1068     $sth = $dbh->prepare("show columns from $table");
1069     $sth->execute();
1070     undef %types;
1071     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1072     {
1073         $types{$column} = $type;
1074     }    # while
1075     foreach $column ( keys %{ $requirefields{$table} } ) {
1076         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
1077         if ( !$types{$column} ) {
1078
1079             # column doesn't exist
1080             print "Adding $column field to $table table...\n" unless $silent;
1081             $query = "alter table $table
1082                         add column $column " . $requirefields{$table}->{$column};
1083             print "Execute: $query\n" if $debug;
1084             my $sti = $dbh->prepare($query);
1085             $sti->execute;
1086             if ( $sti->err ) {
1087                 print "**Error : $sti->errstr \n";
1088                 $sti->finish;
1089             }    # if error
1090         }    # if column
1091     }    # foreach column
1092 }    # foreach table
1093
1094 foreach $table ( keys %fielddefinitions ) {
1095         print "Check table $table\n" if $debug;
1096         $sth = $dbh->prepare("show columns from $table");
1097         $sth->execute();
1098         my $definitions;
1099         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1100         {
1101                 $definitions->{$column}->{type}    = $type;
1102                 $definitions->{$column}->{null}    = $null;
1103                 $definitions->{$column}->{null}    = 'NULL' if $null eq 'YES';
1104                 $definitions->{$column}->{key}     = $key;
1105                 $definitions->{$column}->{default} = $default;
1106                 $definitions->{$column}->{extra}   = $extra;
1107         }    # while
1108         my $fieldrow = $fielddefinitions{$table};
1109         foreach my $row (@$fieldrow) {
1110                 my $field   = $row->{field};
1111                 my $type    = $row->{type};
1112                 my $null    = $row->{null};
1113 #               $null    = 'YES' if $row->{null} eq 'NULL';
1114                 my $key     = $row->{key};
1115                 my $default = $row->{default};
1116                 my $null    = $row->{null};
1117 #               $default="''" unless $default;
1118                 my $extra   = $row->{extra};
1119                 my $def     = $definitions->{$field};
1120                 my $after       = ($row->{after}?" after ".$row->{after}:"");
1121
1122                 unless ( $type eq $def->{type}
1123                         && $null eq $def->{null}
1124                         && $key eq $def->{key}
1125                         && $extra eq $def->{extra} )
1126                 {
1127                         if ( $null eq '' ) {
1128                                 $null = 'NOT NULL';
1129                         }
1130                         if ( $key eq 'PRI' ) {
1131                                 $key = 'PRIMARY KEY';
1132                         }
1133                         unless ( $extra eq 'auto_increment' ) {
1134                                 $extra = '';
1135                         }
1136
1137                         # if it's a new column use "add", if it's an old one, use "change".
1138                         my $action;
1139                         if ($definitions->{$field}->{type}) {
1140                                 $action="change $field"
1141                         } else {
1142                                 $action="add";
1143                         }
1144 # if it's a primary key, drop the previous pk, before altering the table
1145                         my $sth;
1146                         if ($key ne 'PRIMARY KEY') {
1147                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ? $after");
1148                         } else {
1149                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ? $after");
1150                         }
1151                         $sth->execute($default);
1152                         print "  alter or create $field in $table\n" unless $silent;
1153                 }
1154         }
1155 }
1156
1157 # Populate tables with required data
1158
1159
1160 # synch table and deletedtable.
1161 foreach my $table (('borrowers','items','biblio','biblioitems')) {
1162         my %deletedborrowers;
1163         print "synch'ing $table\n";
1164         $sth = $dbh->prepare("show columns from deleted$table");
1165         $sth->execute;
1166         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
1167                 $deletedborrowers{$column}=1;
1168         }
1169         $sth = $dbh->prepare("show columns from $table");
1170         $sth->execute;
1171         my $previous;
1172         while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ) {
1173                 unless ($deletedborrowers{$column}) {
1174                         my $newcol="alter table deleted$table add $column $type";
1175                         if ($null eq 'YES') {
1176                                 $newcol .= " NULL ";
1177                         } else {
1178                                 $newcol .= " NOT NULL ";
1179                         }
1180                         $newcol .= "default $default" if $default;
1181                         $newcol .= " after $previous" if $previous;
1182                         $previous=$column;
1183                         print "creating column $column\n";
1184                         $dbh->do($newcol);
1185                 }
1186         }
1187 }
1188
1189 foreach my $table ( keys %tabledata ) {
1190     print "Checking for data required in table $table...\n" unless $silent;
1191     my $tablerows = $tabledata{$table};
1192     foreach my $row (@$tablerows) {
1193         my $uniquefieldrequired = $row->{uniquefieldrequired};
1194         my $uniquevalue         = $row->{$uniquefieldrequired};
1195         my $forceupdate         = $row->{forceupdate};
1196         my $sth                 =
1197           $dbh->prepare(
1198 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
1199         );
1200         $sth->execute($uniquevalue);
1201                 if ($sth->rows) {
1202                         foreach my $field (keys %$forceupdate) {
1203                                 if ($forceupdate->{$field}) {
1204                                         my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
1205                                         $sth->execute($row->{$field}, $uniquevalue);
1206                                 }
1207                 }
1208                 } else {
1209                         print "Adding row to $table: " unless $silent;
1210                         my @values;
1211                         my $fieldlist;
1212                         my $placeholders;
1213                         foreach my $field ( keys %$row ) {
1214                                 next if $field eq 'uniquefieldrequired';
1215                                 next if $field eq 'forceupdate';
1216                                 my $value = $row->{$field};
1217                                 push @values, $value;
1218                                 print "  $field => $value" unless $silent;
1219                                 $fieldlist .= "$field,";
1220                                 $placeholders .= "?,";
1221                         }
1222                         print "\n" unless $silent;
1223                         $fieldlist    =~ s/,$//;
1224                         $placeholders =~ s/,$//;
1225                         my $sth =
1226                         $dbh->prepare(
1227                                 "insert into $table ($fieldlist) values ($placeholders)");
1228                         $sth->execute(@values);
1229                 }
1230         }
1231 }
1232
1233 #
1234 # check indexes and create them when needed
1235 #
1236 print "Checking for index required...\n" unless $silent;
1237 foreach my $table ( keys %indexes ) {
1238         #
1239         # read all indexes from $table
1240         #
1241         $sth = $dbh->prepare("show index from $table");
1242         $sth->execute;
1243         my %existingindexes;
1244         while ( my ( $table, $non_unique, $key_name, $Seq_in_index, $Column_name, $Collation, $cardinality, $sub_part, $Packed, $comment ) = $sth->fetchrow ) {
1245                 $existingindexes{$key_name} = 1;
1246         }
1247         # read indexes to check
1248         my $tablerows = $indexes{$table};
1249         foreach my $row (@$tablerows) {
1250                 my $key_name=$row->{indexname};
1251                 if ($existingindexes{$key_name} eq 1) {
1252 #                       print "$key_name existing";
1253                 } else {
1254                         print "\tCreating index $key_name in $table\n";
1255                         my $sql;
1256                         if ($row->{indexname} eq 'PRIMARY') {
1257                                 $sql = "alter table $table ADD PRIMARY KEY ($row->{content})";
1258                         } else {
1259                                 $sql = "alter table $table ADD INDEX $key_name ($row->{content}) $row->{type}";
1260                         }
1261                         $dbh->do($sql);
1262             print "Error $sql : $dbh->err \n" if $dbh->err;
1263                 }
1264         }
1265 }
1266
1267 #
1268 # check foreign keys and create them when needed
1269 #
1270 print "Checking for foreign keys required...\n" unless $silent;
1271 foreach my $table ( keys %foreign_keys ) {
1272         #
1273         # read all indexes from $table
1274         #
1275         $sth = $dbh->prepare("show table status like '$table'");
1276         $sth->execute;
1277         my $stat = $sth->fetchrow_hashref;
1278         # read indexes to check
1279         my $tablerows = $foreign_keys{$table};
1280         foreach my $row (@$tablerows) {
1281                 my $foreign_table=$row->{foreigntable};
1282                 if ($stat->{'Comment'} =~/$foreign_table/) {
1283 #                       print "$foreign_table existing\n";
1284                 } else {
1285                         print "\tCreating foreign key $foreign_table in $table\n";
1286                         # first, drop any orphan value in child table
1287                         if ($row->{onDelete} ne "RESTRICT") {
1288                                 my $sql = "delete from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})";
1289                                 $dbh->do($sql);
1290                                 print "SQL ERROR: $sql : $dbh->err \n" if $dbh->err;
1291                         }
1292                         my $sql="alter table $table ADD FOREIGN KEY $row->{key} ($row->{key}) REFERENCES $row->{foreigntable} ($row->{foreignkey})";
1293                         $sql .= " on update ".$row->{onUpdate} if $row->{onUpdate};
1294                         $sql .= " on delete ".$row->{onDelete} if $row->{onDelete};
1295                         $dbh->do($sql);
1296                         if ($dbh->err) {
1297                                 print "====================
1298 An error occured during :
1299 \t$sql
1300 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).
1301 You can find those values with select
1302 \t$table.* from $table where $row->{key} not in (select $row->{foreignkey} from $row->{foreigntable})
1303 ====================\n
1304 ";
1305                         }
1306                 }
1307         }
1308 }
1309
1310 #
1311 # SPECIFIC STUFF
1312 #
1313 #
1314 # create frameworkcode row in biblio table & fill it with marc_biblio.frameworkcode.
1315 #
1316
1317 # 1st, get how many biblio we will have to do...
1318 $sth = $dbh->prepare('select count(*) from marc_biblio');
1319 $sth->execute;
1320 my ($totaltodo) = $sth->fetchrow;
1321
1322 $sth = $dbh->prepare("show columns from biblio");
1323 $sth->execute();
1324 my $definitions;
1325 my $bibliofwexist=0;
1326 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
1327         $bibliofwexist=1 if $column eq 'frameworkcode';
1328 }
1329 unless ($bibliofwexist) {
1330         print "moving biblioframework to biblio table\n";
1331         $dbh->do('ALTER TABLE `biblio` ADD `frameworkcode` VARCHAR( 4 ) NOT NULL AFTER `biblionumber`');
1332         $sth = $dbh->prepare('select biblionumber,frameworkcode from marc_biblio');
1333         $sth->execute;
1334         my $sth_update = $dbh->prepare('update biblio set frameworkcode=? where biblionumber=?');
1335         my $totaldone=0;
1336         while (my ($biblionumber,$frameworkcode) = $sth->fetchrow) {
1337                 $sth_update->execute($frameworkcode,$biblionumber);
1338                 $totaldone++;
1339                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
1340         }
1341         print "\rdone\n";
1342 }
1343
1344 #
1345 # moving MARC data from marc_subfield_table to biblioitems.marc
1346 #
1347 $sth = $dbh->prepare("show columns from biblioitems");
1348 $sth->execute();
1349 my $definitions;
1350 my $marcdone=0;
1351 while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow ){
1352         $marcdone=1 if ($type eq 'blob' && $column eq 'marc') ;
1353 }
1354 unless ($marcdone) {
1355         print "moving MARC record to biblioitems table\n";
1356         # changing marc field type
1357         $dbh->do('ALTER TABLE `biblioitems` CHANGE `marc` `marc` BLOB NULL DEFAULT NULL ');
1358         # adding marc xml, just for convenience
1359         $dbh->do('ALTER TABLE `biblioitems` ADD `marcxml` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ');
1360         # moving data from marc_subfield_value to biblio
1361         $sth = $dbh->prepare('select bibid,biblionumber from marc_biblio');
1362         $sth->execute;
1363         my $sth_update = $dbh->prepare('update biblioitems set marc=?, marcxml=? where biblionumber=?');
1364         my $totaldone=0;
1365         while (my ($bibid,$biblionumber) = $sth->fetchrow) {
1366                 my $record = MARCgetbiblio($dbh,$bibid);
1367         #Force UTF-8 in record leader
1368                 $record->encoding('UTF-8');
1369                 print $record->as_formatted if ($biblionumber==3902);
1370                 $sth_update->execute($record->as_usmarc(),$record->as_xml_record(),$biblionumber);
1371                 $totaldone++;
1372                 print "\r$totaldone / $totaltodo" unless ($totaldone % 100);
1373         }
1374         print "\rdone\n";
1375 }
1376
1377
1378 # at last, remove useless fields
1379 foreach $table ( keys %uselessfields ) {
1380         my @fields = split /,/,$uselessfields{$table};
1381         my $fields;
1382         my $exists;
1383         foreach my $fieldtodrop (@fields) {
1384                 $fieldtodrop =~ s/\t//g;
1385                 $fieldtodrop =~ s/\n//g;
1386                 $exists =0;
1387                 $sth = $dbh->prepare("show columns from $table");
1388                 $sth->execute;
1389                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
1390                 {
1391                         $exists =1 if ($column eq $fieldtodrop);
1392                 }
1393                 if ($exists) {
1394                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
1395                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
1396                         $sth->execute;
1397                 }
1398         }
1399 }    # foreach
1400
1401
1402 # MOVE all tables TO UTF-8 and innoDB
1403 $sth = $dbh->prepare("show table status");
1404 $sth->execute;
1405 while ( my $table = $sth->fetchrow_hashref ) {
1406 #       if ($table->{Engine} ne 'InnoDB') {
1407 #               $dbh->do("ALTER TABLE $table->{Name} TYPE = innodb");
1408 #               print "moving $table->{Name} to InnoDB\n";
1409 #       }
1410         unless ($table->{Collation} =~ /^utf8/) {
1411                 $dbh->do("ALTER TABLE $table->{Name} CONVERT TO CHARACTER SET utf8");
1412                 $dbh->do("ALTER TABLE $table->{Name} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci");
1413                 # 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 !
1414                 print "moving $table->{Name} to utf8\n";
1415         } else {
1416         }
1417 }
1418
1419 $sth->finish;
1420
1421 #
1422 # those 2 subs are a copy of Biblio.pm, version 2.2.4
1423 # they are useful only once, for moving from 2.2 to 3.0
1424 # the MARCgetbiblio & MARCgetitem subs in Biblio.pm
1425 # are still here, but uses other tables
1426 # (the ones that are filled by updatedatabase !)
1427 #
1428
1429 sub MARCgetbiblio {
1430
1431     # Returns MARC::Record of the biblio passed in parameter.
1432     my ( $dbh, $bibid ) = @_;
1433     my $record = MARC::Record->new();
1434 #       warn "". $bidid;
1435
1436     my $sth =
1437       $dbh->prepare(
1438 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
1439                                  from marc_subfield_table
1440                                  where bibid=? order by tag,tagorder,subfieldorder
1441                          "
1442     );
1443     my $sth2 =
1444       $dbh->prepare(
1445         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
1446     $sth->execute($bibid);
1447     my $prevtagorder = 1;
1448     my $prevtag      = 'XXX';
1449     my $previndicator;
1450     my $field;        # for >=10 tags
1451     my $prevvalue;    # for <10 tags
1452     while ( my $row = $sth->fetchrow_hashref ) {
1453
1454         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
1455             $sth2->execute( $row->{'valuebloblink'} );
1456             my $row2 = $sth2->fetchrow_hashref;
1457             $sth2->finish;
1458             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
1459         }
1460         if ( $row->{tagorder} ne $prevtagorder || $row->{tag} ne $prevtag ) {
1461             $previndicator .= "  ";
1462             if ( $prevtag < 10 ) {
1463                                 if ($prevtag ne '000') {
1464                         $record->add_fields( ( sprintf "%03s", $prevtag ), $prevvalue ) unless $prevtag eq "XXX";    # ignore the 1st loop
1465                                 } else {
1466                                         $record->leader(sprintf("%24s",$prevvalue));
1467                                 }
1468             }
1469             else {
1470                 $record->add_fields($field) unless $prevtag eq "XXX";
1471             }
1472             undef $field;
1473             $prevtagorder  = $row->{tagorder};
1474             $prevtag       = $row->{tag};
1475             $previndicator = $row->{tag_indicator};
1476             if ( $row->{tag} < 10 ) {
1477                 $prevvalue = $row->{subfieldvalue};
1478             }
1479             else {
1480                 $field = MARC::Field->new(
1481                     ( sprintf "%03s", $prevtag ),
1482                     substr( $row->{tag_indicator} . '  ', 0, 1 ),
1483                     substr( $row->{tag_indicator} . '  ', 1, 1 ),
1484                     $row->{'subfieldcode'},
1485                     $row->{'subfieldvalue'}
1486                 );
1487             }
1488         }
1489         else {
1490             if ( $row->{tag} < 10 ) {
1491                 $record->add_fields( ( sprintf "%03s", $row->{tag} ),
1492                     $row->{'subfieldvalue'} );
1493             }
1494             else {
1495                 $field->add_subfields( $row->{'subfieldcode'},
1496                     $row->{'subfieldvalue'} );
1497             }
1498             $prevtag       = $row->{tag};
1499             $previndicator = $row->{tag_indicator};
1500         }
1501     }
1502
1503     # the last has not been included inside the loop... do it now !
1504     if ( $prevtag ne "XXX" )
1505     { # check that we have found something. Otherwise, prevtag is still XXX and we
1506          # must return an empty record, not make MARC::Record fail because we try to
1507          # create a record with XXX as field :-(
1508         if ( $prevtag < 10 ) {
1509             $record->add_fields( $prevtag, $prevvalue );
1510         }
1511         else {
1512
1513             #           my $field = MARC::Field->new( $prevtag, "", "", %subfieldlist);
1514             $record->add_fields($field);
1515         }
1516     }
1517     return $record;
1518 }
1519
1520 sub MARCgetitem {
1521
1522     # Returns MARC::Record of the biblio passed in parameter.
1523     my ( $dbh, $bibid, $itemnumber ) = @_;
1524     my $record = MARC::Record->new();
1525
1526     # search MARC tagorder
1527     my $sth2 =
1528       $dbh->prepare(
1529 "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=?"
1530     );
1531     $sth2->execute( $bibid, $itemnumber );
1532     my ($tagorder) = $sth2->fetchrow_array();
1533
1534     #---- TODO : the leader is missing
1535     my $sth =
1536       $dbh->prepare(
1537 "select bibid,subfieldid,tag,tagorder,tag_indicator,subfieldcode,subfieldorder,subfieldvalue,valuebloblink
1538                                  from marc_subfield_table
1539                                  where bibid=? and tagorder=? order by subfieldcode,subfieldorder
1540                          "
1541     );
1542     $sth2 =
1543       $dbh->prepare(
1544         "select subfieldvalue from marc_blob_subfield where blobidlink=?");
1545     $sth->execute( $bibid, $tagorder );
1546     while ( my $row = $sth->fetchrow_hashref ) {
1547         if ( $row->{'valuebloblink'} ) {    #---- search blob if there is one
1548             $sth2->execute( $row->{'valuebloblink'} );
1549             my $row2 = $sth2->fetchrow_hashref;
1550             $sth2->finish;
1551             $row->{'subfieldvalue'} = $row2->{'subfieldvalue'};
1552         }
1553         if ( $record->field( $row->{'tag'} ) ) {
1554             my $field;
1555
1556 #--- this test must stay as this, because of strange behaviour of mySQL/Perl DBI with char var containing a number...
1557             #--- sometimes, eliminates 0 at beginning, sometimes no ;-\\\
1558             if ( length( $row->{'tag'} ) < 3 ) {
1559                 $row->{'tag'} = "0" . $row->{'tag'};
1560             }
1561             $field = $record->field( $row->{'tag'} );
1562             if ($field) {
1563                 my $x =
1564                   $field->add_subfields( $row->{'subfieldcode'},
1565                     $row->{'subfieldvalue'} );
1566                 $record->delete_field($field);
1567                 $record->add_fields($field);
1568             }
1569         }
1570         else {
1571             if ( length( $row->{'tag'} ) < 3 ) {
1572                 $row->{'tag'} = "0" . $row->{'tag'};
1573             }
1574             my $temp =
1575               MARC::Field->new( $row->{'tag'}, " ", " ",
1576                 $row->{'subfieldcode'} => $row->{'subfieldvalue'} );
1577             $record->add_fields($temp);
1578         }
1579
1580     }
1581     return $record;
1582 }
1583
1584
1585 exit;
1586
1587 # $Log$
1588 # Revision 1.140  2006/05/22 22:40:45  rangi
1589 # Adding new systempreference allowing for the library to add borrowers to institutions (rest homes, parishes, schools, classes etc).
1590 #
1591 # Revision 1.139  2006/05/19 19:31:29  tgarip1957
1592 # Added new fields to auth_header and auth_subfield_table to allow ZEBRA use of authorities and new MARC framework like structure.
1593 # 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
1594 #
1595 # Revision 1.138  2006/05/19 16:51:44  alaurin
1596 # update database for :
1597 # - new feature ip and printer management
1598 # adding two fields in branches table (branchip,branchprinter)
1599 #
1600 # - 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
1601 #
1602 # new system preference :
1603 # - ReservesMaxPickUpDelay : Maximum delay to pick up a reserved document
1604 # TransfersMaxDaysWarning : Max delay before considering the transfer as potentialy a problem
1605 #
1606 # Revision 1.137  2006/04/18 09:36:36  plg
1607 # bug fixed: typo fixed in labels and labels_conf tables creation query.
1608 #
1609 # Revision 1.136  2006/04/17 21:55:33  sushi
1610 # Added 'labels' and 'labels_conf' tables, for spine lable tool.
1611 #
1612 # Revision 1.135  2006/04/15 02:37:03  tgarip1957
1613 # Marc record should be set to UTF-8 in leader.Force it.
1614 # XML should be with<record> wrappers
1615 #
1616 # Revision 1.134  2006/04/14 09:37:29  tipaul
1617 # improvements from SAN Ouest Provence :
1618 # * introducing a category_type into categories. It can be A (adult), C (children), P (Professionnal), I (institution/organisation).
1619 # * each category_type has it's own forms to create members.
1620 # * the borrowers table has been heavily modified (many fields changed), to get something more logic & readable
1621 # * reintroducing guarantor/guanrantee system that is now independant from hardcoded C/A for categories
1622 # * updating templates to fit template rules
1623 #
1624 # (see mail feb, 17 on koha-devel "new features for borrowers" for more details)
1625 #
1626 # Revision 1.133  2006/04/13 08:36:42  plg
1627 # new: function C4::Date::get_date_format_string_for_DHTMLcalendar based on
1628 # the system preference prefered date format.
1629 #
1630 # improvement: book fund list and budget list screen redesigned. Filters on
1631 # each field. Columns are not sortable yet. Using DHTML Calendar to fill date
1632 # fields instead of manual filling. Pagination system. From the book fund
1633 # list, you can reach the budget list, filtered on a book fund, or not. A
1634 # budget can be added only from book fund list screen.
1635 #
1636 # bug fixed: branchcode was missing in table aqbudget.
1637 #
1638 # bug fixed: when setting a branchcode to a book fund, all associated budgets
1639 # move to this branchcode.
1640 #
1641 # modification: when adding/modifying budget/fund, MySQL specific "REPLACE..."
1642 # statements replaced by standard SQL compliant statement.
1643 #
1644 # bug fixed: when adding/modifying a budget, if the book fund is associated to
1645 # a branch, the branch selection is disabled and set to the book fund branch.
1646 #
1647 # Revision 1.132  2006/04/06 12:37:05  hdl
1648 # Bugfixing : aqbookfund needed a field.
1649 #
1650 # Revision 1.131  2006/03/03 17:02:22  tipaul
1651 # commit for holidays and news management.
1652 # (some forgotten files)
1653 #
1654 # Revision 1.130  2006/03/03 16:35:21  tipaul
1655 # commit for holidays and news management.
1656 #
1657 # Contrib from Tümer Garip (from Turkey) :
1658 # * holiday :
1659 # 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 :
1660 # - single day : only this day is closed
1661 # - repet weekly (like "sunday") : the day is holiday every week
1662 # - repet yearly (like "July, 4") : this day is closed every year.
1663 #
1664 # You can also put exception :
1665 # - sunday is holiday, but "2006 March, 5th" the library will be open
1666 #
1667 # 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.
1668 #
1669 # Revision 1.129  2006/02/27 18:19:33  hdl
1670 # New table used in overduerules.pl tools page.
1671 #
1672 # Revision 1.128  2006/01/25 15:16:06  tipaul
1673 # updating DB :
1674 # * removing useless tables
1675 # * adding useful indexes
1676 # * altering some columns definitions
1677 # * The goal being to have updater working fine for foreign keys.
1678 #
1679 # 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
1680 #
1681 # Revision 1.127  2006/01/24 17:57:17  tipaul
1682 # DB improvements : adding foreign keys on some tables. partial stuff done.
1683 #
1684 # Revision 1.126  2006/01/06 16:39:42  tipaul
1685 # synch'ing head and rel_2_2 (from 2.2.5, including npl templates)
1686 # Seems not to break too many things, but i'm probably wrong here.
1687 # at least, new features/bugfixes from 2.2.5 are here (tested on some features on my head local copy)
1688 #
1689 # - removing useless directories (koha-html and koha-plucene)
1690 #
1691 # Revision 1.125  2006/01/04 15:54:55  tipaul
1692 # utf8 is a : go for beta test in HEAD.
1693 # some explanations :
1694 # - 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.
1695 # - *-top.inc will show the pages in utf8
1696 # - 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.
1697 # - using marcxml field and no more the iso2709 raw marc biblioitems.marc field.
1698 #
1699 # Revision 1.124  2005/10/27 12:09:05  tipaul
1700 # new features for serial module :
1701 # - 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")
1702 # - 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).
1703 #
1704 # Revision 1.123  2005/10/26 09:13:37  tipaul
1705 # big commit, still breaking things...
1706 #
1707 # * synch with rel_2_2. Probably the last non manual synch, as rel_2_2 should not be modified deeply.
1708 # * code cleaning (cleaning warnings from perl -w) continued
1709 #
1710 # Revision 1.122  2005/09/02 14:18:38  tipaul
1711 # new feature : image for itemtypes.
1712 #
1713 # * run updater/updatedatabase to create imageurl field in itemtypes.
1714 # * 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)
1715 # * go to OPAC, and search something. In the result list, you now have the picture instead of the text itemtype.
1716 #
1717 # Revision 1.121  2005/08/24 08:49:03  hdl
1718 # Adding a note field in serial table.
1719 # This will allow librarian to mention a note on a peculiar waiting serial number.
1720 #
1721 # Revision 1.120  2005/08/09 14:10:32  tipaul
1722 # 1st commit to go to zebra.
1723 # don't update your cvs if you want to have a working head...
1724 #
1725 # this commit contains :
1726 # * 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...
1727 # * 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.
1728 # * other files : get rid of bibid and use biblionumber instead.
1729 #
1730 # What is broken :
1731 # * does not do anything on zebra yet.
1732 # * if you rename marc_subfield_table, you can't search anymore.
1733 # * you can view a biblio & bibliodetails, go to MARC editor, but NOT save any modif.
1734 # * 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 ;-) )
1735 #
1736 # 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
1737 # 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.
1738 #
1739 # Revision 1.119  2005/08/04 16:07:58  tipaul
1740 # Synch really broke this script...
1741 #
1742 # Revision 1.118  2005/08/04 16:02:55  tipaul
1743 # oops... error in synch between 2.2 and head
1744 #
1745 # Revision 1.117  2005/08/04 14:24:39  tipaul
1746 # synch'ing 2.2 and head
1747 #
1748 # Revision 1.116  2005/08/04 08:55:54  tipaul
1749 # Letters / alert system, continuing...
1750 #
1751 # * adding a package Letters.pm, that manages Letters & alerts.
1752 # * 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)
1753 # * 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)
1754 # * 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.
1755 #
1756 # Note that the system should be generic enough to manage any type of alert.
1757 # 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 ;-) )
1758 #
1759 # Revision 1.115  2005/08/02 16:15:34  tipaul
1760 # adding 2 fields to letter system :
1761 # * module (acquisition, catalogue...) : it will be usefull to show the librarian only letters he may be interested by.
1762 # * title, that will be used as mail subject.
1763 #
1764 # Revision 1.114  2005/07/28 15:10:13  tipaul
1765 # 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.
1766 # the letter table contains 3 fields :
1767 # * code => the code of the letter
1768 # * name => the complete name of the letter
1769 # * content => the complete text. It's a TEXT field type, so has no limits.
1770 #
1771 # My next goal now is to work on point 2-I "serial issue alert"
1772 # 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.
1773 # (see mail on koha-devel, 2005/04/07)
1774 #
1775 # The "serial issue alert" will be the 1st to use this letter system that probably needs some tweaking ;-)
1776 #
1777 # Once it will be stabilised default letters (in any languages) could be added during installer to help the library begin with this new feature.
1778 #
1779 # Revision 1.113  2005/07/28 08:38:41  tipaul
1780 # 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 :
1781 # * ReturnBeforeExpiry = yes => return date can't be after expiry date
1782 # * ReturnBeforeExpiry = no  => return date can be after expiry date
1783 #
1784 # Revision 1.112  2005/07/26 08:19:47  hdl
1785 # Adding IndependantBranches System preference variable in order to manage Branch independancy.
1786 #
1787 # Revision 1.111  2005/07/25 15:35:38  tipaul
1788 # we have decided that moving to Koha 3.0 requires being already in Koha 2.2.x
1789 # So, the updatedatabase script can highly be cleaned (90% removed).
1790 # Let's play with the new Koha DB structure now ;-)
1791 #