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