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