http://qs321.pair.com?node_id=324375


in reply to 'automating' SQL queries, use Class::DBI?

Class::DBI takes care of all the basics for you while at the same time helping to keep all your sql stuff in dedicated modules. Once you have your module set up for a table inserts & updates are easy as pie and custom queries aren't much harder.

package My::Table; use base 'My::Class::DBI'; __PACKAGE__->table('blah'); __PACKAGE__->columns( All => qw/ foo bar baz quid quux / ); __PACKAGE__->columns( Essential => qw/ foo bar / ); __PACKAGE__->columns( Primary => 'foo' ); # assuming we have another table called 'other'.. # this creates a method called sql_method_name __PACKAGE__->set_sql( method_name => qq( select b.foo, b.bar, o.summat +, o.summat_else from blah b left join other o using(foo) where b.quid +=?)); sub public_method_name { my ($class,$quid) = @_; my $sth = $class->sql_method_name(); $sth->execute($quid); return @{$sth->fetchall_arrayref({})}; }

and using the module...

# fetch a My::Table object my $record = My::Table->create({ foo => 1, bar => 'bar val', baz => 'baz val', quid => 'quid val', quux => 'quux val' }); # update a value $record->quid('new quid val'); $record->update; # fetch a list of records via our join method my @list = My::Table->public_method_name('new quid val');

I've also recently started using TEMP columns to store values from other tables in the retrieved object via custom join methods so I can still use the oo interface to read the values (can't update in this case) but it's beer o'clock and I don't have an example of that handy.. 8)

cheers,

J

Replies are listed 'Best First'.
Re: Re: 'automating' SQL queries, use Class::DBI?
by geektron (Curate) on Jan 28, 2004 at 02:21 UTC
    Class::DBI takes care of all the basics for you while at the same time helping to keep all your sql stuff in dedicated modules. Once you have your module set up for a table inserts & updates are easy as pie and custom queries aren't much harder.

    i already do what i can to pull all of my SQL out of main 'functional' modules and put them into SQL.pm-type classes/packages ( i think the current one is named ArticleQureies.pm and all it does is fetch/store and return results ).

    i'll have to spend some time playing with it, but it doesn't seem like much of a win to write the query, install it as a method, and then call the method. ( well, OK, it does, but it doesn't require the 'overhead' of importing another module. )