mebil
[kivitendo-erp.git] / scripts / dbconnect.pl
1 #!/usr/bin/perl
2
3 BEGIN {
4   use SL::System::Process;
5   my $exe_dir = SL::System::Process::exe_dir;
6
7   unshift @INC, "${exe_dir}/modules/override"; # Use our own versions of various modules (e.g. YAML).
8   push    @INC, "${exe_dir}/modules/fallback"; # Only use our own versions of modules if there's no system version.
9   unshift @INC, $exe_dir;
10 }
11
12 use strict;
13 use warnings;
14
15 use Data::Dumper;
16 use DBI;
17 use List::MoreUtils qw(any);
18 use SL::LxOfficeConf;
19
20 our %lx_office_conf;
21 SL::LxOfficeConf->read;
22
23 sub psql {
24   my ($title, %params) = @_;
25   print "Connecting to ${title} database '" . $params{db} . "' on " . $params{host} . ':' . $params{port} . " with PostgreSQL username " . $params{user} . "\n\n";
26   print "If asked for the password use this: " . $params{password} . "\n\n";
27   exec "psql", "-U", $params{user}, "-h", $params{host}, "-p", $params{port}, $params{db};
28 }
29
30 my $settings = $lx_office_conf{'authentication/database'};
31 die "Missing configuration section 'authentication/database'" unless $settings;
32 die "Incomplete database settings" if any { !$settings->{$_} } qw (host db user);
33 $settings->{port} ||= 5432;
34
35 psql("authentication", %{ $settings }) if !@ARGV;
36
37 my $dbh = DBI->connect('dbi:Pg:dbname=' . $settings->{db} . ';host=' . $settings->{host} . ($settings->{port} ? ';port=' . $settings->{port} : ''), $settings->{user}, $settings->{password})
38   or die "Database connection to authentication database failed: " . $DBI::errstr;
39
40 my $user_id = $dbh->selectrow_array(qq|SELECT id FROM auth.user WHERE login = ?|, undef, $ARGV[0])
41   or do {
42     $dbh->disconnect;
43     die "No such user in authentication database: " . $ARGV[0];
44   };
45
46 my $href = $dbh->selectall_hashref(qq|SELECT cfg_key, cfg_value FROM auth.user_config WHERE user_id = ?|, 'cfg_key', undef, $user_id);
47 $dbh->disconnect;
48
49 my %params = (
50   host     => $href->{dbhost}->{cfg_value},
51   db       => $href->{dbname}->{cfg_value},
52   port     => $href->{dbport}->{cfg_value} || 5432,
53   user     => $href->{dbuser}->{cfg_value},
54   password => $href->{dbpasswd}->{cfg_value},
55 );
56
57 die "Incomplete database settings for user " . $ARGV[0] if any { !$settings->{$_} } qw (host db user);
58
59 psql($ARGV[0] . "'s", %params);