DBIx-ActiveRecord
view release on metacpan or search on metacpan
lib/DBIx/ActiveRecord/Model.pm view on Meta::CPAN
bless {-org => {}, -set => $hash || {}, in_storage => 0}, $self;
}
sub _new_from_storage {
my ($self, $hash) = @_;
bless {-org => $hash, -set => {}, in_storage => 1}, $self;
}
sub get_column {
my ($self, $name) = @_;
exists $self->{-set}->{$name} ? $self->{-set}->{$name} : $self->{-org}->{$name};
}
sub set_column {
my ($self, $name, $value) = @_;
$self->{-set}->{$name} = $value;
}
sub to_hash {
my $self = shift;
my %h;
foreach (keys %{$self->{-org}}, keys %{$self->{-set}}) {
$h{$_} = $self->get_column($_);
}
\%h;
}
sub in_storage { shift->{in_storage} }
sub create {
my ($self, $hash) = @_;
my $o = $self->new($hash);
$o->save;
$o;
}
sub save {
my $self = shift;
my $res = $self->in_storage ? $self->update(@_) : $self->insert(@_);
$self->{in_storage} = 1;
%{$self->{-org}} = (%{$self->{-org}}, %{$self->{-set}});
$self->{-set} = {};
$res;
}
sub insert {
my ($self) = @_;
return if $self->in_storage;
my $s = $self->scoped;
$self->_record_timestamp(INSERT_RECORD_TIMESTAMPS);
my $arel = $s->{arel}->insert($self->to_hash, $self->_global->{columns});
my $sth = $self->dbh->prepare($arel->to_sql);
my $res = $sth->execute($arel->binds) || croak $sth->errstr;
my $insert_id = $sth->{'insertid'} || $self->dbh->{'mysql_insertid'};
$self->{-set}->{$self->_global->{primary_keys}->[0]} = $insert_id if $insert_id;
$res;
}
sub update {
my ($self) = @_;
return if !%{$self->{-set}};
return if !$self->in_storage;
my $s = $self->_pkey_scope;
$self->_record_timestamp(UPDATE_RECORD_TIMESTAMPS);
my $arel = $s->{arel}->update($self->{-set}, $self->_global->{columns});
my $sth = $self->dbh->prepare($arel->to_sql);
$sth->execute($arel->binds) || croak $sth->errstr;
}
sub delete {
my ($self) = @_;
return if !$self->in_storage;
my $s = $self->_pkey_scope;
my $arel = $s->{arel}->delete;
my $sth = $self->dbh->prepare($arel->to_sql);
$sth->execute($arel->binds) || croak $sth->errstr;
}
sub count { shift->scoped->count }
sub _record_timestamp {
my ($self, $columns) = @_;
my %cs = map {$_ => 1} @{$self->_global->{columns}};
my $now = POSIX::strftime("%Y-%m-%d %H:%M:%S", localtime);
foreach (@$columns) {
$self->{-set}->{$_} = $now if $cs{$_};
}
}
sub _pkey_scope {
my $self = shift;
my $s = $self->unscoped;
$s = $s->eq($_ => $self->{-org}->{$_} || croak 'no primary key') for @{$self->_global->{primary_keys}};
$s;
}
sub instantiates_by_relation {
my ($self, $relation) = @_;
my $sth = $self->dbh->prepare($relation->to_sql);
$sth->execute($relation->_binds) || croak $sth->errstr;
my @all;
while (my $row = $sth->fetchrow_hashref) {
push @all, $self->_new_from_storage($row);
}
\@all;
}
1;
( run in 1.859 second using v1.01-cache-2.11-cpan-39bf76dae61 )