d5791cb600c5f70b47756f120c80000932e23d6d
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / InflateColumn.pm
1 package DBIx::Class::InflateColumn;
2
3 use strict;
4 use warnings;
5 use Scalar::Util qw/blessed/;
6
7 use base qw/DBIx::Class::Row/;
8
9 =head1 NAME
10
11 DBIx::Class::InflateColumn - Automatically create objects from column data
12
13 =head1 SYNOPSIS
14
15     # In your table classes
16     __PACKAGE__->inflate_column('column_name', {
17         inflate => sub { ... },
18         deflate => sub { ... },
19     });
20
21 =head1 DESCRIPTION
22
23 This component translates column data into objects, i.e. "inflating"
24 the column data. It also "deflates" objects into an appropriate format
25 for the database.
26
27 It can be used, for example, to automatically convert to and from
28 L<DateTime> objects for your date and time fields.
29
30 =head1 METHODS
31
32 =head2 inflate_column
33
34 Instruct L<DBIx::Class> to inflate the given column.
35
36 In addition to the column name, you must provide C<inflate> and
37 C<deflate> methods. The C<inflate> method is called when you access
38 the field, while the C<deflate> method is called when the field needs
39 to used by the database.
40
41 For example, if you have a table C<events> with a timestamp field
42 named C<insert_time>, you could inflate the column in the
43 corresponding table class using something like:
44
45     __PACKAGE__->inflate_column('insert_time', {
46         inflate => sub { DateTime::Format::Pg->parse_datetime(shift); },
47         deflate => sub { DateTime::Format::Pg->format_datetime(shift); },
48     });
49
50 (Replace L<DateTime::Format::Pg> with the appropriate module for your
51 database, or consider L<DateTime::Format::DBI>.)
52
53 The coderefs you set for inflate and deflate are called with two parameters,
54 the first is the value of the column to be inflated/deflated, the second is the
55 row object itself. Thus you can call C<< ->result_source->schema->storage->dbh >> on
56 it, to feed to L<DateTime::Format::DBI>.
57
58 In this example, calls to an event's C<insert_time> accessor return a
59 L<DateTime> object. This L<DateTime> object is later "deflated" when
60 used in the database layer.
61
62 =cut
63
64 sub inflate_column {
65   my ($self, $col, $attrs) = @_;
66   $self->throw_exception("No such column $col to inflate")
67     unless $self->has_column($col);
68   $self->throw_exception("inflate_column needs attr hashref")
69     unless ref $attrs eq 'HASH';
70   $self->column_info($col)->{_inflate_info} = $attrs;
71   $self->mk_group_accessors('inflated_column' => $col);
72   return 1;
73 }
74
75 sub _inflated_column {
76   my ($self, $col, $value) = @_;
77   return $value unless defined $value; # NULL is NULL is NULL
78   my $info = $self->column_info($col)
79     or $self->throw_exception("No column info for $col");
80   return $value unless exists $info->{_inflate_info};
81   my $inflate = $info->{_inflate_info}{inflate};
82   $self->throw_exception("No inflator for $col") unless defined $inflate;
83   return $inflate->($value, $self);
84 }
85
86 sub _deflated_column {
87   my ($self, $col, $value) = @_;
88   return $value unless ref $value; # If it's not an object, don't touch it
89   my $info = $self->column_info($col) or
90     $self->throw_exception("No column info for $col");
91   return $value unless exists $info->{_inflate_info};
92   my $deflate = $info->{_inflate_info}{deflate};
93   $self->throw_exception("No deflator for $col") unless defined $deflate;
94   return $deflate->($value, $self);
95 }
96
97 =head2 get_inflated_column
98
99   my $val = $obj->get_inflated_column($col);
100
101 Fetch a column value in its inflated state.  This is directly
102 analogous to L<DBIx::Class::Row/get_column> in that it only fetches a
103 column already retreived from the database, and then inflates it.
104 Throws an exception if the column requested is not an inflated column.
105
106 =cut
107
108 sub get_inflated_column {
109   my ($self, $col) = @_;
110   $self->throw_exception("$col is not an inflated column")
111     unless exists $self->column_info($col)->{_inflate_info};
112   return $self->{_inflated_column}{$col}
113     if exists $self->{_inflated_column}{$col};
114   return $self->{_inflated_column}{$col} =
115            $self->_inflated_column($col, $self->get_column($col));
116 }
117
118 =head2 set_inflated_column
119
120   my $copy = $obj->set_inflated_column($col => $val);
121
122 Sets a column value from an inflated value.  This is directly
123 analogous to L<DBIx::Class::Row/set_column>.
124
125 =cut
126
127 sub set_inflated_column {
128   my ($self, $col, $obj) = @_;
129   $self->set_column($col, $self->_deflated_column($col, $obj));
130   if (blessed $obj) {
131     $self->{_inflated_column}{$col} = $obj; 
132   } else {
133     delete $self->{_inflated_column}{$col};      
134   }
135   return $obj;
136 }
137
138 =head2 store_inflated_column
139
140   my $copy = $obj->store_inflated_column($col => $val);
141
142 Sets a column value from an inflated value without marking the column
143 as dirty. This is directly analogous to L<DBIx::Class::Row/store_column>.
144
145 =cut
146
147 sub store_inflated_column {
148   my ($self, $col, $obj) = @_;
149   unless (blessed $obj) {
150       delete $self->{_inflated_column}{$col};
151       $self->store_column($col => $obj);
152       return $obj;
153   }
154   delete $self->{_column_data}{$col};
155   return $self->{_inflated_column}{$col} = $obj;
156 }
157
158 =head2 get_column
159
160 Gets a column value in the same way as L<DBIx::Class::Row/get_column>. If there
161 is an inflated value stored that has not yet been deflated, it is deflated
162 when the method is invoked.
163
164 =cut
165
166 sub get_column {
167   my ($self, $col) = @_;
168   if (exists $self->{_inflated_column}{$col}
169         && !exists $self->{_column_data}{$col}) {
170     $self->store_column($col, $self->_deflated_column($col, $self->{_inflated_column}{$col})); 
171   }
172   return $self->next::method($col);
173 }
174
175 sub get_columns {
176   my $self = shift;
177   if (exists $self->{_inflated_column}) {
178     foreach my $col (keys %{$self->{_inflated_column}}) {
179       $self->store_column($col, $self->_deflated_column($col, $self->{_inflated_column}{$col}))
180        unless exists $self->{_column_data}{$col};
181     }
182   }
183   return $self->next::method;
184 }
185
186 sub has_column_loaded {
187   my ($self, $col) = @_;
188   return 1 if exists $self->{_inflated_column}{$col};
189   return $self->next::method($col);
190 }
191
192 =head2 update
193
194 Updates a row in the same way as L<DBIx::Class::Row/update>, handling
195 inflation and deflation of columns appropriately.
196
197 =cut
198
199 sub update {
200   my ($class, $attrs, @rest) = @_;
201   foreach my $key (keys %{$attrs||{}}) {
202     if (ref $attrs->{$key}
203           && exists $class->column_info($key)->{_inflate_info}) {
204       $class->set_inflated_column($key, delete $attrs->{$key});
205     }
206   }
207   return $class->next::method($attrs, @rest);
208 }
209
210 =head2 new
211
212 Creates a row in the same way as L<DBIx::Class::Row/new>, handling
213 inflation and deflation of columns appropriately.
214
215 =cut
216
217 sub new {
218   my ($class, $attrs, @rest) = @_;
219   my $inflated;
220   foreach my $key (keys %{$attrs||{}}) {
221     $inflated->{$key} = delete $attrs->{$key} 
222       if ref $attrs->{$key} && exists $class->column_info($key)->{_inflate_info};
223   }
224   my $obj = $class->next::method($attrs, @rest);
225   $obj->{_inflated_column} = $inflated if $inflated;
226   return $obj;
227 }
228
229 =head1 SEE ALSO
230
231 =over 4
232
233 =item L<DBIx::Class::Core> - This component is loaded as part of the
234       "core" L<DBIx::Class> components; generally there is no need to
235       load it directly
236
237 =back
238
239 =head1 AUTHOR
240
241 Matt S. Trout <mst@shadowcatsystems.co.uk>
242
243 =head1 CONTRIBUTORS
244
245 Daniel Westermann-Clark <danieltwc@cpan.org> (documentation)
246
247 =head1 LICENSE
248
249 You may distribute this code under the same terms as Perl itself.
250
251 =cut
252
253 1;