Marc --

Looks cool.  We have been talking about consolidating all the repetitive table operations in similar ways.  I have an experimental implementation as "C4::Table" that also tries to provide baseline SELECT, UPDATE and eventually DELETE.  I think I'll have a chance to look at it more on Friday, after which maybe I can send some patches for review and further experimentation?  It is a little more of an OO approach, and I'll be interested to see what you think of it.

--Joe Atzberger

On Wed, Oct 15, 2008 at 9:28 AM, Marc Chantreux <marc.chantreux@biblibre.com> wrote:
hello guys,

I just rewritten the C4::Bookseller::AddBookseller and it now looks
like:

sub AddBookseller {
   _koha_insert_and_get_id(
       'aqbooksellers', shift
   );
}


_koha_insert_and_get_id is a function where i deal with DBI and all specific
DBD tricks with reuse in mind. You can see the following code.

do i try to push it in koha ? and where ? It sounds like Koha::SQL package.

regards

sub _koha_insert_and_get_id {

   # Todo: implement uses of config
   # like exclude, defaults, ...

   # $tablename is a string and contains the name of the table
   # $data is a reference to an hash that contains column names to set as keys
   # optionnal $config alter default behaviour

   my ( $tablename, $data, $config ) = @_;
   my $dbh = C4::Context->dbh;

   # @fields to insert are all %$data (unless overwritten by $$config{fields} )
   my @fields =
       (defined $config and exists $config->{fields})
       ? @{ $config->{fields} }
       : keys %$data
   ;

   # build the query
   my $query = 'INSERT INTO '
       . $tablename
       .' ('
       . join(',',@fields)
       . ') VALUES ('
       . join(',', map {'?'} @fields)
       . ');'
   ;

   my $sth = $dbh->prepare($query);

   # deal with the server

   $sth->execute( @$data{@fields});
   if ( $sth->err ) {
       warn $sth->errstr;
       return undef;
   }

   # return the last id
   C4::Context->config('db_scheme') eq 'mysql'
       and return $dbh->{mysql_insertid};

   # todo use the last_insert_id dbh function
   # my $id = $dbh->last_insert_id( ? );
   # before give up

   warn 'database unable to get last inserted id';
   return undef;

}

--
Marc Chantreux
http://www.biblibre.com
Expert en Logiciels Libres pour l'info-doc