DBIx-InsertHash
view release on metacpan or search on metacpan
lib/DBIx/InsertHash.pm view on Meta::CPAN
# sort by hash key (predictable results)
my @column = sort keys %$data;
my @value = map { $data->{$_} } @column;
# quote column names?
if (ref $self and ($self->quote or $self->quote_func)) {
foreach my $col (@column) {
next unless $self->quote or $self->quote_func->($col);
$col = $self->quote_char . $col . $self->quote_char;
}
}
my $sql = 'INSERT INTO '.$table.' (';
$sql .= join(', ', @column).') VALUES (';
$sql .= join(', ', ('?') x (scalar @column)).')';
$dbh->do($sql, {}, @value);
return $dbh->last_insert_id(undef, undef, $table, undef);
}
=head2 update
Update record from hash. Returns L<do|DBI/do>.
=over 4
=item data (HASHREF)
Row data. The keys have to match with the column names of your table.
This parameter is mandatory. If an empty hashref is given, no record is
inserted and a warning is given.
=item bind_values (ARRAYREF)
L<Bind values|DBI/Placeholders_and_Bind_Values> for the WHERE clause. If
you do not use or need them, just pass a false value (C<undef> or empty
string) or an empty arrayref. This parameter is optional and has no object
defaults.
=item where (STRING)
Where clause (with optional placeholders C<?>). If this parameter is
missing, the object default (see L<new>) is used. Otherwise it dies.
=item table (STRING)
Table name. If this parameter is missing, the object default (see L<new>
is used). Otherwise it dies.
=item dbh (OBJECT)
DBI database handle (you have to L<connect|DBI/connect> yourself). If
this parameter is missing, the object default (see L<new>) is used).
Otherwise it dies.
=back
=cut
sub update {
my ($self, $data, $vars, $where, $table, $dbh) = @_;
my @vars = ($vars ? @$vars : ());
# object defaults
if (ref $self) {
$where ||= $self->where;
$table ||= $self->table;
$dbh ||= $self->dbh;
}
unless (%$data) {
carp 'No data (empty hash)';
return;
}
croak 'No where clause' unless $where;
croak 'No table name' unless $table;
croak 'No DBI handle' unless $dbh;
# sort by hash key (predictable results)
my @column = sort keys %$data;
my @value = map { $data->{$_} } @column;
# quote column names?
if (ref $self and ($self->quote or $self->quote_func)) {
foreach my $col (@column) {
next unless $self->quote or $self->quote_func->($col);
$col = $self->quote_char . $col . $self->quote_char;
}
}
my $sql = 'UPDATE '.$table.' SET ';
$sql .= join(', ', map { "$_ = ?" } @column).' WHERE '.$where;
return $dbh->do($sql, {}, @value, @vars);
}
1;
__END__
=pod
=head1 REPOSITORY
http://github.com/uwe/dbix-inserthash/tree/master
=head1 AUTHOR
Uwe Voelker, <uwe.voelker@gmx.de>
=cut
( run in 0.757 second using v1.01-cache-2.11-cpan-39bf76dae61 )