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