6 unshift(@INC, $FindBin::Bin . '/../modules/override'); # Use our own versions of various modules (e.g. YAML).
7 push (@INC, $FindBin::Bin . '/..');
14 use English '-no_match_vars';
25 SL::LxOfficeConf->read;
26 our $lxdebug = LXDebug->new();
40 my ($opt_list, $opt_tree, $opt_rtree, $opt_nodeps, $opt_graphviz, $opt_help);
41 my ($opt_user, $opt_client, $opt_apply, $opt_applied, $opt_unapplied, $opt_format, $opt_test_utf8);
42 my ($opt_dbhost, $opt_dbport, $opt_dbname, $opt_dbuser, $opt_dbpassword, $opt_create, $opt_type);
43 my ($opt_description, @opt_depends, $opt_auth_db);
45 our (%myconfig, $form, $user, $auth, $locale, $controls, $dbupgrader);
48 return $auth if $auth;
50 $auth = SL::Auth->new;
51 if (!$auth->session_tables_present) {
52 $form->error("The session and user management tables are not present in the authentication database. Please use the administration web interface to create them.");
59 my $help_text = <<"END_HELP"
60 dbupgrade2_tool.pl [options]
62 A validation and information tool for the database upgrade scripts
63 in \'sql/Pg-upgrade2\'.
65 At startup dbupgrade2_tool.pl will always check the consistency
66 of all database upgrade scripts (e.g. circular references, invalid
67 formats, missing meta information). You can but don\'t have to specifiy
71 --list Lists all database upgrade tags
72 --tree Lists all database upgrades in tree form
73 --rtree Lists all database upgrades in reverse tree form
74 --graphviz[=file] Create a Postscript document showing a tree of
75 all database upgrades and their dependencies.
76 If no file name is given then the output is
77 written to \'db_dependencies.png\'.
78 --format=... Format for the graphviz output. Defaults to
79 \'png\'. All values that the command \'dot\' accepts
80 for it\'s option \'-T\' are acceptable.
81 --nodeps List all database upgrades that no other upgrade
83 --create=tag Creates a new upgrade with the supplied tag. This
84 action accepts several optional other options. See
85 the option section for those. After creating the
86 upgrade file your \$EDITOR will be called with it.
87 --apply=tag Applies the database upgrades \'tag\' and all
88 upgrades it depends on. If \'--apply\' is used
89 then the option \'--user\' must be used as well.
90 --applied List the applied database upgrades for the
91 database that the user given with \'--user\' uses.
92 --unapplied List the database upgrades that haven\'t been applied
93 yet to the database that the user given with
95 --test-utf8 Tests a PostgreSQL cluster for proper UTF-8 support.
96 You have to specify the database to test with the
97 parameters --dbname, --dbhost, --dbport, --dbuser
99 --help Show this help and exit.
102 --client=id-or-name The name (or database ID) of the client to use for
103 database connectivity. You must provide both a client
105 --user=name The name of the user configuration to use for
106 database connectivity. You must provide both a client
108 --auth-db Work on the authentication database instead of a
110 --dbname=name Database connection options for the UTF-8
111 --dbhost=host handling test.
116 Options for --create:
117 --type \'sql\' or \'pl\'. Defaults to sql.
118 --description The description field of the generated upgrade.
119 --depends Tags of upgrades which this upgrade depends upon.
120 Defaults to the latest stable release upgrade.
121 Multiple values possible.
134 sub calc_rev_depends {
135 map { $_->{rev_depends} = []; } values %{ $controls };
137 foreach my $control (values %{ $controls }) {
138 map { push @{ $controls->{$_}->{rev_depends} }, $control->{tag} } @{ $control->{depends} };
143 my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
145 print "LIST VIEW\n\n" .
146 "number tag depth priority\n";
149 foreach (@sorted_controls) {
150 print "$i $_->{tag} $_->{depth} $_->{priority}\n";
158 my ($tag, $depth) = @_;
160 print " " x $depth . $tag . "\n";
162 foreach my $dep_tag (@{ $controls->{$tag}->{depends} }) {
163 dump_node($dep_tag, $depth + 1);
168 print "TREE VIEW\n\n";
172 my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
174 foreach my $control (@sorted_controls) {
175 dump_node($control->{tag}, "") unless (@{ $control->{rev_depends} });
181 sub dump_node_reverse {
182 my ($tag, $depth) = @_;
184 print " " x $depth . $tag . "\n";
186 foreach my $dep_tag (@{ $controls->{$tag}->{rev_depends} }) {
187 dump_node_reverse($dep_tag, $depth + 1);
191 sub dump_tree_reverse {
192 print "REVERSE TREE VIEW\n\n";
196 my @sorted_controls = $dbupgrader->sort_dbupdate_controls;
198 foreach my $control (@sorted_controls) {
199 last if ($control->{depth} > 1);
200 dump_node_reverse($control->{tag}, "");
209 my $format = $params{format} || "png";
210 my $file_name = $params{file_name} || "db_dependencies.${format}";
212 print "GRAPHVIZ OUTPUT -- format: ${format}\n\n";
213 print "Output will be written to '${file_name}'\n";
217 my $dot = "|dot -T${format} ";
218 open OUT, "${dot}> \"${file_name}\"" || die;
221 "digraph db_dependencies {\n" .
222 "graph [size=\"16.53,11.69!\"];\n" .
223 "node [shape=box style=filled fillcolor=white];\n";
226 foreach my $c (values %{ $controls }) {
227 $ranks{$c->{depth}} ||= [];
229 my ($pre, $post) = @{ $c->{rev_depends} } ? ('')x2 :
230 (map "node [fillcolor=$_] ", qw(lightgray white));
232 push @{ $ranks{$c->{"depth"}} }, qq|${pre}"$c->{tag}"; ${post}|;
235 foreach (sort keys %ranks) {
236 print OUT "{ rank = same; ", join("", @{ $ranks{$_} }), " }\n";
239 foreach my $c (values %{ $controls }) {
240 print OUT qq|"$c->{tag}";\n|;
242 foreach my $d (@{ $c->{depends} }) {
243 print OUT qq|"$c->{tag}" -> "$d";\n|;
254 print "SCRIPTS NO OTHER SCRIPTS DEPEND ON\n\n" .
255 join("\n", map { $_->{tag} } grep { !scalar @{ $_->{rev_depends} } } values %{ $controls }) .
262 my $filename = $params{filename};
263 my $dbupgrader = $params{dbupgrader};
264 my $type = $params{type} || 'sql';
265 my $description = $params{description} || '';
266 my @depends = @{ $params{depends} };
268 my $encoding = 'utf-8';
271 my @releases = grep { /^release_/ } keys %$controls;
272 @depends = ((sort @releases)[-1]);
276 if ($type eq 'sql') {
278 } elsif ($type eq 'pl') {
281 die 'Error: No --type was given but is required for --create.';
283 die 'Error: Unknown --type. Try "sql" or "pl".';
286 my $full_filename = $dbupgrader->path . '/' . $filename . '.' . $type;
288 die "file '$full_filename' already exists, aborting" if -f $full_filename;
291 open my $fh, ">:encoding($encoding)", $full_filename or die "can't open $full_filename";
292 print $fh "$comment \@tag: $filename\n";
293 print $fh "$comment \@description: $description\n";
294 print $fh "$comment \@depends: @depends\n";
297 print $fh "package SL::DBUpgrade2::$filename;\n";
299 print $fh "use strict;\n";
300 print $fh "use utf8;\n" if $encoding =~ /utf.?8/i;
302 print $fh "use parent qw(SL::DBUpgrade2::Base);\n";
304 print $fh "sub run {\n";
305 print $fh " my (\$self) = \@_;\n";
314 print "File $full_filename created.\n";
316 system("\$EDITOR $full_filename");
323 my (@order, %tags, @all_tags);
325 if ($name eq "ALL") {
327 @all_tags = map { $_->{tag} } grep { !@{$_->{rev_depends}} } values %{ $controls };
330 $form->error("Unknown dbupgrade tag '$name'") if (!$controls->{$name});
334 foreach my $tag (@all_tags) {
335 build_upgrade_order($tag, \@order, \%tags);
338 my @upgradescripts = map { $controls->{$_}->{applied} = 0; $controls->{$_} } @order;
340 my $dbh = $opt_auth_db ? connect_auth()->dbconnect : SL::DB->client->dbh;
342 $dbh->{PrintWarn} = 0;
343 $dbh->{PrintError} = 0;
345 $user->create_schema_info_table($form, $dbh);
347 my $query = qq|SELECT tag FROM schema_info|;
348 my $sth = $dbh->prepare($query);
349 $sth->execute() || $form->dberror($query);
350 while (my ($tag) = $sth->fetchrow_array()) {
351 $controls->{$tag}->{applied} = 1 if defined $controls->{$tag};
355 @upgradescripts = sort { $a->{priority} <=> $b->{priority} } grep { !$_->{applied} } @upgradescripts;
356 if (!@upgradescripts) {
357 print "The upgrade has already been applied.\n";
361 foreach my $control (@upgradescripts) {
362 $control->{file} =~ /\.(sql|pl)$/;
366 print "Applying upgrade $control->{file}\n";
367 $dbupgrader->process_file($dbh, "sql/Pg-upgrade2/$control->{file}", $control);
370 $dbh->disconnect unless $opt_auth_db;
373 sub dump_sql_result {
374 my ($results, $column_order) = @_;
376 my %column_lengths = map { $_, length $_ } keys %{ $results->[0] };
378 foreach my $row (@{ $results }) {
379 map { $column_lengths{$_} = length $row->{$_} if (length $row->{$_} > $column_lengths{$_}) } keys %{ $row };
383 if ($column_order && scalar @{ $column_order }) {
384 @sorted_names = @{ $column_order };
386 @sorted_names = sort keys %column_lengths;
389 my $format = join('|', map { '%-' . $column_lengths{$_} . 's' } @sorted_names) . "\n";
391 printf $format, @sorted_names;
392 print join('+', map { '-' x $column_lengths{$_} } @sorted_names) . "\n";
394 foreach my $row (@{ $results }) {
395 printf $format, map { $row->{$_} } @sorted_names;
397 printf "(\%d row\%s)\n", scalar @{ $results }, scalar @{ $results } > 1 ? 's' : '';
403 my $dbh = $opt_auth_db ? connect_auth()->dbconnect : SL::DB->client->dbh;
404 $dbh->{AutoCommit} = 0;
406 $dbh->{PrintWarn} = 0;
407 $dbh->{PrintError} = 0;
409 $user->create_schema_info_table($form, $dbh);
411 my $query = qq|SELECT tag, login, itime FROM schema_info ORDER BY itime|;
412 my $sth = $dbh->prepare($query);
413 $sth->execute() || $form->dberror($query);
414 while (my $ref = $sth->fetchrow_hashref()) {
419 $dbh->disconnect unless $opt_auth_db;
421 if (!scalar @results) {
422 print "No database upgrades have been applied yet.\n";
424 dump_sql_result(\@results, [qw(tag login itime)]);
431 my $dbh = $opt_auth_db ? connect_auth()->dbconnect : SL::DB->client->dbh;
433 $dbh->{PrintWarn} = 0;
434 $dbh->{PrintError} = 0;
436 my @unapplied = $dbupgrader->unapplied_upgrade_scripts($dbh);
438 $dbh->disconnect unless $opt_auth_db;
440 if (!scalar @unapplied) {
441 print "All database upgrades have been applied.\n";
443 print map { $_->{tag} . "\n" } @unapplied;
447 sub build_upgrade_order {
452 my $control = $controls->{$name};
454 foreach my $dependency (@{ $control->{depends} }) {
455 next if $tags->{$dependency};
456 $tags->{$dependency} = 1;
457 build_upgrade_order($dependency, $order, $tags);
460 push @{ $order }, $name;
468 $locale = Locale->new;
470 $::request = SL::Request->new(
472 layout => SL::Layout::None->new,
479 GetOptions("list" => \$opt_list,
480 "tree" => \$opt_tree,
481 "rtree" => \$opt_rtree,
482 "nodeps" => \$opt_nodeps,
483 "graphviz:s" => \$opt_graphviz,
484 "format:s" => \$opt_format,
485 "user=s" => \$opt_user,
486 "client=s" => \$opt_client,
487 "apply=s" => \$opt_apply,
488 "applied" => \$opt_applied,
489 "create=s" => \$opt_create,
490 "type=s" => \$opt_type,
491 "description=s" => \$opt_description,
492 "depends=s" => \@opt_depends,
493 "unapplied" => \$opt_unapplied,
494 "test-utf8" => \$opt_test_utf8,
495 "dbhost:s" => \$opt_dbhost,
496 "dbport:s" => \$opt_dbport,
497 "dbname:s" => \$opt_dbname,
498 "dbuser:s" => \$opt_dbuser,
499 "dbpassword:s" => \$opt_dbpassword,
500 "auth-db" => \$opt_auth_db,
501 "help" => \$opt_help,
504 show_help() if ($opt_help);
506 $dbupgrader = SL::DBUpgrade2->new(form => $form, auth => $opt_auth_db);
507 $controls = $dbupgrader->parse_dbupdate_controls->{all_controls};
509 dump_list() if ($opt_list);
510 dump_tree() if ($opt_tree);
511 dump_tree_reverse() if ($opt_rtree);
512 dump_graphviz('file_name' => $opt_graphviz,
513 'format' => $opt_format) if (defined $opt_graphviz);
514 dump_nodeps() if ($opt_nodeps);
515 create_upgrade(filename => $opt_create,
516 dbupgrader => $dbupgrader,
518 description => $opt_description,
519 depends => \@opt_depends) if ($opt_create);
521 if ($opt_client && !connect_auth()->set_client($opt_client)) {
522 $form->error($form->format_string("The client '#1' does not exist.", $opt_client));
526 $form->error("Need a client, too.") if !$auth || !$auth->client;
528 %myconfig = connect_auth()->read_user(login => $opt_user);
530 if (!$myconfig{login}) {
531 $form->error($form->format_string("The user '#1' does not exist.", $opt_user));
534 $locale = new Locale($myconfig{countrycode}, "all");
535 $user = new User(login => $opt_user);
537 map { $form->{$_} = $myconfig{$_} } keys %myconfig;
541 $form->error("--apply used but no user name given with --user.") if !$user && !$opt_auth_db;
542 apply_upgrade($opt_apply);
546 $form->error("--applied used but no user name given with --user.") if !$user && !$opt_auth_db;
550 if ($opt_unapplied) {
551 $form->error("--unapplied used but no user name given with --user.") if !$user && !$opt_auth_db;
556 if ($opt_test_utf8) {
557 $form->error("--test-utf8 used but no database name given with --dbname.") if (!$opt_dbname);
559 my $umlaut_upper = 'Ä';
561 my $dbconnect = "dbi:Pg:dbname=${opt_dbname}";
562 $dbconnect .= ";host=${opt_dbhost}" if ($opt_dbhost);
563 $dbconnect .= ";port=${opt_dbport}" if ($opt_dbport);
565 my $dbh = DBI->connect($dbconnect, $opt_dbuser, $opt_dbpassword, { pg_enable_utf8 => 1 });
567 $form->error("UTF-8 test: Database connect failed (" . $DBI::errstr . ")") if (!$dbh);
569 my ($umlaut_lower) = $dbh->selectrow_array(qq|SELECT lower(?)|, undef, $umlaut_upper);
573 if ($umlaut_lower eq 'ä') {
574 print "UTF-8 test was successful.\n";
575 } elsif ($umlaut_lower eq 'Ä') {
576 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";
578 print "UTF-8 test was NOT successful: Umlauts are destroyed. Do not use UTF-8 on this cluster.\n";