Inflate/Deflate on all refs but scalars, with tests and all!
[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 references 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 references, i.e. "inflating"
24 the column data. It also "deflates" references 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 It will accept arrayrefs, hashrefs and blessed references (objects),
31 but not scalarrefs. Scalar references are passed through to the
32 database to deal with, to allow such settings as C< \'year + 1'> and
33 C< \'DEFAULT' > to work.
34
35 =head1 METHODS
36
37 =head2 inflate_column
38
39 Instruct L<DBIx::Class> to inflate the given column.
40
41 In addition to the column name, you must provide C<inflate> and
42 C<deflate> methods. The C<inflate> method is called when you access
43 the field, while the C<deflate> method is called when the field needs
44 to used by the database.
45
46 For example, if you have a table C<events> with a timestamp field
47 named C<insert_time>, you could inflate the column in the
48 corresponding table class using something like:
49
50     __PACKAGE__->inflate_column('insert_time', {
51         inflate => sub { DateTime::Format::Pg->parse_datetime(shift); },
52         deflate => sub { DateTime::Format::Pg->format_datetime(shift); },
53     });
54
55 (Replace L<DateTime::Format::Pg> with the appropriate module for your
56 database, or consider L<DateTime::Format::DBI>.)
57
58 The coderefs you set for inflate and deflate are called with two parameters,
59 the first is the value of the column to be inflated/deflated, the second is the
60 row object itself. Thus you can call C<< ->result_source->schema->storage->dbh >> on
61 it, to feed to L<DateTime::Format::DBI>.
62
63 In this example, calls to an event's C<insert_time> accessor return a
64 L<DateTime> object. This L<DateTime> object is later "deflated" when
65 used in the database layer.
66
67 =cut
68
69 sub inflate_column {
70   my ($self, $col, $attrs) = @_;
71   $self->throw_exception("No such column $col to inflate")
72     unless $self->has_column($col);
73   $self->throw_exception("inflate_column needs attr hashref")
74     unless ref $attrs eq 'HASH';
75   $self->column_info($col)->{_inflate_info} = $attrs;
76   $self->mk_group_accessors('inflated_column' => $col);
77   return 1;
78 }
79
80 sub _inflated_column {
81   my ($self, $col, $value) = @_;
82   return $value unless defined $value; # NULL is NULL is NULL
83   my $info = $self->column_info($col)
84     or $self->throw_exception("No column info for $col");
85   return $value unless exists $info->{_inflate_info};
86   my $inflate = $info->{_inflate_info}{inflate};
87   $self->throw_exception("No inflator for $col") unless defined $inflate;
88   return $inflate->($value, $self);
89 }
90
91 sub _deflated_column {
92   my ($self, $col, $value) = @_;
93 #  return $value unless ref $value && blessed($value); # If it's not an object, don't touch it
94   ## Leave scalar refs (ala SQL::Abstract literal SQL), untouched, deflate all other refs
95   return $value unless (ref $value && ref($value) ne 'SCALAR');
96   my $info = $self->column_info($col) or
97     $self->throw_exception("No column info for $col");
98   return $value unless exists $info->{_inflate_info};
99   my $deflate = $info->{_inflate_info}{deflate};
100   $self->throw_exception("No deflator for $col") unless defined $deflate;
101   return $deflate->($value, $self);
102 }
103
104 =head2 get_inflated_column
105
106   my $val = $obj->get_inflated_column($col);
107
108 Fetch a column value in its inflated state.  This is directly
109 analogous to L<DBIx::Class::Row/get_column> in that it only fetches a
110 column already retreived from the database, and then inflates it.
111 Throws an exception if the column requested is not an inflated column.
112
113 =cut
114
115 sub get_inflated_column {
116   my ($self, $col) = @_;
117   $self->throw_exception("$col is not an inflated column")
118     unless exists $self->column_info($col)->{_inflate_info};
119   return $self->{_inflated_column}{$col}
120     if exists $self->{_inflated_column}{$col};
121   return $self->{_inflated_column}{$col} =
122            $self->_inflated_column($col, $self->get_column($col));
123 }
124
125 =head2 set_inflated_column
126
127   my $copy = $obj->set_inflated_column($col => $val);
128
129 Sets a column value from an inflated value.  This is directly
130 analogous to L<DBIx::Class::Row/set_column>.
131
132 =cut
133
134 sub set_inflated_column {
135   my ($self, $col, $obj) = @_;
136   $self->set_column($col, $self->_deflated_column($col, $obj));
137   if (blessed $obj) {
138     $self->{_inflated_column}{$col} = $obj; 
139   } else {
140     delete $self->{_inflated_column}{$col};      
141   }
142   return $obj;
143 }
144
145 =head2 store_inflated_column
146
147   my $copy = $obj->store_inflated_column($col => $val);
148
149 Sets a column value from an inflated value without marking the column
150 as dirty. This is directly analogous to L<DBIx::Class::Row/store_column>.
151
152 =cut
153
154 sub store_inflated_column {
155   my ($self, $col, $obj) = @_;
156   unless (blessed $obj) {
157       delete $self->{_inflated_column}{$col};
158       $self->store_column($col => $obj);
159       return $obj;
160   }
161   delete $self->{_column_data}{$col};
162   return $self->{_inflated_column}{$col} = $obj;
163 }
164
165 =head2 get_column
166
167 Gets a column value in the same way as L<DBIx::Class::Row/get_column>. If there
168 is an inflated value stored that has not yet been deflated, it is deflated
169 when the method is invoked.
170
171 =cut
172
173 sub get_column {
174   my ($self, $col) = @_;
175   if (exists $self->{_inflated_column}{$col}
176         && !exists $self->{_column_data}{$col}) {
177     $self->store_column($col, $self->_deflated_column($col, $self->{_inflated_column}{$col})); 
178   }
179   return $self->next::method($col);
180 }
181
182 =head2 get_columns 
183
184 Returns the get_column info for all columns as a hash,
185 just like L<DBIx::Class::Row/get_columns>.  Handles inflation just
186 like L</get_column>.
187
188 =cut
189
190 sub get_columns {
191   my $self = shift;
192   if (exists $self->{_inflated_column}) {
193     foreach my $col (keys %{$self->{_inflated_column}}) {
194       $self->store_column($col, $self->_deflated_column($col, $self->{_inflated_column}{$col}))
195        unless exists $self->{_column_data}{$col};
196     }
197   }
198   return $self->next::method;
199 }
200
201 =head2 has_column_loaded
202
203 Like L<DBIx::Class::Row/has_column_loaded>, but also returns true if there
204 is an inflated value stored.
205
206 =cut
207
208 sub has_column_loaded {
209   my ($self, $col) = @_;
210   return 1 if exists $self->{_inflated_column}{$col};
211   return $self->next::method($col);
212 }
213
214 =head2 update
215
216 Updates a row in the same way as L<DBIx::Class::Row/update>, handling
217 inflation and deflation of columns appropriately.
218
219 =cut
220
221 sub update {
222   my ($class, $attrs, @rest) = @_;
223   foreach my $key (keys %{$attrs||{}}) {
224     if (ref $attrs->{$key} && $class->has_column($key)
225           && exists $class->column_info($key)->{_inflate_info}) {
226       $class->set_inflated_column($key, delete $attrs->{$key});
227     }
228   }
229   return $class->next::method($attrs, @rest);
230 }
231
232 =head2 new
233
234 Creates a row in the same way as L<DBIx::Class::Row/new>, handling
235 inflation and deflation of columns appropriately.
236
237 =cut
238
239 sub new {
240   my ($class, $attrs, @rest) = @_;
241   my $inflated;
242   foreach my $key (keys %{$attrs||{}}) {
243     $inflated->{$key} = delete $attrs->{$key} 
244       if ref $attrs->{$key} && $class->has_column($key)
245          && exists $class->column_info($key)->{_inflate_info};
246   }
247   my $obj = $class->next::method($attrs, @rest);
248   $obj->{_inflated_column} = $inflated if $inflated;
249   return $obj;
250 }
251
252 =head1 SEE ALSO
253
254 =over 4
255
256 =item L<DBIx::Class::Core> - This component is loaded as part of the
257       "core" L<DBIx::Class> components; generally there is no need to
258       load it directly
259
260 =back
261
262 =head1 AUTHOR
263
264 Matt S. Trout <mst@shadowcatsystems.co.uk>
265
266 =head1 CONTRIBUTORS
267
268 Daniel Westermann-Clark <danieltwc@cpan.org> (documentation)
269
270 Jess Robinson <cpan@desert-island.demon.co.uk>
271
272 =head1 LICENSE
273
274 You may distribute this code under the same terms as Perl itself.
275
276 =cut
277
278 1;