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