DBIx-ObjectMapper
view release on metacpan or search on metacpan
lib/DBIx/ObjectMapper/Metadata/Polymorphic.pm view on Meta::CPAN
if( @_ == 1 and !ref($_[0]) ) {
my $name = shift;
if( exists $self->column_map->{$name} ) {
return $self->{columns}->[ $self->column_map->{$name} - 1 ];
}
else {
return;
}
}
elsif( @_ == 0 ) {
return @{$self->columns};
}
else {
confess '$obj->column(Scalar|Void)';
}
}
sub columns { $_[0]->{columns} }
sub column_map { $_[0]->{column_map} }
sub insert {
my $self = shift;
my %data = @_;
my %parent_data;
my %child_data;
for my $key ( keys %data ) {
if( $self->parent_table->c($key) ) {
$parent_data{$key} = $data{$key};
}
if( $self->child_table->c($key) ) {
$child_data{$key} = $data{$key};
}
}
my $parent_data = $self->parent_table->insert(%parent_data)->execute;
for my $add_col( keys %{$self->{shared_column}} ) {
$child_data{$add_col} = $parent_data->{$self->{shared_column}{$add_col}}
if exists $parent_data->{$self->{shared_column}{$add_col}};
}
return $self->child_table->insert(%child_data);
}
sub cast_cond {
my ( $self, $type, $cond ) = @_;
my @cond;
my $table = $type eq 'parent' ? $self->parent_table : $self->child_table;
for my $c (@$cond) {
push @cond, [ map { ref $_ ? $table->c( $_->name ) : $_ } @$c ];
}
return @cond;
}
sub update {
my $self = shift;
my ( $data, $cond ) = @_;
my %parent_data;
my %child_data;
for my $key ( keys %$data ) {
if( $self->{shared_column}->{$key} ) {
$parent_data{$key} = $data->{$key};
$child_data{$key} = $data->{$key};
}
else {
if( $self->parent_table->c($key) ) {
$parent_data{$key} = $data->{$key};
}
if( $self->child_table->c($key) ) {
$child_data{$key} = $data->{$key};
}
}
}
my @query;
if( keys %parent_data ) {
my @parent_where = $self->cast_cond( 'parent', $cond );
push @query,
$self->parent_table->update(\%parent_data, \@parent_where);
}
if( keys %child_data ) {
my @child_where = $self->cast_cond( 'child', $cond );
push @query, $self->child_table->update(\%child_data, \@child_where);
}
return @query;
}
sub delete {
my $self = shift;
my @where = @_;
my @query;
my @parent_where = $self->cast_cond( 'parent', \@where );
push @query, $self->parent_table->delete(@parent_where);
my @child_where = $self->cast_cond( 'child', \@where );
push @query, $self->child_table->delete(@child_where);
return @query;
}
sub select {
my $self = shift;
my $parent_join = $self->parent_table->select->builder->join;
return $self->query_object->select( $self->_select_query_callback )
->column(@{$self->columns})->from( $self )
->add_join(@$parent_join, [ $self->child_table => $self->rel_cond ]);
}
( run in 0.509 second using v1.01-cache-2.11-cpan-39bf76dae61 )