Merge 'trunk' into 'DBIx-Class-C3'
[dbsrgits/DBIx-Class-Historic.git] / lib / DBIx / Class / InflateColumn.pm
CommitLineData
0e5c2582 1package DBIx::Class::InflateColumn;
2
3use strict;
4use warnings;
5
6sub inflate_column {
7 my ($self, $col, $attrs) = @_;
103647d5 8 die "No such column $col to inflate" unless $self->has_column($col);
0e5c2582 9 die "inflate_column needs attr hashref" unless ref $attrs eq 'HASH';
103647d5 10 $self->column_info($col)->{_inflate_info} = $attrs;
0e5c2582 11 $self->mk_group_accessors('inflated_column' => $col);
12 return 1;
13}
14
4a07648a 15sub _inflated_column {
0e5c2582 16 my ($self, $col, $value) = @_;
9f300b1b 17 return $value unless defined $value; # NULL is NULL is NULL
103647d5 18 my $info = $self->column_info($col) || die "No column info for $col";
19 return $value unless exists $info->{_inflate_info};
20 my $inflate = $info->{_inflate_info}{inflate};
21 die "No inflator for $col" unless defined $inflate;
0e5c2582 22 return $inflate->($value, $self);
23}
24
4a07648a 25sub _deflated_column {
0e5c2582 26 my ($self, $col, $value) = @_;
27 return $value unless ref $value; # If it's not an object, don't touch it
103647d5 28 my $info = $self->column_info($col) || die "No column info for $col";
29 return $value unless exists $info->{_inflate_info};
30 my $deflate = $info->{_inflate_info}{deflate};
31 die "No deflator for $col" unless defined $deflate;
0e5c2582 32 return $deflate->($value, $self);
33}
34
35sub get_inflated_column {
36 my ($self, $col) = @_;
37 $self->throw("$col is not an inflated column") unless
103647d5 38 exists $self->column_info($col)->{_inflate_info};
4a07648a 39
0e5c2582 40 return $self->{_inflated_column}{$col}
41 if exists $self->{_inflated_column}{$col};
0e5c2582 42 return $self->{_inflated_column}{$col} =
4a07648a 43 $self->_inflated_column($col, $self->get_column($col));
0e5c2582 44}
45
46sub set_inflated_column {
47 my ($self, $col, @rest) = @_;
48 my $ret = $self->store_inflated_column($col, @rest);
49 $self->{_dirty_columns}{$col} = 1;
50 return $ret;
51}
52
53sub store_inflated_column {
54 my ($self, $col, $obj) = @_;
55 unless (ref $obj) {
56 delete $self->{_inflated_column}{$col};
57 return $self->store_column($col, $obj);
58 }
4a07648a 59
60 my $deflated = $self->_deflated_column($col, $obj);
9f300b1b 61 # Do this now so we don't store if it's invalid
4a07648a 62
0e5c2582 63 $self->{_inflated_column}{$col} = $obj;
64 #warn "Storing $obj: ".($obj->_ident_values)[0];
9f300b1b 65 $self->store_column($col, $deflated);
0e5c2582 66 return $obj;
67}
68
69sub new {
70 my ($class, $attrs, @rest) = @_;
71 $attrs ||= {};
0e5c2582 72 foreach my $key (keys %$attrs) {
103647d5 73 if (ref $attrs->{$key}
74 && exists $class->column_info($key)->{_inflate_info}) {
484c9dda 75 $attrs->{$key} = $class->_deflated_column($key, $attrs->{$key});
0e5c2582 76 }
77 }
147dd158 78 return $class->next::method($attrs, @rest);
0e5c2582 79}
80
0e5c2582 811;