epic-s6ts
[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 }
9
10 use strict;
11 use warnings;
12
13 use Data::Dumper;
14 use DBI;
15 use List::MoreUtils qw(any);
16 use SL::LxOfficeConf;
17
18 our %lx_office_conf;
19 SL::LxOfficeConf->read;
20
21 sub psql {
22   my ($title, %params) = @_;
23   print "Connecting to ${title} database '" . $params{db} . "' on " . $params{host} . ':' . $params{port} . " with PostgreSQL username " . $params{user} . "\n\n";
24   print "If asked for the password use this: " . $params{password} . "\n\n";
25   exec "psql", "-U", $params{user}, "-h", $params{host}, "-p", $params{port}, $params{db};
26 }
27
28 my $settings = $lx_office_conf{'authentication/database'};
29 die "Missing configuration section 'authentication/database'" unless $settings;
30 die "Incomplete database settings" if any { !$settings->{$_} } qw (host db user);
31 $settings->{port} ||= 5432;
32
33 psql("authentication", %{ $settings }) if !@ARGV;
34
35 my $dbh = DBI->connect('dbi:Pg:dbname=' . $settings->{db} . ';host=' . $settings->{host} . ($settings->{port} ? ';port=' . $settings->{port} : ''), $settings->{user}, $settings->{password})
36   or die "Database connection to authentication database failed: " . $DBI::errstr;
37
38 my $user_id = $dbh->selectrow_array(qq|SELECT id FROM auth.user WHERE login = ?|, undef, $ARGV[0])
39   or do {
40     $dbh->disconnect;
41     die "No such user in authentication database: " . $ARGV[0];
42   };
43
44 my $href = $dbh->selectall_hashref(qq|SELECT cfg_key, cfg_value FROM auth.user_config WHERE user_id = ?|, 'cfg_key', undef, $user_id);
45 $dbh->disconnect;
46
47 my %params = (
48   host     => $href->{dbhost}->{cfg_value},
49   db       => $href->{dbname}->{cfg_value},
50   port     => $href->{dbport}->{cfg_value} || 5432,
51   user     => $href->{dbuser}->{cfg_value},
52   password => $href->{dbpasswd}->{cfg_value},
53 );
54
55 die "Incomplete database settings for user " . $ARGV[0] if any { !$settings->{$_} } qw (host db user);
56
57 psql($ARGV[0] . "'s", %params);