[CDBI] using different DSNs for reads/writes

Edward J. Sabol sabol at alderaan.gsfc.nasa.gov
Wed Dec 19 21:13:02 GMT 2007


Aaron Wolfe asked:
> Is there a way to create a dbi class that would be smart enough to do
> selects from the local db, but updates and inserts to the master?

I'm very doubtful.

> I read the "multiple databases" section in the wiki but in addition to
> being a bit over my head, I don't think they address splitting reads vs
> writes, just using multiple connections to identical dbs.

The "multiple databases" wiki node might be the best approach actually, but
here's a different approach I just thought up.... If you have a lot of CDBI
classes, then this probably isn't a good idea, but if you only have a few,
you might try something along this line....

First, create parallel CDBI classes for your master and slave databases:

YourApp::DBI::Master
YourApp::DBI::Master::Foo
YourApp::DBI::Master::Bar
YourApp::DBI::Master::Baz

YourApp::DBI::Slave
YourApp::DBI::Slave::Foo
YourApp::DBI::Slave::Bar
YourApp::DBI::Slave::Baz

You could probably even auto-generate the Slave classes from the Master
classes with a little scripting.

In YourApp::DBI::Slave (so that all Slave classes will inherit it), I'd add a
method called "retrieve_master", which would look something like this:

sub retrieve_master {
   my $self = shift;

   my $masterclass = ref($self);
   $masterclass =~ s/::Slave::/::Master::/;

   return $masterclass->retrieve($self->id);
}

(I'm not sure, but you might need to fiddle with that some to fully support
MCPKs.)

Then, just make sure you compartmentalize your code that creates any CDBI
objects to use the Master classes. When you need to modify an object, just

  my $masterobj = $obj->retrieve_master;

and modify $masterobj instead. Make sure you commit your changes. After doing
so, you'll need to "refresh" $obj, like so:

  $obj->remove_from_object_index();
  undef $obj;
  $obj = YourApp::Slave::DBI::Foo->retrieve($id);

All untested, of course.

Hope this helps,
Ed



More information about the ClassDBI mailing list