Adding IndependantBranches System preference variable in order to manage Branch indep...
[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 # FIXME - The user might be installing a new database, so can't rely
24 # on /etc/koha.conf anyway.
25
26 my $debug = 0;
27
28 my (
29     $sth, $sti,
30     $query,
31     %existingtables,    # tables already in database
32     %types,
33     $table,
34     $column,
35     $type, $null, $key, $default, $extra,
36     $prefitem,          # preference item in systempreferences table
37 );
38
39 my $silent;
40 GetOptions(
41         's' =>\$silent
42         );
43 my $dbh = C4::Context->dbh;
44 print "connected to your DB. Checking & modifying it\n" unless $silent;
45
46 #-------------------
47 # Defines
48
49 # Tables to add if they don't exist
50 my %requiretables = (
51     categorytable       => "(categorycode char(5) NOT NULL default '',
52                              description text default '',
53                              itemtypecodes text default '',
54                              PRIMARY KEY (categorycode)
55                             )",
56     subcategorytable       => "(subcategorycode char(5) NOT NULL default '',
57                              description text default '',
58                              itemtypecodes text default '',
59                              PRIMARY KEY (subcategorycode)
60                             )",
61     mediatypetable       => "(mediatypecode char(5) NOT NULL default '',
62                              description text default '',
63                              itemtypecodes text default '',
64                              PRIMARY KEY (mediatypecode)
65                             )",
66     action_logs         => "(
67                                     `timestamp` TIMESTAMP NOT NULL ,
68                                     `user` INT( 11 ) NOT NULL ,
69                                     `module` TEXT default '',
70                                     `action` TEXT default '' ,
71                                     `object` INT(11) default '' ,
72                                     `info` TEXT default '' ,
73                                     PRIMARY KEY ( `timestamp` , `user` )
74                             )",
75 );
76
77 my %requirefields = (
78 #    tablename        => { 'field' => 'fieldtype' },
79 );
80
81 my %dropable_table = (
82 # tablename => 'tablename',
83 );
84
85 my %uselessfields = (
86 # tablename => "field1,field2",
87         );
88 # the other hash contains other actions that can't be done elsewhere. they are done
89 # either BEFORE of AFTER everything else, depending on "when" entry (default => AFTER)
90
91 # The tabledata hash contains data that should be in the tables.
92 # The uniquefieldrequired hash entry is used to determine which (if any) fields
93 # must not exist in the table for this row to be inserted.  If the
94 # uniquefieldrequired entry is already in the table, the existing data is not
95 # modified, unless the forceupdate hash entry is also set.  Fields in the
96 # anonymous "forceupdate" hash will be forced to be updated to the default
97 # values given in the %tabledata hash.
98
99 my %tabledata = (
100 # tablename => [
101 #       {       uniquefielrequired => 'fieldname', # the primary key in the table
102 #               fieldname => fieldvalue,
103 #               fieldname2 => fieldvalue2,
104 #       },
105 # ],
106     systempreferences => [
107                 {
108             uniquefieldrequired => 'variable',
109             variable            => 'Activate_Log',
110             value               => 'On',
111             forceupdate         => { 'explanation' => 1,
112                                      'type' => 1},
113             explanation         => 'Turn Log Actions on DB On an Off',
114             type                => 'YesNo',
115         },
116         {
117             uniquefieldrequired => 'variable',
118             variable            => 'IndependantBranches',
119             value               => 0,
120             forceupdate         => { 'explanation' => 1,
121                                      'type' => 1},
122             explanation         => 'Turn Branch independancy management On an Off',
123             type                => 'YesNo',
124         },
125
126     ],
127
128 );
129
130 my %fielddefinitions = (
131 # fieldname => [
132 #       {                 field => 'fieldname',
133 #             type    => 'fieldtype',
134 #             null    => '',
135 #             key     => '',
136 #             default => ''
137 #         },
138 #     ],
139 );
140
141 #-------------------
142 # Initialize
143
144 # Start checking
145
146 # Get version of MySQL database engine.
147 my $mysqlversion = `mysqld --version`;
148 $mysqlversion =~ /Ver (\S*) /;
149 $mysqlversion = $1;
150 if ( $mysqlversion ge '3.23' ) {
151     print "Could convert to MyISAM database tables...\n" unless $silent;
152 }
153
154 #---------------------------------
155 # Tables
156
157 # Collect all tables into a list
158 $sth = $dbh->prepare("show tables");
159 $sth->execute;
160 while ( my ($table) = $sth->fetchrow ) {
161     $existingtables{$table} = 1;
162 }
163
164
165 # Now add any missing tables
166 foreach $table ( keys %requiretables ) {
167     unless ( $existingtables{$table} ) {
168         print "Adding $table table...\n" unless $silent;
169         my $sth = $dbh->prepare("create table $table $requiretables{$table}");
170         $sth->execute;
171         if ( $sth->err ) {
172             print "Error : $sth->errstr \n";
173             $sth->finish;
174         }    # if error
175     }    # unless exists
176 }    # foreach
177
178 # now drop useless tables
179 foreach $table ( keys %dropable_table ) {
180         if ( $existingtables{$table} ) {
181                 print "Dropping unused table $table\n" if $debug and not $silent;
182                 $dbh->do("drop table $table");
183                 if ( $dbh->err ) {
184                         print "Error : $dbh->errstr \n";
185                 }
186         }
187 }
188
189 #---------------------------------
190 # Columns
191
192 foreach $table ( keys %requirefields ) {
193     print "Check table $table\n" if $debug and not $silent;
194     $sth = $dbh->prepare("show columns from $table");
195     $sth->execute();
196     undef %types;
197     while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
198     {
199         $types{$column} = $type;
200     }    # while
201     foreach $column ( keys %{ $requirefields{$table} } ) {
202         print "  Check column $column  [$types{$column}]\n" if $debug and not $silent;
203         if ( !$types{$column} ) {
204
205             # column doesn't exist
206             print "Adding $column field to $table table...\n" unless $silent;
207             $query = "alter table $table
208                         add column $column " . $requirefields{$table}->{$column};
209             print "Execute: $query\n" if $debug;
210             my $sti = $dbh->prepare($query);
211             $sti->execute;
212             if ( $sti->err ) {
213                 print "**Error : $sti->errstr \n";
214                 $sti->finish;
215             }    # if error
216         }    # if column
217     }    # foreach column
218 }    # foreach table
219
220 foreach $table ( keys %fielddefinitions ) {
221         print "Check table $table\n" if $debug;
222         $sth = $dbh->prepare("show columns from $table");
223         $sth->execute();
224         my $definitions;
225         while ( ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
226         {
227                 $definitions->{$column}->{type}    = $type;
228                 $definitions->{$column}->{null}    = $null;
229                 $definitions->{$column}->{key}     = $key;
230                 $definitions->{$column}->{default} = $default;
231                 $definitions->{$column}->{extra}   = $extra;
232         }    # while
233         my $fieldrow = $fielddefinitions{$table};
234         foreach my $row (@$fieldrow) {
235                 my $field   = $row->{field};
236                 my $type    = $row->{type};
237                 my $null    = $row->{null};
238                 my $key     = $row->{key};
239                 my $default = $row->{default};
240                 $default="''" unless $default;
241                 my $extra   = $row->{extra};
242                 my $def     = $definitions->{$field};
243                 unless ( $type eq $def->{type}
244                         && $null eq $def->{null}
245                         && $key eq $def->{key}
246                         && $default eq $def->{default}
247                         && $extra eq $def->{extra} )
248                 {
249
250                         if ( $null eq '' ) {
251                                 $null = 'NOT NULL';
252                         }
253                         if ( $key eq 'PRI' ) {
254                                 $key = 'PRIMARY KEY';
255                         }
256                         unless ( $extra eq 'auto_increment' ) {
257                                 $extra = '';
258                         }
259                         # if it's a new column use "add", if it's an old one, use "change".
260                         my $action;
261                         if ($definitions->{$field}->{type}) {
262                                 $action="change $field"
263                         } else {
264                                 $action="add";
265                         }
266 # if it's a primary key, drop the previous pk, before altering the table
267                         my $sth;
268                         if ($key ne 'PRIMARY KEY') {
269                                 $sth =$dbh->prepare("alter table $table $action $field $type $null $key $extra default ?");
270                         } else {
271                                 $sth =$dbh->prepare("alter table $table drop primary key, $action $field $type $null $key $extra default ?");
272                         }
273                         $sth->execute($default);
274                         print "  Alter $field in $table\n" unless $silent;
275                 }
276         }
277 }
278
279
280 # Populate tables with required data
281 foreach my $table ( keys %tabledata ) {
282     print "Checking for data required in table $table...\n" unless $silent;
283     my $tablerows = $tabledata{$table};
284     foreach my $row (@$tablerows) {
285         my $uniquefieldrequired = $row->{uniquefieldrequired};
286         my $uniquevalue         = $row->{$uniquefieldrequired};
287         my $forceupdate         = $row->{forceupdate};
288         my $sth                 =
289           $dbh->prepare(
290 "select $uniquefieldrequired from $table where $uniquefieldrequired=?"
291         );
292         $sth->execute($uniquevalue);
293         if ($sth->rows) {
294             foreach my $field (keys %$forceupdate) {
295                 if ($forceupdate->{$field}) {
296                     my $sth=$dbh->prepare("update systempreferences set $field=? where $uniquefieldrequired=?");
297                     $sth->execute($row->{$field}, $uniquevalue);
298                 }
299             }
300         } else {
301             print "Adding row to $table: " unless $silent;
302             my @values;
303             my $fieldlist;
304             my $placeholders;
305             foreach my $field ( keys %$row ) {
306                 next if $field eq 'uniquefieldrequired';
307                 next if $field eq 'forceupdate';
308                 my $value = $row->{$field};
309                 push @values, $value;
310                 print "  $field => $value" unless $silent;
311                 $fieldlist .= "$field,";
312                 $placeholders .= "?,";
313             }
314             print "\n" unless $silent;
315             $fieldlist    =~ s/,$//;
316             $placeholders =~ s/,$//;
317             my $sth =
318               $dbh->prepare(
319                 "insert into $table ($fieldlist) values ($placeholders)");
320             $sth->execute(@values);
321         }
322     }
323 }
324
325 # at last, remove useless fields
326 foreach $table ( keys %uselessfields ) {
327         my @fields = split /,/,$uselessfields{$table};
328         my $fields;
329         my $exists;
330         foreach my $fieldtodrop (@fields) {
331                 $fieldtodrop =~ s/\t//g;
332                 $fieldtodrop =~ s/\n//g;
333                 $exists =0;
334                 $sth = $dbh->prepare("show columns from $table");
335                 $sth->execute;
336                 while ( my ( $column, $type, $null, $key, $default, $extra ) = $sth->fetchrow )
337                 {
338                         $exists =1 if ($column eq $fieldtodrop);
339                 }
340                 if ($exists) {
341                         print "deleting $fieldtodrop field in $table...\n" unless $silent;
342                         my $sth = $dbh->prepare("alter table $table drop $fieldtodrop");
343                         $sth->execute;
344                 }
345         }
346 }    # foreach
347
348
349 $sth->finish;
350
351 exit;
352
353 # $Log$
354 # Revision 1.112  2005/07/26 08:19:47  hdl
355 # Adding IndependantBranches System preference variable in order to manage Branch independancy.
356 #
357 # Revision 1.111  2005/07/25 15:35:38  tipaul
358 # we have decided that moving to Koha 3.0 requires being already in Koha 2.2.x
359 # So, the updatedatabase script can highly be cleaned (90% removed).
360 # Let's play with the new Koha DB structure now ;-)
361 #