referencing DateTime/Floating_DateTimes
[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 Then you can treat the specified column as a L<DateTime> object.
23
24   print "This event starts the month of ".
25     $event->starts_when->month_name();
26
27 If you want to set a specific timezone for that field, use:
28
29   __PACKAGE__->add_columns(
30     starts_when => { data_type => 'datetime', extra => { timezone => "America/Chicago" } }
31   );
32
33 If you want to inflate no matter what data_type your column is,
34 use inflate_datetime or inflate_date:
35
36   __PACKAGE__->add_columns(
37     starts_when => { data_type => 'varchar', inflate_datetime => 1 }
38   );
39   
40   __PACKAGE__->add_columns(
41     starts_when => { data_type => 'varchar', inflate_date => 1 }
42   );
43
44 It's also possible to explicitly skip inflation:
45   
46   __PACKAGE__->add_columns(
47     starts_when => { data_type => 'datetime', inflate_datetime => 0 }
48   );
49
50 =head1 WARNING
51
52 You'll notice some warning about floating timezone if you set timezone in your schema but
53 didn't set it when creating/updating a row:
54
55   __PACKAGE__->add_columns(
56     starts_when => { data_type => 'datetime', extra => { timezone => "America/Chicago" } }
57   );
58
59   my $event = $schema->resultset('EventTZ')->create({
60     starts_at => DateTime->new(year=>2007, month=>12, day=>31, ),
61   });
62
63 To avoid this, you have three options:
64
65 =over
66
67 =item Fix your broken code
68
69   my $event = $schema->resultset('EventTZ')->create({
70     starts_at => DateTime->new(year=>2007, month=>12, day=>31, time_zone => "America/Chicago" ),
71   });
72
73 =item Suppress the warning by doing either ...
74
75   __PACKAGE__->add_columns(
76     starts_when => { data_type => 'datetime', extra => { timezone => "America/Chicago", floating_tz_ok => 1 } }
77   );
78
79 =item ... or ...
80
81 Set environment variable DBIC_FLOATING_TZ_OK to some true value.
82
83 =back
84
85 Please take  look at L<DateTime/Floating_DateTimes> for further information abour floating
86 timezone.
87
88 =head1 DESCRIPTION
89
90 This module figures out the type of DateTime::Format::* class to 
91 inflate/deflate with based on the type of DBIx::Class::Storage::DBI::* 
92 that you are using.  If you switch from one database to a different 
93 one your code should continue to work without modification (though note
94 that this feature is new as of 0.07, so it may not be perfect yet - bug
95 reports to the list very much welcome).
96
97 For more help with using components, see L<DBIx::Class::Manual::Component/USING>.
98
99 =cut
100
101 __PACKAGE__->load_components(qw/InflateColumn/);
102
103 __PACKAGE__->mk_group_accessors('simple' => '__datetime_parser');
104
105 =head2 register_column
106
107 Chains with the L<DBIx::Class::Row/register_column> method, and sets
108 up datetime columns appropriately.  This would not normally be
109 directly called by end users.
110
111 In the case of an invalid date, L<DateTime> will throw an exception.  To
112 bypass these exceptions and just have the inflation return undef, use
113 the C<datetime_undef_if_invalid> option in the column info:
114   
115     "broken_date",
116     {
117         data_type => "datetime",
118         default_value => '0000-00-00',
119         is_nullable => 1,
120         datetime_undef_if_invalid => 1
121     }
122
123 =cut
124
125 sub register_column {
126   my ($self, $column, $info, @rest) = @_;
127   $self->next::method($column, $info, @rest);
128   return unless defined($info->{data_type});
129
130   my $type;
131
132   for (qw/date datetime/) {
133     my $key = "inflate_${_}";
134
135     next unless exists $info->{$key};
136     return unless $info->{$key};
137
138     $type = $_;
139     last;
140   }
141
142   unless ($type) {
143     $type = lc($info->{data_type});
144     $type = 'datetime' if ($type =~ /^timestamp/);
145   }
146
147   my $timezone;
148   if ( exists $info->{extra} and exists $info->{extra}{timezone} and defined $info->{extra}{timezone} ) {
149     $timezone = $info->{extra}{timezone};
150   }
151
152   my $floating_tz_ok   = $info->{extra}{floating_tz_ok} ? 1 : 0;
153   my $undef_if_invalid = $info->{datetime_undef_if_invalid};
154
155   if ($type eq 'datetime' || $type eq 'date') {
156     my ($parse, $format) = ("parse_${type}", "format_${type}");
157     $self->inflate_column(
158       $column =>
159         {
160           inflate => sub {
161             my ($value, $obj) = @_;
162             my $dt = eval { $obj->_datetime_parser->$parse($value); };
163             die "Error while inflating ${value} for ${column} on ${self}: $@"
164               if $@ and not $undef_if_invalid;
165             $dt->set_time_zone($timezone) if $timezone;
166             return $dt;
167           },
168           deflate => sub {
169             my ($value, $obj) = @_;
170             if ($timezone) {
171                 warn "You're using a floating timezone, please see the documentation of"
172                   . " DBIx::Class::InflateColumn::DateTime for an explanation"
173                   if ref( $value->time_zone ) eq 'DateTime::TimeZone::Floating'
174                       and not $floating_tz_ok
175                       and not $ENV{DBIC_FLOATING_TZ_OK};
176                 $value->set_time_zone($timezone);
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 SEE ALSO
198
199 =over 4
200
201 =item More information about the add_columns method, and column metadata, 
202       can be found in the documentation for L<DBIx::Class::ResultSource>.
203
204 =back
205
206 =head1 AUTHOR
207
208 Matt S. Trout <mst@shadowcatsystems.co.uk>
209
210 =head1 CONTRIBUTORS
211
212 Aran Deltac <bluefeet@cpan.org>
213
214 =head1 LICENSE
215
216 You may distribute this code under the same terms as Perl itself.
217