[Koha-devel] adding a model abstraction ?

Marc Chantreux marc.chantreux at biblibre.com
Wed Oct 15 15:28:12 CEST 2008


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(',', at 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



More information about the Koha-devel mailing list