# file KLEIDER/catalog/src/dbdump/MysqlAccess.pm # Zugang zu einer Mysql-Datenbank über secrets-Datei # 2020-12-06 Herbert Schiemann # GPL Version 2 oder neuer package Herbaer::MysqlAccess ; BEGIN { use Cwd qw(realpath); use DBI; use Exporter; our $VERSION = 20201206; our @ISA = qw (Exporter); our @EXPORT = qw (get_database); our @EXPORT_OK = qw (get_database); } sub get_database { my ($dbkey, $secrets, $verbose) = @_; $verbose //= 1; if (!$secrets) { $secrets = realpath($INC{"Herbaer/MysqlAccess.pm"}); $secrets =~ s/\/catalog\/.*$//; $secrets = "$secrets/web/secrets"; } my $hnd; if (! open ($hnd, "<:encoding(utf-8)", $secrets)) { print STDERR "Kann Datei \"$secrets\" nicht lesen:$!\n" if $verbose; return undef; } my $line; my $dbname; my $dbn; my $user; my $password; while (defined ($line = <$hnd>)) { $line =~ s/\s*$//; if ( $line =~ /^\s*dbkey.mysql.([a-z0-9]+)\s*=\s*(.+)/ ) { if ($1 eq $dbkey) { $dbname = $2; } } elsif ($line =~ /^\s*mysql\.([a-z0-9]+)\.([a-z]+)\s*=\s*(.+)/) { if ($dbname && $1 eq $dbname) { if ($2 eq "name") { $dbn = $3; } if ($2 eq "user") { $user = $3; } elsif ($2 eq "password") { $password = $3; } } } } close $hnd; $dbn ||= $dbname; if (!$dbn) { print STDERR "Datenbank nicht gefunden: dbkey $dbkey\n" if $verbose; return undef; } if (!$user) { print STDERR "Datenbank-User nicht gefunden: dbname $dbname\n" if $verbose; return undef; } if (!$password) { print STDERR "Datenbank-Kennwort nicht gefunden: dbname $dbname\n" if $verbose; return undef; } my $dbh = DBI -> connect ("DBI:mysql:$dbn", $user, $password); if (!$dbh) { print STDERR "Keine Verbindung zur MySQL-Datenbank $dbn\n" if $verbose; return undef; } [$dbh, $dbn]; } # get_database 1; # end of file KLEIDER/catalog/src/dbdump/MysqlAccess.pm