DBIx-Wizard
view release on metacpan or search on metacpan
lib/DBIx/Wizard/ResultSet.pm view on Meta::CPAN
sub count {
my $clone = shift->_clone;
$clone->{columns} = [$sw->func('COUNT', '*')];
my @count = $clone->_select();
## NOTE: fallback is for ClickHouse
return $count[0]->{'COUNT(*)'} // $count[0]->{'count()'} // $count[0]->{'COUNT()'};
}
sub exists {
my $self = shift;
return $self->count > 0;
}
sub sum {
my ($self, $column) = @_;
my $clone = $self->_clone;
$column =~ s/[^\w\.]+//gs;
$clone->{columns} = [$sw->func('SUM', $column)];
my @sum = $clone->_select();
return $sum[0]->{"SUM($column)"} + 0;
}
## Data modification
sub insert {
my ($self, $rh_insert, $auto_pk) = @_;
$rh_insert ||= {};
my $dbh = DBIx::Wizard::DB->dbh($self->{db});
$auto_pk ||= DBIx::Wizard::DB::Table->auto_pk($self->{db}, $self->{table});
my ($sql, @bind) = $sw->insert(
-into => $self->{table},
-values => $rh_insert,
)->to_sql;
_debug_log('insert', $sql, @bind);
my $sth = $dbh->prepare($sql);
$sth->execute(@bind) || croak "DBIW: insert failed: $DBI::errstr";
if ($auto_pk) {
my @row;
if ($sth->can('last_insert_id')) {
@row = $sth->last_insert_id();
} elsif ($dbh->can('last_insert_id')) {
@row = $dbh->last_insert_id(undef, $self->{db}, $self->{table}, $auto_pk);
} else {
@row = $dbh->selectrow_array('SELECT LAST_INSERT_ID()');
}
return $row[0];
}
return;
}
sub update {
my ($self, $rh_update) = @_;
my ($sql, @bind) = $sw->update(
-table => $self->{table},
-set => $rh_update,
($self->{where}) ? (-where => $self->{where}) : (),
(defined $self->{limit}) ? (-limit => $self->{limit}) : (),
)->to_sql;
_debug_log('update', $sql, @bind);
my $dbh = DBIx::Wizard::DB->dbh($self->{db});
my $sth = $dbh->prepare($sql);
$sth->execute(@bind) || croak "DBIW: update failed: $DBI::errstr";
return $sth->rows;
}
sub delete {
my $self = shift;
my ($sql, @bind) = $sw->delete(
-from => $self->{table},
($self->{where}) ? (-where => $self->{where}) : (),
)->to_sql;
_debug_log('delete', $sql, @bind);
my $dbh = DBIx::Wizard::DB->dbh($self->{db});
my $sth = $dbh->prepare($sql);
$sth->execute(@bind) || croak "DBIW: delete failed: $DBI::errstr";
}
sub truncate {
my $self = shift;
my $dbh = DBIx::Wizard::DB->dbh($self->{db});
my $driver = $dbh->{Driver}->{Name};
# SQLite doesn't support TRUNCATE TABLE
my ($sql, @bind);
if ($driver eq 'SQLite') {
($sql, @bind) = $sw->delete(-from => $self->{table})->to_sql;
} else {
($sql, @bind) = $sw->truncate(-table => $self->{table})->to_sql;
}
_debug_log('truncate', $sql, @bind);
my $sth = $dbh->prepare($sql);
$sth->execute(@bind) || croak "DBIW: truncate failed: $DBI::errstr";
}
sub dbh {
my $self = shift;
return DBIx::Wizard::DB->dbh($self->{db});
}
## Internal
( run in 0.498 second using v1.01-cache-2.11-cpan-39bf76dae61 )