in reply to Auto-Increment and DBD Agnosticism
I applaud your goal of DBD-agnosticism. But it's really hard to be DBD-agnostic without also being DBD-specific. Look at all the big cross-platform DB modules out there (Class::DBI for instance). What they do is have all DBD-specific features subclassed out. That's the "right" way to do it. In my own database module, I had to resort to something similar for getting the last-insert-id, as well as schema detection. It goes something like this:
Then you have a few small DBD-specific modules implementing insert_id:package Foo; sub new { my $class = shift; my $dbh = ... my $subclass = "$class::$dbh->{Driver}{Name}"; eval "use $subclass; 1;" or croak "$dbh->{Driver}{Name} is unsupported"; bless { dbh => $dbh }, $subclass; } sub dbh { $_[0]->{dbh}; }
(In my own module, I don't actually bless the objects into the subclass, but I do store the name of the DBD subclass and call insert_id as a class method when I need it) Subclassing is clean and easy to maintain, plus it encourages me to stretch support to as many DBDs as possible.package Foo::mysql; sub insert_id { my $self = shift; $self->dbh->{mysql_insertid}; } ########### package Foo::Pg; ## notice how Pg requires the table and column, while the ## other DBDs ignore these args sub insert_id { my ($self, $table, $col) = @_; my $id; eval { my $seq = $table . '_' . $col . '_seq'; my $sth = $self->dbh->prepare( "select currval('$seq')" ); $sth->execute; ($id) = $sth->fetchrow_array; $sth->finish; 1; } or die; return $id; } ########## package Foo::SQLite; sub insert_id { my $self = shift; $self->dbh->func('last_insert_rowid'); }
blokhead
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Auto-Increment and DBD Agnosticism
by skyknight (Hermit) on Jun 22, 2004 at 19:39 UTC |