A few comments on portability (as you did not specify which DB engine you were using)
1. Dropping a database
The SQL92 standard does not specify a DROP DATABASE statement AFAIK (can somebody please
confirm/infirm this as I don't have access to standard documents, also comments on newer standards would be welcome). This is no big deal anyway, because most DBs stick to their fancy syntax,
mainly for backward compatibility reason, and because vendors think that sticking with it will give them
competitive edge/distinct personality/whatever. The two mature/widespread free software engines
(PostgreSQL and MySQL) implement it though.
Also the standard DBI module does not implement abstraction for dropping a database ;
there are AFAIK "higher level" modules on CPAN that do it but I'm not familiar with them, if you're interested do a search. Your best friend is the standard documentation for your DB, anyway.
2. Listing databases
This is even more non-standard, but fortunately DBI has abstraction for it from version 1.38 (if your DB engine concept of a "data base" matches DBI's concept of a "data source", which is usually the case with backend DBs). The method is called data_sources.
To give you an idea of this biodiversity, this is how I would solve your problem for PostgreSQL with only native SQL (PostgreSQL doesn't implement DROP DATABASE ... IF EXISTS) :
use DBI;
my $dbh=DBI->connect('dbi:Pg:dbname=template1', 'user' , 'password', {
+ RaiseError => 1, AutoCommit => 1 } );
# [...]
sub pg_drop_if_exists {
my $dbname = shift;
my $sth = $dbh->prepare(q{SELECT datname FROM pg_catalog.pg_database
+ WHERE datname = ?});
$sth->execute($dbname);
if ($sth->fetchrow_arrayref()) {
$dbh->do('DROP DATABASE ' . $dbname); #placeholder and quote don't
+ work, security!
}
}
pg_drop_if_exists('nikos_db');
|