putting IC::DateTime locale, timezone or floating_tz_ok attributes into extra =>...
[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
7 =head1 NAME
8
9 DBIx::Class::InflateColumn::DateTime - Auto-create DateTime objects from date and datetime columns.
10
11 =head1 SYNOPSIS
12
13 Load this component and then declare one or more 
14 columns to be of the datetime, timestamp or date datatype.
15
16   package Event;
17   __PACKAGE__->load_components(qw/InflateColumn::DateTime Core/);
18   __PACKAGE__->add_columns(
19     starts_when => { data_type => 'datetime' }
20   );
21
22 NOTE: You B<must> load C<InflateColumn::DateTime> B<before> C<Core>. See
23 L<DBIx::Class::Manual::Component> for details.
24
25 Then you can treat the specified column as a L<DateTime> object.
26
27   print "This event starts the month of ".
28     $event->starts_when->month_name();
29
30 If you want to set a specific timezone and locale for that field, use:
31
32   __PACKAGE__->add_columns(
33     starts_when => { data_type => 'datetime', timezone => "America/Chicago", locale => "de_DE" }
34   );
35
36 If you want to inflate no matter what data_type your column is,
37 use inflate_datetime or inflate_date:
38
39   __PACKAGE__->add_columns(
40     starts_when => { data_type => 'varchar', inflate_datetime => 1 }
41   );
42   
43   __PACKAGE__->add_columns(
44     starts_when => { data_type => 'varchar', inflate_date => 1 }
45   );
46
47 It's also possible to explicitly skip inflation:
48   
49   __PACKAGE__->add_columns(
50     starts_when => { data_type => 'datetime', inflate_datetime => 0 }
51   );
52
53 =head1 DESCRIPTION
54
55 This module figures out the type of DateTime::Format::* class to 
56 inflate/deflate with based on the type of DBIx::Class::Storage::DBI::* 
57 that you are using.  If you switch from one database to a different 
58 one your code should continue to work without modification (though note
59 that this feature is new as of 0.07, so it may not be perfect yet - bug
60 reports to the list very much welcome).
61
62 For more help with using components, see L<DBIx::Class::Manual::Component/USING>.
63
64 =cut
65
66 __PACKAGE__->load_components(qw/InflateColumn/);
67
68 __PACKAGE__->mk_group_accessors('simple' => '__datetime_parser');
69
70 =head2 register_column
71
72 Chains with the L<DBIx::Class::Row/register_column> method, and sets
73 up datetime columns appropriately.  This would not normally be
74 directly called by end users.
75
76 In the case of an invalid date, L<DateTime> will throw an exception.  To
77 bypass these exceptions and just have the inflation return undef, use
78 the C<datetime_undef_if_invalid> option in the column info:
79   
80     "broken_date",
81     {
82         data_type => "datetime",
83         default_value => '0000-00-00',
84         is_nullable => 1,
85         datetime_undef_if_invalid => 1
86     }
87
88 =cut
89
90 sub register_column {
91   my ($self, $column, $info, @rest) = @_;
92   $self->next::method($column, $info, @rest);
93   return unless defined($info->{data_type});
94
95   my $type;
96
97   for (qw/date datetime/) {
98     my $key = "inflate_${_}";
99
100     next unless exists $info->{$key};
101     return unless $info->{$key};
102
103     $type = $_;
104     last;
105   }
106
107   unless ($type) {
108     $type = lc($info->{data_type});
109     $type = 'datetime' if ($type =~ /^timestamp/);
110   }
111
112   my $timezone;
113   if ( defined $info->{extra}{timezone} ) {
114     warn "Putting timezone into extra => { timezone => '...' } has been deprecated, ".
115          "please put it directly into the columns definition.";
116     $timezone = $info->{extra}{timezone};
117   }
118
119   my $locale;
120   if ( defined $info->{extra}{locale} ) {
121     warn "Putting locale into extra => { locale => '...' } has been deprecated, ".
122          "please put it directly into the columns definition.";
123     $locale = $info->{extra}{locale};
124   }
125   
126   $locale   = $info->{locale}   if defined $info->{locale};
127   $timezone = $info->{timezone} if defined $info->{timezone};
128
129   my $undef_if_invalid = $info->{datetime_undef_if_invalid};
130
131   if ($type eq 'datetime' || $type eq 'date') {
132     my ($parse, $format) = ("parse_${type}", "format_${type}");
133
134     # This assignment must happen here, otherwise Devel::Cycle treats
135     # the resulting deflator as a circular reference (go figure):
136     #
137     # Cycle #1
138     #     DBICTest::Schema A->{source_registrations} => %B
139     #     %B->{Event} => DBIx::Class::ResultSource::Table C
140     #     DBIx::Class::ResultSource::Table C->{_columns} => %D
141     #     %D->{created_on} => %E
142     #     %E->{_inflate_info} => %F
143     #     %F->{deflate} => &G
144     #     closure &G, $info => $H
145     #     $H => %E
146     #
147     my $floating_tz_ok;
148     if (defined $info->{extra}{floating_tz_ok}) {
149       warn "Putting floating_tz_ok into extra => { floating_tz_ok => 1 } has been deprecated, ".
150            "please put it directly into the columns definition.";
151       $floating_tz_ok = $info->{extra}{floating_tz_ok};
152     }
153     $floating_tz_ok = $info->{floating_tz_ok} if defined $info->{floating_tz_ok};
154
155     $self->inflate_column(
156       $column =>
157         {
158           inflate => sub {
159             my ($value, $obj) = @_;
160             my $dt = eval { $obj->_datetime_parser->$parse($value); };
161             die "Error while inflating ${value} for ${column} on ${self}: $@"
162               if $@ and not $undef_if_invalid;
163             $dt->set_time_zone($timezone) if $timezone;
164             $dt->set_locale($locale) if $locale;
165             return $dt;
166           },
167           deflate => sub {
168             my ($value, $obj) = @_;
169             if ($timezone) {
170                 warn "You're using a floating timezone, please see the documentation of"
171                   . " DBIx::Class::InflateColumn::DateTime for an explanation"
172                   if ref( $value->time_zone ) eq 'DateTime::TimeZone::Floating'
173                       and not $floating_tz_ok
174                       and not $ENV{DBIC_FLOATING_TZ_OK};
175                 $value->set_time_zone($timezone);
176                 $value->set_locale($locale) if $locale;
177             }
178             $obj->_datetime_parser->$format($value);
179           },
180         }
181     );
182   }
183 }
184
185 sub _datetime_parser {
186   my $self = shift;
187   if (my $parser = $self->__datetime_parser) {
188     return $parser;
189   }
190   my $parser = $self->result_source->storage->datetime_parser(@_);
191   return $self->__datetime_parser($parser);
192 }
193
194 1;
195 __END__
196
197 =head1 USAGE NOTES
198
199 If you have a datetime column with the C<timezone> extra setting, and subsenquently 
200 create/update this column with a DateTime object in the L<DateTime::TimeZone::Floating>
201 timezone, you will get a warning (as there is a very good chance this will not have the
202 result you expect). For example:
203
204   __PACKAGE__->add_columns(
205     starts_when => { data_type => 'datetime', timezone => "America/Chicago" }
206   );
207
208   my $event = $schema->resultset('EventTZ')->create({
209     starts_at => DateTime->new(year=>2007, month=>12, day=>31, ),
210   });
211
212 The warning can be avoided in several ways:
213
214 =over
215
216 =item Fix your broken code
217
218 When calling C<set_time_zone> on a Floating DateTime object, the timezone is simply
219 set to the requested value, and B<no time conversion takes place>. It is always a good idea
220 to be supply explicit times to the database:
221
222   my $event = $schema->resultset('EventTZ')->create({
223     starts_at => DateTime->new(year=>2007, month=>12, day=>31, time_zone => "America/Chicago" ),
224   });
225
226 =item Suppress the check on per-column basis
227
228   __PACKAGE__->add_columns(
229     starts_when => { data_type => 'datetime', timezone => "America/Chicago", floating_tz_ok => 1 }
230   );
231
232 =item Suppress the check globally
233
234 Set the environment variable DBIC_FLOATING_TZ_OK to some true value.
235
236 =back
237
238 Putting extra attributes like timezone, locale or floating_tz_ok into extra => {} has been
239 B<DEPRECATED> because this gets you into trouble using L<DBIx::Class::Schema::Versioned>.
240 Instead put it directly into the columns definition like in the examples above. If you still
241 use the old way you'll see a warning - please fix your code then!
242
243 =head1 SEE ALSO
244
245 =over 4
246
247 =item More information about the add_columns method, and column metadata, 
248       can be found in the documentation for L<DBIx::Class::ResultSource>.
249
250 =item Further discussion of problems inherent to the Floating timezone:
251       L<Floating DateTimes|DateTime/Floating_DateTimes> 
252       and L<< $dt->set_time_zone|DateTime/"Set" Methods >>
253
254 =back
255
256 =head1 AUTHOR
257
258 Matt S. Trout <mst@shadowcatsystems.co.uk>
259
260 =head1 CONTRIBUTORS
261
262 Aran Deltac <bluefeet@cpan.org>
263
264 =head1 LICENSE
265
266 You may distribute this code under the same terms as Perl itself.
267