blib/script/gbrowse_metadb_config.pl untested

filter: Statementstmt 0.0% 0 / 553 Branchbran 0.0% 0 / 174 Conditioncond 0.0% 0 / 152 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 942 CC 79 SCAR 40.2
CC
79
Cov
0%
check_data_sources
210.0
fix_sqlite_permissions
110.0
check_table
90.0
CRAP 55.8
1 #!/usr/local/bin/perl -w
2 # This script checks the schemas and required fields of the Users Database.
3 use strict;
4 use FindBin '$Bin';
5 use lib "$Bin/../blib/lib";
6 use Bio::Graphics::Browser2 "open_globals";
7 use CGI::Session;
8 use Digest::MD5 qw(md5_hex);
9 use Getopt::Long;
10 use GBrowse::ConfigData;
11 use List::Util;
12 use File::Spec;
13 use File::Basename 'dirname','basename';
14 use File::Path 'rmtree';
15 use File::Spec;
16 use POSIX 'strftime';
17  
18 use constant SCHEMA_VERSION => 4;
19  
20 # First, collect all the flags - or output the correct usage, if none listed.
21 my @argv = @ARGV;
22  
23 my ($dsn, $admin);
24 GetOptions('dsn=s' => \$dsn,
25 'admin=s' => \$admin) or die <<EOF;
26 Usage: $0 [options] <optional path to GBrowse.conf>
27  
28 Initializes an empty GBrowse user accounts and uploads metadata database.
29 Options:
30  
31 -dsn Provide a custom DBI connection string, overriding what is
32 set in Gbrowse.conf. Note that if there are semicolons in the
33 string (like most MySQL connection DSNs will), you WILL have
34 to escape it with quotes.
35 -admin Provide an administrator username and password (in the form
36 'user:pass') to skip the prompts if the database does not
37 exist.
38  
39 Currently mysql and SQLite databases are supported. When creating a
40 mysql database you must provide the -admin option to specify a user
41 and password that has database create privileges on the server.
42 EOF
43 ;
44  
45 my $www_user = GBrowse::ConfigData->config('wwwuser');
46 my ($current_user) = getpwuid($<);
47  
48 unless ($www_user eq $current_user or $< == 0) {
49 print STDERR <<END;
50 For user account installation to work properly, this script must be able to
51 create directories owned by the Apache server account ($www_user).
52 This script will now invoke sudo to become the 'root' user temporarily.
53 You may be prompted for your login password now.
54 END
55 ;
56 exec 'sudo','-u','root',$0,@argv;
57 }
58  
59 my $line_counter = 0; # controls newlines
60  
61 # Open the connections.
62 my $globals = Bio::Graphics::Browser2->open_globals;
63 $dsn ||= $globals->user_account_db;
64 if (!$dsn || ($dsn =~ /filesystem|memory/i) || !$globals->user_accounts) {
65 print "No need to run database metadata configuration script, filesystem-backend will be used.";
66 exit 0;
67 }
68  
69 fix_sqlite_permissions() if $dsn =~ /sqlite/i;
70 create_mysql_database() if $dsn =~ /mysql/i;
71  
72 eval "require DBI" or die "DBI module not installed. Cannot continue.";
73  
74 my $database = DBI->connect($dsn)
75 or die "Error: Could not open users database, please check your credentials.\n" . DBI->errstr;
76 my $type = $database->{Driver}->{Name};
77  
78 my $autoincrement = $type =~ /mysql/i ? 'auto_increment'
79 :$type =~ /sqlite/i ? 'autoincrement'
80 :'';
81 my $last_id = $type =~ /mysql/i ? 'mysql_insertid'
82 :$type =~ /sqlite/i ? 'last_insert_rowid'
83 :'';
84  
85 # Database schema. To change the schema, update/add the fields here, and run this script.
86 my $users_columns = {
87 userid => "integer PRIMARY KEY $autoincrement",
88 email => "varchar(64) not null UNIQUE",
89 pass => "varchar(44) not null",
90 gecos => "varchar(64)",
91 remember => "boolean not null",
92 openid_only => "boolean not null",
93 confirmed => "boolean not null",
94 cnfrm_code => "varchar(32) not null",
95 last_login => "timestamp not null",
96 created => "datetime not null"
97 };
98  
99 my $session_columns = {
100 userid => "integer PRIMARY KEY $autoincrement",
101 username => "varchar(32)",
102 sessionid => 'char(32) not null UNIQUE',
103 uploadsid => 'char(32) not null UNIQUE',
104 };
105  
106 my $openid_columns = {
107 userid => "integer not null",
108 openid_url => "varchar(128) PRIMARY KEY"
109 };
110  
111 my $uploads_columns = {
112 trackid => "varchar(32) not null PRIMARY key",
113 userid => "integer not null",
114 path => "text",
115 title => "text",
116 description => "text",
117 imported => "boolean not null",
118 creation_date => "datetime not null",
119 modification_date => "datetime",
120 sharing_policy => "ENUM('private', 'public', 'group', 'casual') not null",
121 public_count => "int",
122 data_source => "text",
123 };
124  
125 my $sharing_columns = {
126 trackid => "varchar(32) not null",
127 userid => "integer not null",
128 public => "boolean",
129 };
130  
131 my $dbinfo_columns = {
132 schema_version => 'int(10) not null UNIQUE'
133 };
134  
135 my $old_users_columns = {
136 userid => "varchar(32) not null UNIQUE PRIMARY KEY",
137 uploadsid => "varchar(32) not null UNIQUE",
138 username => "varchar(32) not null UNIQUE",
139 email => "varchar(64) not null UNIQUE",
140 pass => "varchar(32) not null",
141 remember => "boolean not null",
142 openid_only => "boolean not null",
143 confirmed => "boolean not null",
144 cnfrm_code => "varchar(32) not null",
145 last_login => "timestamp not null",
146 created => "datetime not null"
147 };
148  
149 my $old_uploads_columns = {
150 uploadid => "varchar(32) not null PRIMARY key",
151 userid => "varchar(32) not null",
152 path => "text",
153 title => "text",
154 description => "text",
155 imported => "boolean not null",
156 creation_date => "datetime not null",
157 modification_date => "datetime",
158 sharing_policy => "ENUM('private', 'public', 'group', 'casual') not null",
159 users => "text",
160 public_users => "text",
161 public_count => "int",
162 data_source => "text",
163 };
164  
165 upgrade_schema(SCHEMA_VERSION);
166 check_table("users", $users_columns);
167 check_table("session", $session_columns);
168 check_table("openid_users", $openid_columns);
169 check_table("uploads", $uploads_columns);
170 check_table("sharing", $sharing_columns);
171  
172 check_sessions();
173 check_uploads_ids();
174 check_all_files();
175 check_data_sources();
176 fix_session_permissions();
177 fix_sqlite_permissions() if $type =~ /sqlite/i;
178  
179 $database->disconnect;
180  
181 print STDERR "Done!\n";
182  
183 exit 0;
184  
185  
186 # Check Table (Name, Columns) - Makes sure the named table is there and follows the schema needed.
187 sub check_table {
188 my $name = shift or die "No table name given, please check the gbrowse_metadb_config.pl script.\n";
189 my $columns = shift or die "No table schema given, please check the gbrowse_metadb_config.pl script.\n";
190
191 # If the database doesn't exist, create it.
192 local $database->{PrintError} = 0;
193 unless (eval {$database->do("SELECT * FROM $name LIMIT 1")}) {
194 $database->{PrintError} = 1;
195 print STDERR ucfirst $name . " table didn't exist, creating...\n";
196 my @column_descriptors = map { "$_ " . escape_enums($$columns{$_}) }
197 keys %$columns; # This simply outputs %columns as "$key $value, ";
198 my $creation_sql = "CREATE TABLE $name ("
199 . (join ", ", @column_descriptors) . ")"
200 . (($type =~ /mysql/i)? " ENGINE=InnoDB;" : ";");
201 $database->do($creation_sql) or die "Could not create $name database.\n";
202  
203 }
204  
205 my $sth = $database->prepare("SELECT * from $name LIMIT 1");
206 $sth->execute;
207 my %existing_columns = map {$_=>1} @{$sth->{NAME_lc}};
208
209 # If an extra column exists, drop it.
210 my @columns_to_drop = grep {!$columns->{$_}} keys %existing_columns;
211 if (@columns_to_drop) {
212 print STDERR "Dropping the following columns from $name: ",join(',',@columns_to_drop),".\n";
213 if ($type !~ /sqlite/i) {
214 for my $c (@columns_to_drop) {
215 $database->do("ALTER TABLE $name DROP $c");
216 }
217 }
218 }
219  
220 # If a required column doesn't exist, add it.
221 my @columns_to_create = grep {!$existing_columns{$_}} keys %$columns;
222 if (@columns_to_create) {
223 print STDERR ucfirst $name . " table schema is incorrect, adding "
224 . @columns_to_create . " missing column"
225 . ((@columns_to_create > 1)? "s." : ".");
226
227 # SQLite doesn't support altering to add multiple columns or ENUMS,
228 # so it gets special treatment.
229 if ($type =~ /sqlite/i) {
230 # If we don't find a specific column, add its SQL to the columns_to_create array.
231 foreach (@columns_to_create) {
232 $$columns{$_} = escape_enums($$columns{$_});
233
234 # Now add each column individually
235 my $alter_sql = "ALTER TABLE $name ADD COLUMN $_ " . $$columns{$_} . ";";
236 $database->do($alter_sql) or die "While adding column $_ to $name: ",
237 $database->errstr;
238 }
239 } else {
240 @columns_to_create = map { "$_ " . $$columns{$_} } @columns_to_create;
241
242 # Now add all the columns
243 my $alter_sql;
244
245 if ($type =~ /mysql/) {
246 $alter_sql .= "ALTER TABLE $name";
247 $alter_sql .= " ADD COLUMN " . shift @columns_to_create;
248 $alter_sql .= ", ADD COLUMN $_" foreach @columns_to_create;
249 $alter_sql .= ";";
250 } else {
251 $alter_sql = "ALTER TABLE $name ADD (" . (join ", ", @columns_to_create) . ");" ;
252 }
253 $database->do($alter_sql) or die $database->errstr;
254 }
255 }
256  
257 return $database;
258 }
259  
260 # iterate through each session and make sure that there is a
261 # corresponding user in the session table
262 sub check_sessions {
263 my $session_driver = $globals->session_driver;
264 my $session_args = $globals->session_args;
265 my $users_updated = 0;
266 local $database->{PrintError} = 0;
267 my $do_session_check = sub {
268 my $session = shift;
269 my $session_id = $session->id;
270 my $source = $session->param('.source') or return;
271 my $config_hash = $session->param($source) or return;
272 my $uploadsid = $session->param('.uploadsid') ||
273 $config_hash->{page_settings}{uploadid};
274 $uploadsid or return;
275  
276 my $sql = "SELECT count(*) FROM session WHERE sessionid=? AND uploadsid=?";
277 my $rows = $database->selectrow_array($sql,undef,$session_id,$uploadsid);
278 return if $rows == 0;
279 $sql = "UPDATE session SET uploadsid=? WHERE sessionid=? AND uploadsid!=?";
280 $rows = $database->do($sql,undef,$uploadsid,$session_id,$uploadsid);
281 $users_updated += $rows;
282 };
283 eval {
284 CGI::Session->find($session_driver,$do_session_check,$session_args);
285 };
286 if ($users_updated) {
287 print STDERR "$users_updated users had their session/upload IDs updated.\n";
288 }
289 }
290  
291  
292 # Check Uploads IDs () - Makes sure every user ID has an uploads ID corresponding to it.
293 sub check_uploads_ids {
294 print STDERR "Checking uploads IDs in database...";
295 my $ids_in_db = $database->selectcol_arrayref("SELECT userid, uploadsid FROM session", { Columns=>[1,2] });
296 my $missing = 0;
297 if ($ids_in_db) {
298 my %uploads_ids = @$ids_in_db;
299 foreach my $userid (keys %uploads_ids) {
300 unless ($uploads_ids{$userid}) {
301 print STDERR "missing uploads ID found.\n" unless $missing;
302 print STDERR "- Uploads ID not found for $userid, ";
303 my $session = $globals->session($userid);
304 my $settings= $session->page_settings;
305 my $uploadsid = $session->param('.uploadsid') ||
306 $settings->{uploadid};
307 $database->do("UPDATE session SET uploadsid = ? WHERE sessionid = ?", undef, $uploadsid, $userid) or print STDERR "could not add to database.\n" . DBI->errstr;
308 print STDERR "added to database.\n" unless DBI->errstr;
309 $missing = 1;
310 }
311 }
312 }
313 print STDERR "all uploads IDs are present.\n" unless $missing;
314 }
315  
316 # Check Data Sources () - Checks to make sure the data sources are there for each file.
317 sub check_data_sources {
318 print STDERR "Checking for any files with missing data sources...";
319 my $missing = 0;
320
321 # Since we can't access the Database.pm access without the data source, we'll have to go in the back door,
322 # and manually get the uploads ID, file path, and data source from the userdata folder.
323 my $userdata_folder = $globals->user_dir;
324 unless (-e $userdata_folder) {
325 print STDERR "No files, no checks needed.\n";
326 return;
327 }
328 my @data_sources;
329 opendir U, $userdata_folder;
330 while (my $dir = readdir(U)) {
331 next if $dir =~ /^\.+$/;
332 next unless -d $dir;
333 push @data_sources, $dir;
334 }
335 closedir(U);
336
337 foreach my $data_source (@data_sources) {
338 # Within each data source, get a list of users with uploaded files.
339 my @users;
340 my $source_path = File::Spec->catfile($userdata_folder, $data_source);
341 opendir DS, $source_path;
342 while (my $folder = readdir(DS)) {
343 next if $folder =~ /^\.+$/;
344 next unless -d $folder;
345 my $user_path = File::Spec->catfile($userdata_folder, $data_source, $folder);
346 opendir USER, $user_path if -d $user_path;
347 next unless readdir(USER);
348 push @users, $folder;
349 closedir(USER);
350 }
351 closedir(DS);
352
353 foreach my $uploadsid (@users) {
354 # For each user, get the list of their files.
355 my @files;
356 my $user_path = File::Spec->catfile($userdata_folder, $data_source, $uploadsid);
357 opendir FILE, $user_path;
358 while (my $file = readdir(FILE)) {
359 next if $file =~ /^\.+$/;
360 next unless -d $file;
361 push @files, $file;
362 }
363 closedir(FILE);
364
365 # For each file, we have the data source and user - make sure the data source is present.
366 foreach my $file (@files) {
367 my @data_source_in_db = $database->selectrow_array("SELECT data_source FROM uploads WHERE path = ? AND userid = ?", undef, $file, $uploadsid);
368 unless (@data_source_in_db) {
369 print STDERR "missing source found.\n" unless $missing;
370 print STDERR "- Data Source not found for $file (owned by $uploadsid), ";
371 $database->do("UPDATE uploads SET data_source = ? WHERE path = ? AND userid = ?", undef, $data_source, $file, $uploadsid) or print STDERR "could not add to database.\n" . DBI->errstr;
372 print STDERR "added to database.\n" unless DBI->errstr;
373 $missing = 1;
374 }
375 }
376 }
377 }
378 print STDERR "all data sources are present.\n" unless $missing;
379 }
380  
381 # Check All Files () - Checks the integrity of the file data for every user.
382 sub check_all_files {
383 print STDERR "Checking for any files not in the database...";
384 $line_counter = 0;
385 # Get all data sources
386 my $userdata_folder = $globals->user_dir;
387 unless (-e $userdata_folder) {
388 print STDERR "no uploaded files to check.\n";
389 return;
390 }
391 my @data_sources;
392 opendir U, $userdata_folder;
393 while (my $dir = readdir(U)) {
394 next if $dir =~ /^\.+$/;
395 push @data_sources, $dir;
396 }
397 closedir(U);
398
399 my $all_ok = 1;
400 foreach my $data_source (@data_sources) {
401 # Within each data source, get a list of users with uploaded files.
402 my @uploads_ids;
403 my $source_path = File::Spec->catfile($userdata_folder, $data_source);
404 opendir DS, $source_path;
405 while (my $folder = readdir(DS)) {
406 next if $folder =~ /^\.+$/;
407 my $user_path = File::Spec->catfile($userdata_folder, $data_source, $folder);
408 opendir USER, $user_path;
409 next unless readdir(USER);
410 push @uploads_ids, $folder;
411 closedir(USER);
412 }
413 closedir(DS);
414  
415 foreach my $uploadsid (@uploads_ids) {
416 my $userid = check_uploadsid($source_path,$uploadsid) or next;
417 my $this_ok = check_files($userid,$uploadsid, $data_source);
418 $all_ok = $this_ok if $all_ok;
419 }
420 }
421 print STDERR "all files are accounted for.\n" if $all_ok;
422 }
423  
424 # remove dangling upload directories
425 sub check_uploadsid {
426 my ($source_path,$uploadsid) = @_;
427 return if $uploadsid eq 'shared_remote_tracks';
428 my ($userid) = $database->selectrow_array('select (userid) from session where uploadsid=?',
429 undef,$uploadsid);
430  
431 unless ($userid) {
432 print STDERR "\n" unless $line_counter++;
433 print STDERR "Uploadsid $uploadsid has no corresponding user. Removing.\n";
434 rmtree(File::Spec->catfile($source_path,$uploadsid));
435 return;
436 }
437 return $userid;
438 }
439  
440 # Check Files (Uploads ID, Data Source) - Makes sure a user's files are in the database, add them if not.
441 sub check_files {
442 my $userid = shift or die "No user ID given, please check the gbrowse_metadb_config.pl script.\n";
443 my $uploadsid = shift or die "No uploads ID given, please check the gbrowse_metadb_config.pl script.\n";
444 my $data_source = shift or die "No data source given, please check the gbrowse_metadb_config.pl script.\n";
445
446 # Get the files from the database.
447 my $files_in_db = $database->selectcol_arrayref("SELECT path FROM uploads WHERE userid=? AND data_source=?",
448 undef, $userid, $data_source);
449 my @files_in_db = @$files_in_db;
450
451 # Get the files in the folder.
452 my $path = $globals->user_dir($data_source, $uploadsid);
453 my @files_in_folder;
454 opendir D, $path;
455 while (my $dir = readdir(D)) {
456 next if $dir =~ /^\.+$/;
457 push @files_in_folder, $dir;
458 }
459 closedir(D);
460
461 my $all_ok = 1;
462 foreach my $file (@files_in_folder) {
463 my $found = grep(/$file/, @files_in_db);
464 unless ($found) {
465 print STDERR "\n" unless $line_counter++;
466 add_file($file, $userid, $uploadsid, $data_source, $file) &&
467 print STDERR "- File \"$file\" found in the \"$data_source/$uploadsid\" folder without metadata, added to database.\n";
468 $all_ok = 0;
469 }
470 }
471 return $all_ok;
472 }
473  
474 # Fix Permissions () - Grants the web user the required privileges on all databases.
475 sub fix_permissions {
476 my (undef, $db_name) = $dsn =~ /.*:(database=)?([^;]+)/;
477 $db_name ||= "gbrowse_login";
478 ($type) = $dsn =~ /^dbi:([^:]+)/i unless defined $type;
479  
480 if ($type =~ /mysql/i) {
481 my ($db_user) = $dsn =~ /user=([^;]+)/i;
482 my ($db_pass) = $dsn =~ /password=([^;]+)/i;
483 $db_pass ||= '';
484 warn "GRANT ALL PRIVILEGES on $db_name.* TO '$db_user'\@'%' IDENTIFIED BY '$db_pass'";
485 $database->do("GRANT ALL PRIVILEGES on $db_name.* TO '$db_user'\@'%' IDENTIFIED BY '$db_pass'")
486 or die DBI->errstr;
487 }
488 }
489  
490 sub fix_session_permissions {
491 print STDERR "Fixing permissions in sessions directory\n";
492 my $globals = Bio::Graphics::Browser2->open_globals;
493 my $session_dir = $globals->session_dir;
494 my $webuser = GBrowse::ConfigData->config('wwwuser');
495 system "sudo chown -R $webuser $session_dir";
496 }
497  
498 sub fix_sqlite_permissions {
499 my (undef, $db_name) = $dsn =~ /.*:(database=)?([^;]+)/;
500 $db_name ||= "gbrowse_login";
501  
502 my ($path) = $dsn =~ /dbname=([^;]+)/i;
503 ($path) = $dsn =~ /DBI:SQLite:([^;]+)/i unless $path;
504 die "Couldn't figure out location of database index from $dsn" unless $path;
505  
506 my $user = GBrowse::ConfigData->config('wwwuser');
507 my $group = get_group_from_user($user);
508  
509 my $dir = dirname($path);
510 unless (-e $dir) {
511 my $parent = dirname($dir);
512 if (-w $parent) {
513 mkdir $parent;
514 } else {
515 print STDERR "Using sudo to create $parent directory. You may be prompted for your login password now.\n";
516 system "sudo mkdir $parent";
517 }
518 }
519 my $file_owner = -e $path ? getpwuid((stat($path))[4]) : '';
520 my $dir_owner = -e $dir ? getpwuid((stat($dir))[4]) : '';
521  
522 # Check if we need to, to avoid unnecessary printing/sudos.
523 unless ($group) {
524 print STDERR "Unable to look up group for $user. Will not change ownerships on $path.\n";
525 print STDERR "You should do this manually to give the Apache web server read/write access to $path.\n";
526 return;
527 }
528  
529 if (-e $path && $user ne $file_owner) {
530 print STDERR "Using sudo to set $path ownership to $user:$group. You may be prompted for your login password now.\n";
531 system "sudo chown $user $path" ;
532 system "sudo chgrp $group $path";
533 system "sudo chmod 0644 $path";
534 }
535 if (-e $dir && $user ne $dir_owner) {
536 print STDERR "Using sudo to set $dir ownership to $user:$group. You may be prompted for your login password now.\n";
537 system "sudo chown $user $dir";
538 system "sudo chgrp $group $dir";
539 system "sudo chmod 0755 $dir";
540 }
541 }
542  
543 # Create Database() - Creates the database specified (or the default gbrowse_login database).
544 sub create_mysql_database {
545 my (undef, $db_name) = $dsn =~ /.*:(database=)?([^;]+)/;
546 $db_name ||= "gbrowse_login";
547 unless (DBI->connect($dsn)) {
548 if ($dsn =~ /mysql/i) {
549 print STDERR "Could not log into $db_name database, creating and/or fixing login permissions...\n";
550
551 my ($admin_user, $admin_pass);
552 if ($admin) {
553 ($admin_user) = $admin =~ /^(.*):/;
554 ($admin_pass) = $admin =~ /:(.*)$/;
555 }
556
557 $admin_user ||= prompt("Please enter the MySQL administrator user", "root");
558 $admin_pass ||= prompt("Please enter the MySQL administrator password", "",1);
559  
560 my ($db_user) = $dsn =~ /user=([^;]+)/i;
561 my ($db_pass) = $dsn =~ /password=([^;]+)/i;
562 $db_pass ||= '';
563  
564 my $test_dbi = DBI->connect("DBI:mysql:database=mysql;user=$admin_user;password=$admin_pass;");
565 $test_dbi->do("CREATE DATABASE IF NOT EXISTS $db_name");
566 $test_dbi->do("GRANT ALL PRIVILEGES on $db_name.* TO '$db_user'\@'%' IDENTIFIED BY '$db_pass'");
567 print STDERR "Database created!\n" unless DBI->errstr;
568 }
569 }
570 # SQLite will create the file/database upon first connection.
571 }
572  
573 # Add File (Full Path, Owner's Uploads ID, Data Source) - Adds $file to the database under a specified owner.
574 # Database.pm's add_file() is dependant too many outside variables, not enough time to re-structure.
575 sub add_file {
576 my $filename = shift;
577 my $userid = shift;
578 my $uploadsid = shift;
579 my $data_source = shift;
580 my $full_path = shift;
581  
582 my $imported = ($filename =~ /^(ftp|http|das)_/)? 1 : 0;
583 my $description = "";
584 my $shared = "private";
585  
586 my $trackid = md5_hex($uploadsid.$filename.$data_source);
587 my $now = nowfun();
588 $database->do("INSERT INTO uploads (trackid, userid, path, description, imported, creation_date, modification_date, sharing_policy, data_source) VALUES (?, ?, ?, ?, ?, $now, $now, ?, ?)", undef, $trackid, $userid, $filename, $description, $imported, $shared, $data_source);
589 return $trackid;
590 }
591  
592 # Now Function - return the database-dependent function for determining current date & time
593 sub nowfun {
594 return ($type =~ /sqlite/i)? "datetime('now','localtime')" : 'NOW()';
595 }
596  
597 # Escape Enums (type string) - If the string contains an ENUM, returns a compatible data type that works with SQLite.
598 sub escape_enums {
599 my $string = shift;
600 # SQLite doesn't support ENUMs, so convert to a varchar.
601 if ($string =~ /^ENUM\(/i) {
602 #Check for any suffixes - "NOT NULL" or whatever.
603 my @options = ($string =~ m/^ENUM\('(.*)'\)/i);
604 my @suffix = ($string =~ m/([^\)]+)$/);
605 my @values = split /',\w*'/, $options[0];
606 my $length = List::Util::max(map length $_, @values);
607 $string = "varchar($length)" . $suffix[0];
608 }
609 return $string;
610 }
611  
612 # Asks q question and sets a default - blatantly stolen (& modified) from Module::Build.
613 sub prompt {
614 my $mess = shift
615 or die "prompt() called without a prompt message";
616 my ($default,$hide) = @_;
617  
618 print STDERR "$mess [$default] ";
619 my $ans;
620 if ($hide) {
621 eval {
622 use Term::ReadKey;
623 ReadMode('noecho');
624 $ans = ReadLine(0);
625 ReadMode('normal');
626 print STDERR "\n";
627 };
628 }
629 $ans ||= <STDIN>;
630 chomp $ans if defined $ans;
631  
632 if (!defined($ans) || !length($ans)) {
633 print STDERR "$default\n";
634 $ans = $default;
635 }
636 return $ans;
637 }
638  
639 sub get_group_from_user {
640 my $user = shift;
641 my (undef,undef,undef,$gid) = $user =~ /^\d+$/ ? getpwuid($user)
642 : getpwnam($user);
643 $gid or return;
644 my $group = getgrgid($gid);
645 return $group;
646 }
647  
648 sub upgrade_schema {
649 my $new_version = shift;
650  
651 # probe whether this is a completely empty database
652 {
653 local $database->{PrintWarn} = 0;
654 local $database->{PrintError} = 0;
655 my ($count) = $database->selectrow_array('select count(*) from users');
656 if (!defined $count) {
657 check_table('dbinfo',$dbinfo_columns);
658 set_schema_version('dbinfo',$new_version);
659 return;
660 }
661 }
662  
663 my ($old_version) = $database->selectrow_array('SELECT MAX(schema_version) FROM dbinfo LIMIT 1');
664 unless ($old_version) {
665 # table is missing, so add it
666 check_table('dbinfo',$dbinfo_columns);
667 $old_version = 0;
668 }
669 backup_database() unless $old_version == $new_version;
670 for (my $i=$old_version;$i<$new_version;$i++) {
671 my $function = "upgrade_from_${i}_to_".($i+1);
672 eval "$function();1" or die "Can't upgrade from version $i to version ",$i+1;
673 }
674 set_schema_version('dbinfo',$new_version);
675 }
676  
677 sub backup_database {
678 my $temp = File::Spec->tmpdir;
679 if ($type =~ /sqlite/i) {
680 my ($src) = $dsn =~ /dbname=([^;]+)/i;
681 unless ($src) {
682 ($src) = $dsn =~ /DBI:SQLite:([^;]+)/i;
683 }
684 my $time = localtime;
685 my $basename = basename($src);
686 my $dest = strftime("$temp/${basename}_%d%b%Y.%H:%M",localtime);
687 warn "backing up existing users database to $dest";
688 system ('cp',$src,$dest);
689 } elsif ($type =~ /mysql/i) {
690 my $dest = strftime("$temp/gbrowse_users_%d%b%Y.%H:%M",localtime);
691 warn "backing up existing users database to ./$dest";
692 my ($src) = $dsn =~ /dbname=([^;]+)/i;
693 unless ($src) {
694 (undef, $src) = $dsn =~ /.*:(database=)?([^;]+)/i;
695 }
696
697 my ($db_user) = $dsn =~ /user=([^;]+)/i;
698 my ($db_pass) = $dsn =~ /password=([^;]+)/i;
699 $db_pass ||= '';
700 no warnings;
701 open SAVEOUT,">&STDOUT";
702 open STDOUT,">$dest" or die "$dest: $!";
703 system('mysqldump',"--user=$db_user","--password=$db_pass",$src);
704 open STDOUT,">&SAVEOUT";
705 } else {
706 die "Don't know how to backup this driver";
707 }
708 }
709  
710 sub set_schema_version {
711 my ($table,$version) = @_;
712 local $database->{AutoCommit} = 0;
713 local $database->{RaiseError} = 1;
714 eval {
715 $database->do("delete from $table");
716 $database->do("insert into $table (schema_version) values ($version)");
717 $database->commit();
718 };
719 if ($@) {
720 warn "update failed due to $@. Rolling back";
721 eval {$database->rollback()};
722 die "Can't continue";
723 }
724 }
725  
726 ############################## one function to upgrade each level
727 sub upgrade_from_0_to_1 {
728  
729 # create dbinfo table
730 check_table("dbinfo", $dbinfo_columns);
731  
732 local $database->{AutoCommit} = 0;
733 local $database->{RaiseError} = 1;
734 eval {
735 # this upgrades the original users table to the last version
736 # before the session table was added
737 check_table('users',$old_users_columns);
738  
739 # this creates the new session table
740 check_table("session", $session_columns);
741 check_table("users_new", $users_columns);
742  
743 # query to pull old data out of original users table
744 my $select = $database->prepare(<<END ) or die $database->errstr;
745 SELECT userid,uploadsid,username,email,pass,remember,openid_only,
746 confirmed,cnfrm_code,last_login,created
747 FROM users
748 END
749 ;
750
751 # query to insert data into new session table
752 my $insert_session = $database->prepare(<<END ) or die $database->errstr;
753 REPLACE INTO session (username,sessionid,uploadsid)
754 VALUES (?,?,?)
755 END
756 ;
757  
758 # query to insert data into new users table
759 my $insert_user = $database->prepare(<<END ) or die $database->errstr;
760 REPLACE INTO users_new (userid, email, pass, remember,
761 openid_only, confirmed, cnfrm_code, last_login, created)
762 VALUES (?,?,?,?,?,?,?,?,?)
763 END
764 ;
765 $select->execute() or die $database->errstr;
766 my %uploadsid_to_userid;
767  
768 while (my ($sessionid,$uploadsid,$username,@rest) = $select->fetchrow_array()) {
769 $insert_session->execute($username,$sessionid,$uploadsid)
770 or die $database->errstr;
771 my $userid = $database->last_insert_id('','','','') or die "Didn't get an autoincrement ID!";
772 $insert_user->execute($userid,@rest) or die $database->errstr;
773 $uploadsid_to_userid{$uploadsid}=$userid;
774 }
775 $select->finish;
776 $insert_session->finish;
777 $insert_user->finish;
778 # rename the current users table
779 $database->do('drop table users')
780 or die "Couldn't drop old users table";
781 $database->do('alter table users_new rename to users')
782 or die "Couldn't rename new users table";
783 $database->do('create index index_session on session(username)')
784 or die "Couldn't index sessions table";
785  
786 # now do the uploads table
787 # this upgrades to latest version 0
788 check_table('uploads', $old_uploads_columns);
789 check_table("uploads_new", $uploads_columns);
790  
791 $select = $database->prepare(<<END ) or die $database->errstr;
792 SELECT uploadid,userid,path,title,description,imported,
793 creation_date,modification_date,sharing_policy,users,
794 public_users,public_count,data_source
795 FROM uploads
796 END
797 ;
798 my $insert = $database->prepare(<<END ) or die $database->errstr;
799 REPLACE INTO uploads_new (trackid,userid,path,title,description,imported,
800 creation_date,modification_date,sharing_policy,users,
801 public_users,public_count,data_source)
802 VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
803 END
804 ;
805
806 $select->execute();
807 while (my ($trackid,$uploadsid,@rest) = $select->fetchrow_array()) {
808 my $uid = $uploadsid_to_userid{$uploadsid};
809 unless ($uid) {
810 print STDERR "Found an upload from uploadsid=$uploadsid, but there is no corresponding user. Skipping...\n";
811 next;
812 }
813 $insert->execute($trackid,$uid,@rest)
814 or die $database->errstr;
815 }
816 $select->finish();
817 $insert->finish();
818  
819 $database->do('drop table uploads')
820 or die "Couldn't drop old uploads table";
821 $database->do('alter table uploads_new rename to uploads')
822 or die "Couldn't rename new uploads table";
823  
824 # now do the openid_users table
825 # this creates the new one
826 check_table('openid_users', $openid_columns);
827 check_table('openid_users_new', $openid_columns);
828 $select = $database->prepare(<<END ) or die $database->errstr;
829 SELECT b.sessionid,a.openid_url,b.userid
830 FROM openid_users as a,session as b
831 WHERE a.userid=b.userid
832 END
833 ;
834 $insert = $database->prepare(<<END ) or die $database->errstr;
835 REPLACE INTO openid_users_new(userid,openid_url) VALUES (?,?)
836 END
837 ;
838  
839 $select->execute() or die $select->errstr;
840 while (my ($sessionid,$url,$userid) = $select->fetchrow_array()) {
841 $insert->execute($userid,$url) or die $insert->errstr;
842 }
843  
844 $select->finish();
845 $insert->finish();
846 $database->do('drop table openid_users')
847 or die "Couldn't drop old openid_users table: ",$database->errstr;
848 $database->do('alter table openid_users_new rename to openid_users')
849 or die "Couldn't rename new openid_users table: ",$database->errstr;
850  
851 $database->commit();
852 };
853 if ($@) {
854 warn "upgrade failed due to $@. Rolling back";
855 eval {$database->rollback()};
856 die "Can't continue";
857 } else {
858 print STDERR "Successfully upgraded schema from 0 to 1.\n";
859 }
860 }
861  
862 sub upgrade_from_1_to_2 {
863 # Create sharing table.
864 check_table("sharing", $sharing_columns);
865  
866 local $database->{AutoCommit} = 0;
867 local $database->{RaiseError} = 1;
868 eval {
869  
870 # Upgrade sharing table from
871 my $select = $database->prepare("SELECT trackid, users, public_users FROM uploads") or die $database->errstr;
872 $select->execute();
873 my $run = 0;
874 while (my ($trackid, $users, $public_users) = $select->fetchrow_array()) {
875 my @users = split ", ", $users if $users;
876 my @public_users = split ", ", $public_users if $public_users;
877
878 $database->do("INSERT INTO sharing (trackid, userid, public) VALUES (?, ?, ?)", undef, $trackid, $_, 0) foreach @users;
879 $database->do("INSERT INTO sharing (trackid, userid, public) VALUES (?, ?, ?)", undef, $trackid, $_, 1) foreach @public_users;
880 $run = 1 if ($users || $public_users);
881 }
882
883 # Now delete the users & public_users columns from the database.
884 check_table("uploads", $uploads_columns);
885
886 $select->finish();
887 $database->commit() if $run;
888 };
889  
890 if ($@) {
891 warn "upgrade failed due to $@. Rolling back";
892 eval {$database->rollback()};
893 die "Can't continue";
894 } else {
895 print STDERR "Successfully upgraded schema from 1 to 2.\n";
896 }
897 }
898  
899 sub upgrade_from_2_to_3 {
900 # add the gecos field
901 check_table('users',$users_columns);
902 }
903  
904 sub upgrade_from_3_to_4 {
905 # change the size of the password table in the users table
906 local $database->{AutoCommit} = 0;
907 local $database->{RaiseError} = 1;
908 eval {
909 check_table("users_new",$users_columns);
910 my $select = $database->prepare(<<END ) or die $database->errstr;
911 SELECT userid,email,pass,gecos,remember,openid_only,confirmed,cnfrm_code,last_login,created
912 FROM users
913 END
914 ;
915 # query to insert data into new users table
916 my $insert = $database->prepare(<<END ) or die $database->errstr;
917 REPLACE INTO users_new (userid,email,pass,gecos,remember,openid_only,confirmed,cnfrm_code,last_login,created)
918 VALUES (?,?,?,?,?,?,?,?,?,?)
919 END
920 ;
921 $select->execute();
922 while (my @cols = $select->fetchrow_array) {
923 $insert->execute(@cols);
924 }
925 $select->finish;
926 $insert->finish;
927 $database->do('drop table users')
928 or die "Couldn't drop old users table";
929  
930 $database->do('alter table users_new rename to users')
931 or die "Couldn't rename new users table";
932 $database->commit();
933 };
934
935 if ($@) {
936 warn "upgrade failed due to $@. Rolling back";
937 eval {$database->rollback()};
938 die "Can't continue";
939 } else {
940 print STDERR "Successfully upgraded schema from 3 to 4.\n";
941 }
942 }
943  
944  
945 __END__