alexbio has asked for the wisdom of the Perl Monks concerning the following question:

Hi everybody. I'm using Class::DBI inside a project to access an SQLite database. It works very well, but I'm facing a problem: the path to the database file (the db name) have to be harcoded inside the package.

I have the following packages

The DBI classes

package MyModule::DBI; use base Class::DBI; use warnings; use strict; our $VERSION = '0.01'; my $dsn = "dbi:SQLite:dbname=/path/to/db"; __PACKAGE__ -> set_db('Main', $dsn); 1;

And

package MyModule::Data; use base MyModule::DBI; use warnings; use strict; our $VERSION = '0.01'; __PACKAGE__ -> table('data'); __PACKAGE__ -> columns(All => qw(column1 column2 column3)); 1;

And the main module

package MyModule; use MyModule::Data; use warnings; use strict; our $VERSION = '0.01'; sub new { my ($class, %args) = @_; my $self = bless({%args}, $class); return $self; } 1;

It could be obvious but my question is, is it possible to call the new method and pass the path to the database and use it in MyModule::DBI? If yes, how?

What I want to do is something like

use MyModule; my $obj = MyModule -> new(db_path => '/path/to/file');

Thank you

Alex's Log - http://alexlog.co.cc

Replies are listed 'Best First'.
Re: Class::DBI and database name
by NetWallah (Canon) on Jun 27, 2010 at 22:57 UTC
    Yes - I had excactly the same issue. Here is how I resolved it:

    In the DB module:

    #!/usr/bin/perl -w use strict; use warnings; use Class::DBI; package AvalancheDB; our $DBPath="avalanchedata.sqlite"; # Default file nme our $DBH; sub import{ my ($class,$newpath)=@_; $DBPath = $newpath || $DBPath; #print "IMPORT: Setting path to '$DBPath' \n\t \n"; ## Delay this setting till AFTER IMPORT !! AvalancheDB::DBI->connection(qq|dbi:SQLite:dbname=$DBPath|, "", "") or die "Cannot connect to Database at $DBPath;"; } ...
    In the MAIN code...
    ... my $ProgramDir; BEGIN{ ($ProgramDir) = ( $0=~m|(.+)\/.+$|, $0=~m|(.+)\\.+$| ,"."); } use lib ( $ProgramDir, ); # Current Program's Dir use AvalancheDB ("$ProgramDir/avalanchedata.sqlite"); ...
    Basically, I'm (ab)using the "import" function to get the DB path.

         Syntactic sugar causes cancer of the semicolon.        --Alan Perlis

      Thank you very much for the help, but that's not precisely what I wanted.

      Anyway, I resolved by using your code and setting the db path with File::Temp so that user is no longer asked to set it manually.

      Alex's Log - http://alexlog.co.cc