DBIO
view release on metacpan or search on metacpan
lib/DBIO/Timestamp.pm view on Meta::CPAN
package DBIO::Timestamp;
# ABSTRACT: Automatically set and update timestamp columns
use strict;
use warnings;
use DateTime;
sub add_columns {
my ($self, @cols) = @_;
my @columns;
while (my $col = shift @cols) {
my $info = ref $cols[0] ? shift @cols : {};
if (delete $info->{set_on_create}) {
$info->{_timestamp_on_create} = 1;
}
if (delete $info->{set_on_update}) {
$info->{_timestamp_on_update} = 1;
}
push @columns, $col => $info;
}
return $self->next::method(@columns);
}
sub insert {
my $self = shift;
my $columns_info = $self->result_source->columns_info;
for my $col (keys %$columns_info) {
next unless $columns_info->{$col}{_timestamp_on_create};
next if defined $self->get_column($col);
$self->store_column($col => $self->get_timestamp);
}
return $self->next::method(@_);
}
sub update {
my $self = shift;
my $upd = shift;
$self->set_inflated_columns($upd) if $upd;
my $columns_info = $self->result_source->columns_info;
for my $col (keys %$columns_info) {
next unless $columns_info->{$col}{_timestamp_on_update};
$self->set_inflated_columns({ $col => $self->get_timestamp });
}
return $self->next::method(@_);
}
sub get_timestamp {
return DateTime->now;
}
sub col_created {
my ($self, $name) = @_;
$name ||= 'created_at';
$self->add_columns($name => {
data_type => 'timestamp',
set_on_create => 1,
is_nullable => 0,
});
}
sub col_updated {
my ($self, $name) = @_;
$name ||= 'updated_at';
$self->add_columns($name => {
data_type => 'timestamp',
set_on_create => 1,
set_on_update => 1,
is_nullable => 0,
});
}
sub cols_updated_created {
my ($self) = @_;
$self->col_created;
$self->col_updated;
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
DBIO::Timestamp - Automatically set and update timestamp columns
( run in 1.955 second using v1.01-cache-2.11-cpan-600a1bdf6e4 )