Subject: | [REQ] DBD::SQLite mkpath connect param |
Hi Matt,
I've been making a lot of duplicate code to make dirs for SQLite DB's.. I'm using DBIx::AnyDBD, so I tried sneaking the code into the SQLite subclass, but DBIx::AnyDBD calls DBI->connect before it does much else, so it's a bit difficult to auto-create the dir here.
I've had a think about it, and was wondering if you'd consider adding a param to connect to allow auto-creation of the dir, ala:
dbi:sqlite:dbname=t/tmp/sqlite/foo.db;mkpath=1
The patch I've attached implements this...
hth,
-Steve
Binary files DBD-SQLite-0.31/foo and DBD-SQLite-0.31-mkpath/foo differ
diff -ruN DBD-SQLite-0.31/lib/DBD/SQLite.pm DBD-SQLite-0.31-mkpath/lib/DBD/SQLite.pm
--- DBD-SQLite-0.31/lib/DBD/SQLite.pm Wed Jun 16 19:36:57 2004
+++ DBD-SQLite-0.31-mkpath/lib/DBD/SQLite.pm Wed Jun 16 20:03:58 2004
@@ -33,6 +33,29 @@
undef $drh;
}
+sub create_dir_for_dsn {
+ my $class = shift;
+ my $path = $class->get_path_from_dsn( shift );
+
+ require File::Basename;
+ my $dir = File::Basename::dirname( $path );
+
+ unless (-d $dir) {
+ require File::Path;
+ File::Path::mkpath( $dir );
+ }
+
+ return $class;
+}
+
+sub get_path_from_dsn {
+ my $class = shift;
+ my $dsn = shift;
+ my ($path) = ($dsn =~ /dbname=(.+?)(?:;|\z)/i);
+ return $path;
+}
+
+
package DBD::SQLite::dr;
sub connect {
@@ -43,17 +66,24 @@
});
my $real_dbname = $dbname;
+ my $mkpath = 0;
if ($dbname =~ /=/) {
foreach my $attrib (split(/;/, $dbname)) {
my ($k, $v) = split(/=/, $attrib, 2);
if ($k eq 'dbname') {
$real_dbname = $v;
}
+ elsif ($k eq 'mkpath') {
+ $mkpath = $v;
+ }
else {
# TODO: add to attribs
}
}
}
+
+ DBD::SQLite->create_dir_for_dsn( $dbname ) if $mkpath;
+
DBD::SQLite::db::_login($dbh, $real_dbname, $user, $auth)
or return undef;
@@ -275,6 +305,9 @@
use DBI;
my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile","","");
+
+ # if you want to create dirs required for dbfile:
+ my $dbh = DBI->connect("dbi:SQLite:dbname=dbfile;mkpath=1","","");
=head1 DESCRIPTION
Binary files DBD-SQLite-0.31/output/foo and DBD-SQLite-0.31-mkpath/output/foo differ
diff -ruN DBD-SQLite-0.31/t/01logon_mkpath.t DBD-SQLite-0.31-mkpath/t/01logon_mkpath.t
--- DBD-SQLite-0.31/t/01logon_mkpath.t Thu Jan 1 01:00:00 1970
+++ DBD-SQLite-0.31-mkpath/t/01logon_mkpath.t Wed Jun 16 19:55:27 2004
@@ -0,0 +1,19 @@
+use DBI;
+use Test;
+use File::Spec::Functions;
+
+BEGIN { plan tests => 3 }
+
+my $dir = catdir(qw( output mydir ));
+my $file = catfile( $dir, 'foo' );
+my $dbh = DBI->connect("dbi:SQLite:dbname=$file;mkpath=1", "", "");
+
+ok( $dbh );
+ok( -d $dir );
+ok( -e $file );
+
+unlink( $file );
+rmdir( $dir );
+
+$dbh->disconnect if $dbh;
+