Microoptimization of the IC::DT registration code
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / InflateColumn / DateTime.pm
1 package DBIx::Class::InflateColumn::DateTime;
2
3 use strict;
4 use warnings;
5 use base qw/DBIx::Class/;
6 use Carp::Clan qw/^DBIx::Class/;
7 use Try::Tiny;
8 use namespace::clean;
9
10 =head1 NAME
11
12 DBIx::Class::InflateColumn::DateTime - Auto-create DateTime objects from date and datetime columns.
13
14 =head1 SYNOPSIS
15
16 Load this component and then declare one or more
17 columns to be of the datetime, timestamp or date datatype.
18
19   package Event;
20   use base 'DBIx::Class::Core';
21
22   __PACKAGE__->load_components(qw/InflateColumn::DateTime/);
23   __PACKAGE__->add_columns(
24     starts_when => { data_type => 'datetime' }
25     create_date => { data_type => 'date' }
26   );
27
28 Then you can treat the specified column as a L<DateTime> object.
29
30   print "This event starts the month of ".
31     $event->starts_when->month_name();
32
33 If you want to set a specific timezone and locale for that field, use:
34
35   __PACKAGE__->add_columns(
36     starts_when => { data_type => 'datetime', timezone => "America/Chicago", locale => "de_DE" }
37   );
38
39 If you want to inflate no matter what data_type your column is,
40 use inflate_datetime or inflate_date:
41
42   __PACKAGE__->add_columns(
43     starts_when => { data_type => 'varchar', inflate_datetime => 1 }
44   );
45
46   __PACKAGE__->add_columns(
47     starts_when => { data_type => 'varchar', inflate_date => 1 }
48   );
49
50 It's also possible to explicitly skip inflation:
51
52   __PACKAGE__->add_columns(
53     starts_when => { data_type => 'datetime', inflate_datetime => 0 }
54   );
55
56 NOTE: Don't rely on C<InflateColumn::DateTime> to parse date strings for you.
57 The column is set directly for any non-references and C<InflateColumn::DateTime>
58 is completely bypassed.  Instead, use an input parser to create a DateTime
59 object. For instance, if your user input comes as a 'YYYY-MM-DD' string, you can
60 use C<DateTime::Format::ISO8601> thusly:
61
62   use DateTime::Format::ISO8601;
63   my $dt = DateTime::Format::ISO8601->parse_datetime('YYYY-MM-DD');
64
65 =head1 DESCRIPTION
66
67 This module figures out the type of DateTime::Format::* class to
68 inflate/deflate with based on the type of DBIx::Class::Storage::DBI::*
69 that you are using.  If you switch from one database to a different
70 one your code should continue to work without modification (though note
71 that this feature is new as of 0.07, so it may not be perfect yet - bug
72 reports to the list very much welcome).
73
74 If the data_type of a field is C<date>, C<datetime> or C<timestamp> (or
75 a derivative of these datatypes, e.g. C<timestamp with timezone>), this
76 module will automatically call the appropriate parse/format method for
77 deflation/inflation as defined in the storage class. For instance, for
78 a C<datetime> field the methods C<parse_datetime> and C<format_datetime>
79 would be called on deflation/inflation. If the storage class does not
80 provide a specialized inflator/deflator, C<[parse|format]_datetime> will
81 be used as a fallback. See L<DateTime::Format> for more information on
82 date formatting.
83
84 For more help with using components, see L<DBIx::Class::Manual::Component/USING>.
85
86 =cut
87
88 __PACKAGE__->load_components(qw/InflateColumn/);
89
90 =head2 register_column
91
92 Chains with the L<DBIx::Class::Row/register_column> method, and sets
93 up datetime columns appropriately.  This would not normally be
94 directly called by end users.
95
96 In the case of an invalid date, L<DateTime> will throw an exception.  To
97 bypass these exceptions and just have the inflation return undef, use
98 the C<datetime_undef_if_invalid> option in the column info:
99
100     "broken_date",
101     {
102         data_type => "datetime",
103         default_value => '0000-00-00',
104         is_nullable => 1,
105         datetime_undef_if_invalid => 1
106     }
107
108 =cut
109
110 sub register_column {
111   my ($self, $column, $info, @rest) = @_;
112
113   $self->next::method($column, $info, @rest);
114
115   my $requested_type;
116   for (qw/datetime timestamp date/) {
117     my $key = "inflate_${_}";
118     if (exists $info->{$key}) {
119
120       # this bailout is intentional
121       return unless $info->{$key};
122
123       $requested_type = $_;
124       last;
125     }
126   }
127
128   return if (!$requested_type and !$info->{data_type});
129
130   my $data_type = lc( $info->{data_type} || '' );
131
132   # _ic_dt_method will follow whatever the registration requests
133   # thus = instead of ||=
134   if ($data_type eq 'timestamp with time zone' || $data_type eq 'timestamptz') {
135     $info->{_ic_dt_method} = 'timestamp_with_timezone';
136   }
137   elsif ($data_type eq 'timestamp without time zone') {
138     $info->{_ic_dt_method} = 'timestamp_without_timezone';
139   }
140   elsif ($data_type eq 'smalldatetime') {
141     $info->{_ic_dt_method} = 'smalldatetime';
142   }
143   elsif ($data_type =~ /^ (?: date | datetime | timestamp ) $/x) {
144     $info->{_ic_dt_method} = $data_type;
145   }
146   elsif ($requested_type) {
147     $info->{_ic_dt_method} = $requested_type;
148   }
149   else {
150     return;
151   }
152
153   if ($info->{extra}) {
154     for my $slot (qw/timezone locale floating_tz_ok/) {
155       if ( defined $info->{extra}{$slot} ) {
156         carp "Putting $slot into extra => { $slot => '...' } has been deprecated, ".
157              "please put it directly into the '$column' column definition.";
158         $info->{$slot} = $info->{extra}{$slot} unless defined $info->{$slot};
159       }
160     }
161   }
162
163   # shallow copy to avoid unfounded(?) Devel::Cycle complaints
164   my $infcopy = {%$info};
165
166   $self->inflate_column(
167     $column =>
168       {
169         inflate => sub {
170           my ($value, $obj) = @_;
171
172           my $dt = try
173             { $obj->_inflate_to_datetime( $value, $infcopy ) }
174             catch {
175               $self->throw_exception ("Error while inflating ${value} for ${column} on ${self}: $_")
176                 unless $infcopy->{datetime_undef_if_invalid};
177               undef;  # rv
178             };
179
180           return (defined $dt)
181             ? $obj->_post_inflate_datetime( $dt, $infcopy )
182             : undef
183           ;
184         },
185         deflate => sub {
186           my ($value, $obj) = @_;
187
188           $value = $obj->_pre_deflate_datetime( $value, $infcopy );
189           $obj->_deflate_from_datetime( $value, $infcopy );
190         },
191       }
192   );
193 }
194
195 sub _flate_or_fallback
196 {
197   my( $self, $value, $info, $method_fmt ) = @_;
198
199   my $parser = $self->_datetime_parser;
200   my $preferred_method = sprintf($method_fmt, $info->{ _ic_dt_method });
201   my $method = $parser->can($preferred_method) ? $preferred_method : sprintf($method_fmt, 'datetime');
202   return $parser->$method($value);
203 }
204
205 sub _inflate_to_datetime {
206   my( $self, $value, $info ) = @_;
207   return $self->_flate_or_fallback( $value, $info, 'parse_%s' );
208 }
209
210 sub _deflate_from_datetime {
211   my( $self, $value, $info ) = @_;
212   return $self->_flate_or_fallback( $value, $info, 'format_%s' );
213 }
214
215 sub _datetime_parser {
216   shift->result_source->storage->datetime_parser (@_);
217 }
218
219 sub _post_inflate_datetime {
220   my( $self, $dt, $info ) = @_;
221
222   $dt->set_time_zone($info->{timezone}) if defined $info->{timezone};
223   $dt->set_locale($info->{locale}) if defined $info->{locale};
224
225   return $dt;
226 }
227
228 sub _pre_deflate_datetime {
229   my( $self, $dt, $info ) = @_;
230
231   if (defined $info->{timezone}) {
232     carp "You're using a floating timezone, please see the documentation of"
233       . " DBIx::Class::InflateColumn::DateTime for an explanation"
234       if ref( $dt->time_zone ) eq 'DateTime::TimeZone::Floating'
235           and not $info->{floating_tz_ok}
236           and not $ENV{DBIC_FLOATING_TZ_OK};
237
238     $dt->set_time_zone($info->{timezone});
239   }
240
241   $dt->set_locale($info->{locale}) if defined $info->{locale};
242
243   return $dt;
244 }
245
246 1;
247 __END__
248
249 =head1 USAGE NOTES
250
251 If you have a datetime column with an associated C<timezone>, and subsequently
252 create/update this column with a DateTime object in the L<DateTime::TimeZone::Floating>
253 timezone, you will get a warning (as there is a very good chance this will not have the
254 result you expect). For example:
255
256   __PACKAGE__->add_columns(
257     starts_when => { data_type => 'datetime', timezone => "America/Chicago" }
258   );
259
260   my $event = $schema->resultset('EventTZ')->create({
261     starts_at => DateTime->new(year=>2007, month=>12, day=>31, ),
262   });
263
264 The warning can be avoided in several ways:
265
266 =over
267
268 =item Fix your broken code
269
270 When calling C<set_time_zone> on a Floating DateTime object, the timezone is simply
271 set to the requested value, and B<no time conversion takes place>. It is always a good idea
272 to be supply explicit times to the database:
273
274   my $event = $schema->resultset('EventTZ')->create({
275     starts_at => DateTime->new(year=>2007, month=>12, day=>31, time_zone => "America/Chicago" ),
276   });
277
278 =item Suppress the check on per-column basis
279
280   __PACKAGE__->add_columns(
281     starts_when => { data_type => 'datetime', timezone => "America/Chicago", floating_tz_ok => 1 }
282   );
283
284 =item Suppress the check globally
285
286 Set the environment variable DBIC_FLOATING_TZ_OK to some true value.
287
288 =back
289
290 Putting extra attributes like timezone, locale or floating_tz_ok into extra => {} has been
291 B<DEPRECATED> because this gets you into trouble using L<DBIx::Class::Schema::Versioned>.
292 Instead put it directly into the columns definition like in the examples above. If you still
293 use the old way you'll see a warning - please fix your code then!
294
295 =head1 SEE ALSO
296
297 =over 4
298
299 =item More information about the add_columns method, and column metadata,
300       can be found in the documentation for L<DBIx::Class::ResultSource>.
301
302 =item Further discussion of problems inherent to the Floating timezone:
303       L<Floating DateTimes|DateTime/Floating_DateTimes>
304       and L<< $dt->set_time_zone|DateTime/"Set" Methods >>
305
306 =back
307
308 =head1 AUTHOR
309
310 Matt S. Trout <mst@shadowcatsystems.co.uk>
311
312 =head1 CONTRIBUTORS
313
314 Aran Deltac <bluefeet@cpan.org>
315
316 =head1 LICENSE
317
318 You may distribute this code under the same terms as Perl itself.
319