6 unshift(@INC, $FindBin::Bin . '/../modules/override'); # Use our own versions of various modules (e.g. YAML).
7 push (@INC, $FindBin::Bin . '/..');
8 push (@INC, $FindBin::Bin . '/../modules/fallback'); # Only use our own versions of modules if there's no system version.
15 use English '-no_match_vars';
26 SL::LxOfficeConf->read;
27 our $lxdebug = LXDebug->new();
41 my ($opt_list, $opt_tree, $opt_rtree, $opt_nodeps, $opt_graphviz, $opt_help);
42 my ($opt_user, $opt_client, $opt_apply, $opt_applied, $opt_unapplied, $opt_format, $opt_test_utf8);
43 my ($opt_dbhost, $opt_dbport, $opt_dbname, $opt_dbuser, $opt_dbpassword, $opt_create, $opt_type);
44 my ($opt_description, @opt_depends, $opt_auth_db);
46 our (%myconfig, $form, $user, $auth, $locale, $controls, $dbupgrader);
49 return $auth if $auth;
51 $auth = SL::Auth->new;
52 if (!$auth->session_tables_present) {
53 $form->error("The session and user management tables are not present in the authentication database. Please use the administration web interface to create them.");
60 my $help_text = <<"END_HELP"
61 dbupgrade2_tool.pl [options]
63 A validation and information tool for the database upgrade scripts
64 in \'sql/Pg-upgrade2\'.
66 At startup dbupgrade2_tool.pl will always check the consistency
67 of all database upgrade scripts (e.g. circular references, invalid
68 formats, missing meta information). You can but don\'t have to specifiy
72 --list Lists all database upgrade tags
73 --tree Lists all database upgrades in tree form
74 --rtree Lists all database upgrades in reverse tree form
75 --graphviz[=file] Create a Postscript document showing a tree of
76 all database upgrades and their dependencies.
77 If no file name is given then the output is
78 written to \'db_dependencies.png\'.
79 --format=... Format for the graphviz output. Defaults to
80 \'png\'. All values that the command \'dot\' accepts
81 for it\'s option \'-T\' are acceptable.
82 --nodeps List all database upgrades that no other upgrade
84 --create=tag Creates a new upgrade with the supplied tag. This
85 action accepts several optional other options. See
86 the option section for those. After creating the
87 upgrade file your \$EDITOR will be called with it.
88 --apply=tag Applies the database upgrades \'tag\' and all
89 upgrades it depends on. If \'--apply\' is used
90 then the option \'--user\' must be used as well.
91 --applied List the applied database upgrades for the
92 database that the user given with \'--user\' uses.
93 --unapplied List the database upgrades that haven\'t been applied
94 yet to the database that the user given with
96 --test-utf8 Tests a PostgreSQL cluster for proper UTF-8 support.
97 You have to specify the database to test with the
98 parameters --dbname, --dbhost, --dbport, --dbuser
100 --help Show this help and exit.
103 --client=id-or-name The name (or database ID) of the client to use for
104 database connectivity. You must provide both a client
106 --user=name The name of the user configuration to use for
107 database connectivity. You must provide both a client
109 --auth-db Work on the authentication database instead of a
111 --dbname=name Database connection options for the UTF-8
112 --dbhost=host handling test.
117 Options for --create:
118 --type \'sql\' or \'pl\'. Defaults to sql.
119 --description The description field of the generated upgrade.
120 --depends Tags of upgrades which this upgrade depends upon.
121 Defaults to the latest stable release upgrade.
122 Multiple values possible.
135 sub calc_rev_depends {
136 map { $_->{rev_depends} = []; } values %{ $controls };
138 foreach my $control (values %{ $controls }) {
139 map { push @{ $controls->{$_}->{rev_depends} }, $control->{tag} } @{ $control->{depends} };
144 my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
146 print "LIST VIEW\n\n" .
147 "number tag depth priority\n";
150 foreach (@sorted_controls) {
151 print "$i $_->{tag} $_->{depth} $_->{priority}\n";
159 my ($tag, $depth) = @_;
161 print " " x $depth . $tag . "\n";
163 foreach my $dep_tag (@{ $controls->{$tag}->{depends} }) {
164 dump_node($dep_tag, $depth + 1);
169 print "TREE VIEW\n\n";
173 my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
175 foreach my $control (@sorted_controls) {
176 dump_node($control->{tag}, "") unless (@{ $control->{rev_depends} });
182 sub dump_node_reverse {
183 my ($tag, $depth) = @_;
185 print " " x $depth . $tag . "\n";
187 foreach my $dep_tag (@{ $controls->{$tag}->{rev_depends} }) {
188 dump_node_reverse($dep_tag, $depth + 1);
192 sub dump_tree_reverse {
193 print "REVERSE TREE VIEW\n\n";
197 my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
199 foreach my $control (@sorted_controls) {
200 last if ($control->{depth} > 1);
201 dump_node_reverse($control->{tag}, "");
210 my $format = $params{format} || "png";
211 my $file_name = $params{file_name} || "db_dependencies.${format}";
213 print "GRAPHVIZ OUTPUT -- format: ${format}\n\n";
214 print "Output will be written to '${file_name}'\n";
218 my $dot = "|dot -T${format} ";
219 open OUT, "${dot}> \"${file_name}\"" || die;
222 "digraph db_dependencies {\n" .
223 "graph [size=\"16.53,11.69!\"];\n" .
224 "node [shape=box style=filled fillcolor=white];\n";
227 foreach my $c (values %{ $controls }) {
228 $ranks{$c->{depth}} ||= [];
230 my ($pre, $post) = @{ $c->{rev_depends} } ? ('')x2 :
231 (map "node [fillcolor=$_] ", qw(lightgray white));
233 push @{ $ranks{$c->{"depth"}} }, qq|${pre}"$c->{tag}"; ${post}|;
236 foreach (sort keys %ranks) {
237 print OUT "{ rank = same; ", join("", @{ $ranks{$_} }), " }\n";
240 foreach my $c (values %{ $controls }) {
241 print OUT qq|"$c->{tag}";\n|;
243 foreach my $d (@{ $c->{depends} }) {
244 print OUT qq|"$c->{tag}" -> "$d";\n|;
255 print "SCRIPTS NO OTHER SCRIPTS DEPEND ON\n\n" .
256 join("\n", map { $_->{tag} } grep { !scalar @{ $_->{rev_depends} } } values %{ $controls }) .
263 my $filename = $params{filename};
264 my $dbupgrader = $params{dbupgrader};
265 my $type = $params{type} || 'sql';
266 my $description = $params{description} || '';
267 my @depends = @{ $params{depends} };
269 my $encoding = 'utf-8';
272 my @releases = grep { /^release_/ } keys %$controls;
273 @depends = ((sort @releases)[-1]);
277 if ($type eq 'sql') {
279 } elsif ($type eq 'pl') {
282 die 'Error: No --type was given but is required for --create.';
284 die 'Error: Unknown --type. Try "sql" or "pl".';
287 my $full_filename = $dbupgrader->path . '/' . $filename . '.' . $type;
289 die "file '$full_filename' already exists, aborting" if -f $full_filename;
292 open my $fh, ">:encoding($encoding)", $full_filename or die "can't open $full_filename";
293 print $fh "$comment \@tag: $filename\n";
294 print $fh "$comment \@description: $description\n";
295 print $fh "$comment \@depends: @depends\n";
298 print $fh "package SL::DBUpgrade2::$filename;\n";
300 print $fh "use strict;\n";
301 print $fh "use utf8;\n" if $encoding =~ /utf.?8/i;
303 print $fh "use parent qw(SL::DBUpgrade2::Base);\n";
305 print $fh "sub run {\n";
306 print $fh " my (\$self) = \@_;\n";
315 print "File $full_filename created.\n";
317 system("\$EDITOR $full_filename");
324 my (@order, %tags, @all_tags);
326 if ($name eq "ALL") {
328 @all_tags = map { $_->{tag} } grep { !@{$_->{rev_depends}} } values %{ $controls };
331 $form->error("Unknown dbupgrade tag '$name'") if (!$controls->{$name});
335 foreach my $tag (@all_tags) {
336 build_upgrade_order($tag, \@order, \%tags);
339 my @upgradescripts = map { $controls->{$_}->{applied} = 0; $controls->{$_} } @order;
341 my $dbh = $opt_auth_db ? connect_auth()->dbconnect : $form->dbconnect_noauto(\%myconfig);
342 $dbh->{AutoCommit} = 0;
344 $dbh->{PrintWarn} = 0;
345 $dbh->{PrintError} = 0;
347 $user->create_schema_info_table($form, $dbh);
349 my $query = qq|SELECT tag FROM schema_info|;
350 my $sth = $dbh->prepare($query);
351 $sth->execute() || $form->dberror($query);
352 while (my ($tag) = $sth->fetchrow_array()) {
353 $controls->{$tag}->{applied} = 1 if defined $controls->{$tag};
357 @upgradescripts = sort { $a->{priority} <=> $b->{priority} } grep { !$_->{applied} } @upgradescripts;
358 if (!@upgradescripts) {
359 print "The upgrade has already been applied.\n";
363 foreach my $control (@upgradescripts) {
364 $control->{file} =~ /\.(sql|pl)$/;
368 print "Applying upgrade $control->{file}\n";
370 if ($file_type eq "sql") {
371 $dbupgrader->process_query($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
373 $dbupgrader->process_perl_script($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
377 $dbh->disconnect unless $opt_auth_db;
380 sub dump_sql_result {
381 my ($results, $column_order) = @_;
383 my %column_lengths = map { $_, length $_ } keys %{ $results->[0] };
385 foreach my $row (@{ $results }) {
386 map { $column_lengths{$_} = length $row->{$_} if (length $row->{$_} > $column_lengths{$_}) } keys %{ $row };
390 if ($column_order && scalar @{ $column_order }) {
391 @sorted_names = @{ $column_order };
393 @sorted_names = sort keys %column_lengths;
396 my $format = join('|', map { '%-' . $column_lengths{$_} . 's' } @sorted_names) . "\n";
398 printf $format, @sorted_names;
399 print join('+', map { '-' x $column_lengths{$_} } @sorted_names) . "\n";
401 foreach my $row (@{ $results }) {
402 printf $format, map { $row->{$_} } @sorted_names;
404 printf "(\%d row\%s)\n", scalar @{ $results }, scalar @{ $results } > 1 ? 's' : '';
410 my $dbh = $opt_auth_db ? connect_auth()->dbconnect : $form->dbconnect_noauto(\%myconfig);
411 $dbh->{AutoCommit} = 0;
413 $dbh->{PrintWarn} = 0;
414 $dbh->{PrintError} = 0;
416 $user->create_schema_info_table($form, $dbh);
418 my $query = qq|SELECT tag, login, itime FROM schema_info ORDER BY itime|;
419 my $sth = $dbh->prepare($query);
420 $sth->execute() || $form->dberror($query);
421 while (my $ref = $sth->fetchrow_hashref()) {
426 $dbh->disconnect unless $opt_auth_db;
428 if (!scalar @results) {
429 print "No database upgrades have been applied yet.\n";
431 dump_sql_result(\@results, [qw(tag login itime)]);
438 my $dbh = $opt_auth_db ? connect_auth()->dbconnect : $form->dbconnect_noauto(\%myconfig);
440 $dbh->{PrintWarn} = 0;
441 $dbh->{PrintError} = 0;
443 my @unapplied = $dbupgrader->unapplied_upgrade_scripts($dbh);
445 $dbh->disconnect unless $opt_auth_db;
447 if (!scalar @unapplied) {
448 print "All database upgrades have been applied.\n";
450 print map { $_->{tag} . "\n" } @unapplied;
454 sub build_upgrade_order {
459 my $control = $controls->{$name};
461 foreach my $dependency (@{ $control->{depends} }) {
462 next if $tags->{$dependency};
463 $tags->{$dependency} = 1;
464 build_upgrade_order($dependency, $order, $tags);
467 push @{ $order }, $name;
475 $locale = Locale->new;
477 $::request = SL::Request->new(
479 layout => SL::Layout::None->new,
486 GetOptions("list" => \$opt_list,
487 "tree" => \$opt_tree,
488 "rtree" => \$opt_rtree,
489 "nodeps" => \$opt_nodeps,
490 "graphviz:s" => \$opt_graphviz,
491 "format:s" => \$opt_format,
492 "user=s" => \$opt_user,
493 "client=s" => \$opt_client,
494 "apply=s" => \$opt_apply,
495 "applied" => \$opt_applied,
496 "create=s" => \$opt_create,
497 "type=s" => \$opt_type,
498 "description=s" => \$opt_description,
499 "depends=s" => \@opt_depends,
500 "unapplied" => \$opt_unapplied,
501 "test-utf8" => \$opt_test_utf8,
502 "dbhost:s" => \$opt_dbhost,
503 "dbport:s" => \$opt_dbport,
504 "dbname:s" => \$opt_dbname,
505 "dbuser:s" => \$opt_dbuser,
506 "dbpassword:s" => \$opt_dbpassword,
507 "auth-db" => \$opt_auth_db,
508 "help" => \$opt_help,
511 show_help() if ($opt_help);
513 $dbupgrader = SL::DBUpgrade2->new(form => $form, auth => $opt_auth_db);
514 $controls = $dbupgrader->parse_dbupdate_controls->{all_controls};
516 dump_list() if ($opt_list);
517 dump_tree() if ($opt_tree);
518 dump_tree_reverse() if ($opt_rtree);
519 dump_graphviz('file_name' => $opt_graphviz,
520 'format' => $opt_format) if (defined $opt_graphviz);
521 dump_nodeps() if ($opt_nodeps);
522 create_upgrade(filename => $opt_create,
523 dbupgrader => $dbupgrader,
525 description => $opt_description,
526 depends => \@opt_depends) if ($opt_create);
528 if ($opt_client && !connect_auth()->set_client($opt_client)) {
529 $form->error($form->format_string("The client '#1' does not exist.", $opt_client));
533 $form->error("Need a client, too.") if !$auth || !$auth->client;
535 %myconfig = connect_auth()->read_user(login => $opt_user);
537 if (!$myconfig{login}) {
538 $form->error($form->format_string("The user '#1' does not exist.", $opt_user));
541 $locale = new Locale($myconfig{countrycode}, "all");
542 $user = new User(login => $opt_user);
544 map { $form->{$_} = $myconfig{$_} } keys %myconfig;
548 $form->error("--apply used but no user name given with --user.") if !$user && !$opt_auth_db;
549 apply_upgrade($opt_apply);
553 $form->error("--applied used but no user name given with --user.") if !$user && !$opt_auth_db;
557 if ($opt_unapplied) {
558 $form->error("--unapplied used but no user name given with --user.") if !$user && !$opt_auth_db;
563 if ($opt_test_utf8) {
564 $form->error("--test-utf8 used but no database name given with --dbname.") if (!$opt_dbname);
566 my $umlaut_upper = 'Ä';
568 my $dbconnect = "dbi:Pg:dbname=${opt_dbname}";
569 $dbconnect .= ";host=${opt_dbhost}" if ($opt_dbhost);
570 $dbconnect .= ";port=${opt_dbport}" if ($opt_dbport);
572 my $dbh = DBI->connect($dbconnect, $opt_dbuser, $opt_dbpassword, { pg_enable_utf8 => 1 });
574 $form->error("UTF-8 test: Database connect failed (" . $DBI::errstr . ")") if (!$dbh);
576 my ($umlaut_lower) = $dbh->selectrow_array(qq|SELECT lower(?)|, undef, $umlaut_upper);
580 if ($umlaut_lower eq 'ä') {
581 print "UTF-8 test was successful.\n";
582 } elsif ($umlaut_lower eq 'Ä') {
583 print "UTF-8 test was NOT successful: Umlauts are not modified (this might be partially ok, but you should probably not use UTF-8 on this cluster).\n";
585 print "UTF-8 test was NOT successful: Umlauts are destroyed. Do not use UTF-8 on this cluster.\n";