I don't remember the circumstances that brought this module on. Probably drugs of some sort. In any case, I thought of this minimal DBI that uses nothing more than a tied scalar to play with databases. I've only really tested it with SELECT statements, but it works pretty well. Since I have a tendency to create somewhat crazy modules (like Parse::Tinymush), I thought this one would get my usual response ("Stop the madness!", "Peope are starving and you wrote THIS?"). Instead, people thought it was "perly and useful" and "/cool/". So, does this module demonstrate insanity or genius?
It works like this:package Tie::DBI; use 5.008003; use strict; use warnings; use base 'Tie::Scalar'; use DBI; our $VERSION = '0.01'; sub TIESCALAR { my $class = shift; my ($dsn, $user, $pass) = @_; my $self = { dbh => undef, }; $self->{dbh} = DBI->connect($dsn, $user, $pass); bless $self, $class; } sub STORE { my ($self, $value) = @_; if ( $self->{sth} && ref($value) eq 'ARRAY' ) { $self->{sth}->execute(@$value); } else { $self->{sth} = $self->{dbh}->prepare($value); if ( $self->{sth}->FETCH('NUM_OF_PARAMS') == 0 ) { $self->{sth}->execute(); } } } sub FETCH { my ($self) = @_; return undef if !$self->{sth} || $self->{dbh}->err; return $self->{sth}->fetchrow_arrayref() || 0; } 1;
my $dbh; tie $dbh, 'Tie::DBI', $dsn, $user, $pass; $dbh = "select * from table where field = $value"; while ( my $row = $dbh ) { print $row->[0], "\n"; }
Assigning to the tied variable causes the value to be prepared and executed. Reading from the variable causes fetchrow_arrayref() to be called and one row is returned. 'undef' is returned if there is no statement handle or there is an error. 0 is returned if there are no more rows.
Placeholders can be used as well:
Any comments or questions?$dbh = "select * from table where field = ?"; $dbh = [$value]; while ( my $row = $dbh ) { print $row->[0], "\n"; }
Note 1: I realize that Tie::DBI already exists on CPAN. I just couldn't think of a good name, except for Tie::DBI::Minimalist, which is kinda dumb. Any good suggestions?
Note 2: I think an even better minimal interface can be done using a tied filehandle. I'm working on that.
Note 3: On a side note, is this a meditation or a craft?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Genius or Insanity: My minimal DBI
by perrin (Chancellor) on Jan 13, 2004 at 04:23 UTC | |
by Kageneko (Scribe) on Jan 13, 2004 at 04:42 UTC | |
|
Re: Genius or Insanity: My minimal DBI
by theorbtwo (Prior) on Jan 13, 2004 at 05:21 UTC | |
|
Re: Genius or Insanity: My minimal DBI
by dws (Chancellor) on Jan 13, 2004 at 05:37 UTC | |
|
Re: Genius or Insanity: My minimal DBI
by gmpassos (Priest) on Jan 14, 2004 at 01:52 UTC |