Class::DBI::Plugin::MultiDatabases - use multiple databases from a snigle class
package Your::App::DBI; use base qw(Class::DBI); use Class::DBI::Plugin::MultiDatabases; Your::App::DBI->set_connections({ databaseA => ["dbi:SQLite:dbname=databaseA", '', ''], databaseB => ["dbi:SQLite:dbname=databaseB", '', ''], }); package Your::App::CD; Your::App::CD->table('cds'); Your::App::CD->column(All => qw/cdid title artist/); package main_script; my $cd; Your::App::DBI->change_db('databaseA'); $cd = Your::App::CD->retrieve(123); print $cd->title, "\n"; # from databaseA # .... Your::App::DBI->change_db('databaseB'); $cd = Your::App::CD->retrieve(123); print $cd->title, "\n"; # from databaseB $cd->save_db_Main(); # this object saves 'databaseB' Your::App::DBI->change_db('databaseA'); my @cds = Your::App::CD->retrieve_all(); print $cd->title, "\n"; # from databaseB still for(@cds){ # objects are from databaseA }
"There are cases when you have the same schema in multiple databases and would like to access two or more databases from the same script without reconnecting every time."
from http://wiki.class-dbi.com/index.cgi?UsingMultipleDatabases
This module helps you for it automatically.
All that you must do is use Class::DBI::Plugin::MultiDatabases in your base CDBI application class.
use Class::DBI::Plugin::MultiDatabases
takes key/arrayref pair. $arrayref is a DSN, username, password and options.
set_connections( db1 => ["dbi:Pg:dbname=pgdb", $user, $pass, $opts], db2 => ["dbi:SQLite:dbname=sqlitedb", '', ''], )
You give a database key which you have set with set_connections.
set_connections
This method is object method. When change_db is called, all existing objects return new database handle from db_Main(). If you called save_db_Main before calling change_db, the object return unchanged dbh.
change_db
db_Main()
save_db_Main
This method is object method which erases save_db_Main's effect.
Maybe, there are a lot of bugs.
http://wiki.class-dbi.com/index.cgi?UsingMultipleDatabases
Class::DBI
Makamaka Hannyaharamitu, <makamaka[at]cpan.org>
Copyright 2005 by Makamaka Hannyaharamitu
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
To install Class::DBI::Plugin::MultiDatabases, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Class::DBI::Plugin::MultiDatabases
CPAN shell
perl -MCPAN -e shell install Class::DBI::Plugin::MultiDatabases
For more information on module installation, please visit the detailed CPAN module installation guide.