use warnings;
use FrBr::Common;
+use FrBr::Books::Util::Locks;
# Export-Deklarationen
my $storage = $c->stash->{'storage'};
my $save_func = sub {
- my ( $storage, $dbh, $autor_id, $titel, $vorname, $mittelname, $nachname, $suffix, $desc ) = @_;
+
+ my ( $storage, $dbh, $insert, $autor_id, $titel, $vorname, $mittelname, $nachname, $suffix, $desc ) = @_;
$desc = '' unless defined $desc;
- my $sql = <<ENDE;
+
+ my $sql = '';
+ my @P = ();
+
+ if ( $insert ) {
+ if ( $autor_id ) {
+ $sql = <<ENDE;
INSERT INTO `autoren` (
`id`, `titel`, `vorname`, `mittelname`, `nachname`, `name_suffix`, `autor_descr` )
VALUES (
- ?, ?, ?, ?, ?, ?, ? )
- ON DUPLICATE KEY UPDATE
- `id` = LAST_INSERT_ID(`id`),
- `titel` = ?,
- `vorname` = ?,
- `mittelname` = ?,
- `nachname` = ?,
- `name_suffix` = ?,
- `autor_descr` = ?
+ LAST_INSERT_ID(?), ?, ?, ?, ?, ?, ? )
ENDE
-
- my @P = ();
- push @P, $autor_id;
- push @P, $titel;
- push @P, $vorname;
- push @P, $mittelname;
- push @P, $nachname;
- push @P, $suffix;
- push @P, $desc;
- push @P, $titel;
- push @P, $vorname;
- push @P, $mittelname;
- push @P, $nachname;
- push @P, $suffix;
- push @P, $desc;
+ @P = ( $autor_id, $titel, $vorname, $mittelname, $nachname, $suffix, $desc );
+ }
+ else {
+ $sql = <<ENDE;
+INSERT INTO `autoren` (
+ `titel`, `vorname`, `mittelname`, `nachname`, `name_suffix`, `autor_descr` )
+ VALUES (
+ ?, ?, ?, ?, ?, ? )
+ENDE
+ @P = ( $titel, $vorname, $mittelname, $nachname, $suffix, $desc );
+ }
+ }
+ else {
+ $sql = <<ENDE;
+UPDATE `autoren`
+ SET `id` = LAST_INSERT_ID(`id`),
+ `titel` = ?,
+ `vorname` = ?,
+ `mittelname` = ?,
+ `nachname` = ?,
+ `name_suffix` = ?,
+ `autor_descr` = ?
+ WHERE `id` = ?
+ENDE
+ @P = ( $titel, $vorname, $mittelname, $nachname, $suffix, $desc, $autor_id );
+ }
if ( $storage->debug() ) {
my $text = $sql;
my $sth = $dbh->prepare($sql);
$sth->execute( @P );
+
};
my @Params = ();
+ my $search_params = {};
+
push @Params, $autor->{'id'};
my $tmp = $autor->{'titel'};
push @Params, $autor->{'desc'};
- $storage->dbh_do( $save_func, @Params );
+ lock_tables( $c, 'write' => [ 'autoren', 'autoren', 'as', 'me' ] );
+
+ my $id = undef;
+ my $do_insert = undef;
+ if ( $autor->{'id'} ) {
+ $search_params = { '`id`' => $autor->{'id'}, };
+ }
+ else {
+ $search_params = {
+ 'nachname' => $autor->{'nachname'},
+ 'vorname' => $autor->{'vorname'},
+ 'mittelname' => $autor->{'mittelname'},
+ 'name_suffix' => $autor->{'name_suffix'},
+ };
+ }
+ for my $autor_rs ( $c->model('Schema::Autoren')->search( $search_params )->all() ) {
+ $id = $autor_rs->id();
+ }
+
+ if ( $id ) {
+ $autor->{'id'} = $id;
+ $Params[0] = $id;
+ }
+ else {
+ $do_insert = 1;
+ }
+
+ $storage->dbh_do( $save_func, $do_insert, @Params );
- return $storage->last_insert_id();
+ my $author_id = $storage->last_insert_id();
+ unlock_tables($c);
+ return $author_id;
}