blib/lib/DateTime/Format/Pg.pm

filter: Statementstmt 88.2% 173 / 196 Branchbran 74.4% 67 / 90 Conditioncond 65.7% 25 / 38 MC/DCmcdc 38.8% 7 / 18 Subroutinesub 83.8% 26 / 31 Podpod 100% 13 / 13 totaltotal 80.5% 311 / 386 CC 62 SCAR 21.5
CC
62
Cov
82%
_fix_timezone
20.7
server_tz
20.0
parse_duration
10.0
CRAP 8.6
↑ Summary
1 package DateTime::Format::Pg;
2  
3 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use vars qw ($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 23 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use DateTime 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use DateTime::Duration;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use DateTime::Format::Builder 0.72;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 23 ▶use DateTime::TimeZone 0.06;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 23 ▶use DateTime::TimeZone::UTC;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 23 ▶use DateTime::TimeZone::Floating;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 23 $VERSION = '0.16014';
15 23 $VERSION = eval $VERSION;
16  
17 23 our @ISA = ('DateTime::Format::Builder');
18  
19 =head1 NAME
20  
21 DateTime::Format::Pg - Parse and format PostgreSQL dates and times
22  
23 =head1 SYNOPSIS
24  
25 use DateTime::Format::Pg;
26  
27 my $dt = DateTime::Format::Pg->parse_datetime( '2003-01-16 23:12:01' );
28  
29 # 2003-01-16 23:12:01
30 DateTime::Format::Pg->format_datetime($dt);
31  
32 =head1 DESCRIPTION
33  
34 This module understands the formats used by PostgreSQL for its DATE, TIME,
35 TIMESTAMP, and INTERVAL data types. It can be used to parse these formats in
36 order to create C<DateTime> or C<DateTime::Duration> objects, and it can take a
37 C<DateTime> or C<DateTime::Duration> object and produce a string representing
38 it in a format accepted by PostgreSQL.
39  
40 =head1 CONSTRUCTORS
41  
42 The following methods can be used to create C<DateTime::Format::Pg> objects.
43  
44 =over 4
45  
46 =item * new( name => value, ... )
47  
48 Creates a new C<DateTime::Format::Pg> instance. This is generally not
49 required for simple operations. If you wish to use a different parsing
50 style from the default then it is more comfortable to create an object.
51  
52 my $parser = DateTime::Format::Pg->new()
53 my $copy = $parser->new( 'european' => 1 );
54  
55 This method accepts the following options:
56  
57 =over 8
58  
59 =item * european
60  
61 If european is set to non-zero, dates are assumed to be in european
62 dd/mm/yyyy format. The default is to assume US mm/dd/yyyy format
63 (because this is the default for PostgreSQL).
64  
65 This option only has an effect if PostgreSQL is set to output dates in
66 the 'PostgreSQL' (DATE only) and 'SQL' (DATE and TIMESTAMP) styles.
67  
68 Note that you don't have to set this option if the PostgreSQL server has
69 been set to use the 'ISO' format, which is the default.
70  
71 =item * server_tz
72  
73 This option can be set to a C<DateTime::TimeZone> object or a string
74 that contains a time zone name.
75  
76 This value must be set to the same value as the PostgreSQL server's time
77 zone in order to parse TIMESTAMP WITH TIMEZONE values in the
78 'PostgreSQL', 'SQL', and 'German' formats correctly.
79  
80 Note that you don't have to set this option if the PostgreSQL server has
81 been set to use the 'ISO' format, which is the default.
82  
83 =back
84  
85 =cut
86  
87 sub _add_param
88 2 ▶{
Subroutine _add_param: called CC=4 SCAR=17.9
89 2 my ($to,%param) = @_;
90 2 foreach(keys %param)
91 {
92 2 ▶ if($_ eq 'european') {
Branch: 2 branches
BranchTrueFalseTotal
if ($_ eq 'european') { } 2 0 2
elsif ($_ eq 'server_tz') { } 0 0 0
93 2 $$to{'_european'} = $param{$_};
94 } elsif($_ eq 'server_tz') {
95 0 $$to{'_server_tz'} = $param{$_};
96 } else {
97 0 croak("Unknown option $_." );
98 }
99 }
100 }
101  
102 14 ▶sub european {
Subroutine european: called CC=3 SCAR=11.1
Pod documented
103 14 my ($self,%param) = @_;
104 14 ▶ return $param{'european'} if exists $param{'european'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $param{"european"} 12 2 14
105 2 ▶ return $self->{'_european'} if ref $self;
Branch: 1 branch
BranchTrueFalseTotal
if ref $self 2 0 2
106 }
107  
108 0 ▶sub server_tz {
Subroutine server_tz: not called CC=4 SCAR=30.0
Pod documented
109 0 my ($self,%param) = @_;
110 0 ▶ return $param{''} if (ref($param{'server_tz'})) =~ /TimeZone/;
Branch: 1 branch
BranchTrueFalseTotal
if ref($param{"server_tz"}) =~ /TimeZone/ 0 0 0
111 0 ▶ return DateTime::TimeZone->new('name' => $param{''}) if exists $param{'server_tz'};
Branch: 1 branch
BranchTrueFalseTotal
if exists $param{"server_tz"} 0 0 0
112 0 ▶ return ((ref $self) && $self->{'_server_tz'});
Condition0%0/3
ref $self && $self->{'_server_tz'}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $self && $self->{'_server_tz'}
ref $self $self->{'_server_tz'}
Truth table0%0/3
A && B
A= ref $selfB= $self->{'_server_tz'}
ABresult
0X0
100
111
113 }
114  
115 sub new
116 2 ▶{
Subroutine new: called CC=3 SCAR=12.3
Pod documented
117 2 my $class = shift;
118 2 ▶ my $self = bless {}, ref($class)||$class;
Condition33%1/3
ref $class || $class
l!l&&r!l&&!r
020
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table33%1/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
119 2 ▶ if (ref $class)
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class) 0 2 2
120 {
121 0 $self->{'_european'} = ( scalar $class->{'_european'} );
122 }
123 2 _add_param($self,@_);
124 2 return $self;
125 }
126  
127 =item * clone()
128  
129 This method is provided for those who prefer to explicitly clone via a
130 method called C<clone()>.
131  
132 my $clone = $original->clone();
133  
134 If called as a class method it will die.
135  
136 =back
137  
138 =cut
139  
140 sub clone
141 0 ▶{
Subroutine clone: not called CC=2 SCAR=17.9
Pod documented
142 0 my $self = shift;
143 0 ▶ croak('Calling object method as class method!') unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 0 0
144 0 return $self->new();
145 }
146  
147 sub _create_infinity
148 6 ▶{
Subroutine _create_infinity: called CC=2 SCAR=6.9
149 6 my $self = shift;
150 6 my %p = @_;
151  
152 6 ▶ if ($p{sign}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p{'sign'}) { } 3 3 6
153 3 return DateTime::Infinite::Past->new;
154 } else {
155 3 return DateTime::Infinite::Future->new;
156 }
157 }
158  
159 # infinite datetimes
160 23 my $pg_infinity =
161 {
162 regex => qr/^(-)?infinity$/,
163 params => [ qw(sign) ],
164 constructor => \&_create_infinity,
165 };
166  
167 # Dates (without time zone)
168 #
169 # see EncodeDateOnly() in
170 # pgsql-server/src/backend/utils/adt/datetime.c
171 #
172 # 2003-04-18 (USE_ISO_DATES)
173 #
174 23 my $pg_dateonly_iso =
175 {
176 regex => qr/^(\d{4,})-(\d{2,})-(\d{2,})( BC)?$/,
177 params => [ qw( year month day era ) ],
178 postprocess => \&_fix_era,
179 };
180  
181 # 18/04/2003 (USE_SQL_DATES, EuroDates)
182 # 18-04-2003 (USE_POSTGRES_DATES, EuroDates)
183 # 04/18/2003 (USE_SQL_DATES, !EuroDates)
184 # 04-18-2003 (USE_POSTGRES_DATES, !EuroDates)
185 #
186 23 my $pg_dateonly_sql =
187 {
188 regex => qr/^(\d{2,})[\/-](\d{2,})[\/-](\d{4,})( BC)?$/,
189 params => [ qw( month day year era) ],
190 postprocess => [ \&_fix_era, \&_fix_eu ],
191 };
192  
193 # 18.04.2003 (USE_GERMAN_DATES)
194 #
195 23 my $pg_dateonly_german =
196 {
197 regex => qr/^(\d{2,})\.(\d{2,})\.(\d{4,})( BC)?$/,
198 params => [ qw( day month year era ) ],
199 postprocess => \&_fix_era
200 };
201  
202 # Times (with/without time zone)
203 #
204 # see EncodeTimeOnly() in
205 # pgsql-server/src/backend/utils/adt/datetime.c
206 #
207 # 17:20:24.373942+02
208 # (NB: always uses numerical tz)
209 #
210 23 my $pg_timeonly =
211 {
212 regex => qr/^T?(\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? *([-\+][\d:]+)?$/,
213 params => [ qw( hour minute second nanosecond time_zone) ],
214 extra => { year => '1970' },
215 postprocess => [ \&_fix_timezone, \&_fix_nanosecond ],
216 };
217  
218 # Timestamps (with/without time zone)
219 #
220 # see EncodeDateTime() in
221 # pgsql-server/src/backend/utils/adt/datetime.c
222 #
223 # 2003-04-18 17:20:24.373942+02 (USE_ISO_DATES)
224 # (NB: always uses numerical tz)
225 23 my $pg_datetime_iso =
226 {
227 regex =>
228 qr/^
229 (\d{4,})-(\d{2,})-(\d{2,}) # date part
230 [ T] # separator
231 (\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? # time part
232 [ ]*
233 ([-\+][\d:]+)? # numerical timezone
234 ([ ]BC)?
235 $/x,
236 params => [ qw( year month day hour minute second nanosecond time_zone era) ],
237 postprocess => [ \&_fix_era, \&_fix_timezone, \&_fix_nanosecond ],
238 };
239  
240 # * Added for https://github.com/lestrrat-p5/DateTime-Format-Pg/issues/18
241 # Concatenated dates/times are accepted
242 # e.g. YYYYMMDDTHHMMSS
243 23 my $pg_datetime_iso_concat_date =
244 {
245 regex =>
246 qr/^
247 (\d{4})(\d{2})(\d{2}) # concatenated date
248 [ T] # separator
249 (\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? # time part
250 [ ]*
251 ([-\+][\d:]+)? # numerical timezone
252 ([ ]BC)?
253 $/x,
254 params => [ qw( year month day hour minute second nanosecond time_zone era) ],
255 postprocess => [ \&_fix_era, \&_fix_timezone, \&_fix_nanosecond ],
256 };
257  
258 # Fri 18 Apr 17:20:24.373942 2003 CEST (USE_POSTGRES_DATES, EuroDates)
259 #
260 23 my $pg_datetime_pg_eu =
261 {
262 regex => qr/^\S{3,} (\d{2,}) (\S{3,}) (\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? (\d{4,}) *((?:[-\+][\d:]+)|(?:\S+))?( BC)?$/,
263 params => [ qw( day month hour minute second nanosecond year time_zone era ) ],
264 postprocess => [ \&_fix_era, \&_fix_timezone, \&_fix_nanosecond ],
265 };
266  
267 # Fri Apr 18 17:20:24.373942 2003 CEST (USE_POSTGRES_DATES, !EuroDates)
268 #
269 23 my $pg_datetime_pg_us =
270 {
271 regex => qr/^\S{3,} (\S{3,}) (\s{2,}) (\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? (\d{4,}) *((?:[-\+][\d:]+)|(?:\S+))?( BC)?$/,
272 params => [ qw( month day hour minute second nanosecond year time_zone era ) ],
273 postprocess => [ \&_fix_era, \&_fix_month_names, \&_fix_timezone, \&_fix_nanosecond ],
274 };
275  
276 # 18/04/2003 17:20:24.373942 CEST (USE_SQL_DATES, EuroDates)
277 # 04/18/2003 17:20:24.373942 CEST (USE_SQL_DATES, !EuroDates)
278 #
279 23 my $pg_datetime_sql =
280 {
281 regex => qr/^(\d{2,})\/(\d{2,})\/(\d{4,}) (\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? *((?:[-\+][\d:]+)|(?:\S+))?( BC)?$/,
282 params => [ qw( month day year hour minute second nanosecond time_zone era ) ],
283 postprocess => [ \&_fix_era, \&_fix_eu, \&_fix_timezone, \&_fix_nanosecond ],
284 };
285  
286 # 18.04.2003 17:20:24.373942 CEST (USE_GERMAN_DATES)
287 #
288 23 my $pg_datetime_german =
289 {
290 regex => qr/^(\d{2,})\.(\d{2,})\.(\d{4,}) (\d{2,}):(\d{2,}):(\d{2,})(\.\d+)? *((?:[-\+][\d:]+)|(?:\S+))?( BC)?$/,
291 params => [ qw( day month year hour minute second nanosecond time_zone era ) ],
292 postprocess => [ \&_fix_era, \&_fix_timezone, \&_fix_nanosecond ],
293 };
294  
295 # Helper functions
296 #
297 # Fix BC dates (1 BC => year 0, 2 BC => year -1)
298 #
299 39 ▶sub _fix_era {
Subroutine _fix_era: called CC=3 SCAR=11.0
300 39 my %args = @_;
301 39 ▶ my $era = (delete $args{'parsed'}->{'era'}) || '';
Condition100%2/2
delete $args{'parsed'}{'era'} || ''
l!l
732
MC/DC100%1/1
delete $args{'parsed'}{'era'} || ''
delete $args{'parsed'}{'era'}
Truth table100%2/2
A
A= delete $args{'parsed'}{'era'}
Aresult
11
00
302 39 ▶ if ($era =~ m/BC/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($era =~ /BC/) 7 32 39
303 7 $args{'parsed'}->{'year'} = 1-$args{'parsed'}->{'year'}
304 }
305 39 return 1;
306 }
307  
308 # Fix European dates (swap month and day)
309 #
310 14 ▶sub _fix_eu {
Subroutine _fix_eu: called CC=2 SCAR=6.9
311 14 my %args = @_;
312 14 ▶ if($args{'self'}->european(@{$args{'args'}}) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"self"}->european(@{$args{"args"};})) 7 7 14
313 7 my $save = $args{'parsed'}->{'month'};
314 7 $args{'parsed'}->{'month'} = $args{'parsed'}->{'day'};
315 7 $args{'parsed'}->{'day'} = $save;
316 }
317 14 return 1;
318 }
319  
320 # Fix month names (name => numeric)
321 #
322 23 my %months = (
323 'jan' => 1, 'feb' => 2, 'mar' => 3, 'apr' => 4,
324 'may' => 5, 'jun' => 6, 'jul' => 7, 'aug' => 8,
325 'sep' => 9, 'oct' =>10, 'nov' =>11, 'dec' =>12, );
326  
327 0 ▶sub _fix_month_names {
Subroutine _fix_month_names: not called CC=2 SCAR=17.9
328 0 my %args = @_;
329 0 $args{'parsed'}->{'month'} = $months{lc( $args{'parsed'}->{'month'} )};
330 0 ▶ return $args{'parsed'}->{'month'} ? 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
$args{'parsed'}{'month'} ? : 0 0 0
331 }
332  
333 # Fix time zones
334 #
335 22 ▶sub _fix_timezone {
Subroutine _fix_timezone: called CC=18 SCAR=30.3
336 22 my %args = @_;
337 22 ▶ my %param = $args{'args'} ? (@{$args{'args'}}) : ();
Branch: 1 branch
BranchTrueFalseTotal
$args{'args'} ? : 2 20 22
338
339 22 ▶ if($param{'_force_tz'}) {
Branch: 3 branches
BranchTrueFalseTotal
if ($param{'_force_tz'}) { } 2 20 22
elsif (not defined $args{'parsed'}{'time_zone'}) { } 6 14 20
elsif ($args{'parsed'}{'time_zone'} =~ /^([-\+])(\d+)(?::(\d+))?(?::(\d+))?$/) { } 14 0 14
340 2 $args{'parsed'}->{'time_zone'} = $param{'_force_tz'};
341 }
342  
343 elsif(!defined($args{'parsed'}->{'time_zone'})) {
344 # For very early and late dates, PostgreSQL always returns times in
345 # UTC and does not tell us that it did so.
346 #
347 6 ▶ if ( $args{'parsed'}->{'year'} < 1901
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'parsed'}{'year'} < 1901 or $args{'parsed'}{'year'} == 1901 and $args{'parsed'}{'month'} < 12 || $args{'parsed'}{'day'} < 14 or $args{'parsed'}{'year'} > 2038 or $args{'parsed'}{'year'} == 2038 and $args{'parsed'}{'month'} > 1 || $args{'parsed'}{'day'} > 18) { } 2 4 6
Condition80%17/21
$args{"parsed"}{"year"} < 1901 or $args{"parsed"}{"year"} == 1901 and $args{"parsed"}{"month"} < 12 || $args{"parsed"}{"day"} < 14 or $args{"parsed"}{"year"} > 2038 or $args{"parsed"}{"year"} == 2038 and $args{"parsed"}{"month"} > 1 || $args{"parsed"}{"day"} > 18
l!l&&r!l&&!r
114
$args{"parsed"}{"year"} < 1901 or $args{"parsed"}{"year"} == 1901 and $args{"parsed"}{"month"} < 12 || $args{"parsed"}{"day"} < 14 or $args{"parsed"}{"year"} > 2038
l!l&&r!l&&!r
105
$args{"parsed"}{"year"} < 1901 or $args{"parsed"}{"year"} == 1901 and $args{"parsed"}{"month"} < 12 || $args{"parsed"}{"day"} < 14
l!l&&r!l&&!r
015
$args{"parsed"}{"year"} == 1901 and $args{"parsed"}{"month"} < 12 || $args{"parsed"}{"day"} < 14
!ll&&!rl&&r
411
$args{"parsed"}{"month"} < 12 or $args{"parsed"}{"day"} < 14
l!l&&r!l&&!r
011
$args{"parsed"}{"year"} == 2038 and $args{"parsed"}{"month"} > 1 || $args{"parsed"}{"day"} > 18
!ll&&!rl&&r
311
$args{"parsed"}{"month"} > 1 or $args{"parsed"}{"day"} > 18
l!l&&r!l&&!r
011
MC/DC50%4/8
$args{"parsed"}{"year"} < 1901 or $args{"parsed"}{"year"} == 1901 and $args{"parsed"}{"month"} < 12 || $args{"parsed"}{"day"} < 14 or $args{"parsed"}{"year"} > 2038 or $args{"parsed"}{"year"} == 2038 and $args{"parsed"}{"month"} > 1 || $args{"parsed"}{"day"} > 18
$args{"parsed"}{"year"} < 1901 $args{"parsed"}{"year"} == 1901 $args{"parsed"}{"month"} < 12 $args{"parsed"}{"day"} < 14 $args{"parsed"}{"year"} > 2038 $args{"parsed"}{"year"} == 2038 $args{"parsed"}{"month"} > 1 $args{"parsed"}{"day"} > 18
Truth table38%5/13
A or B and C or D or E or F and G or H
A= $args{"parsed"}{"year"} < 1901B= $args{"parsed"}{"year"} == 1901C= $args{"parsed"}{"month"} < 12D= $args{"parsed"}{"day"} < 14E= $args{"parsed"}{"year"} > 2038F= $args{"parsed"}{"year"} == 2038G= $args{"parsed"}{"month"} > 1H= $args{"parsed"}{"day"} > 18
ABCDEFGHresult
1XXXXXXX1
011XXXXX1
0101XXXX1
00XX1XXX1
01001XXX1
00XX011X1
00XX01011
0100011X1
010001011
00XX00XX0
00XX01000
010000XX0
010001000
348 || ( $args{'parsed'}->{'year'} == 1901 && ($args{'parsed'}->{'month'} < 12 || $args{'parsed'}->{'day'} < 14) )
349 || $args{'parsed'}->{'year'} > 2038
350 || ( $args{'parsed'}->{'year'} == 2038 && ($args{'parsed'}->{'month'} > 01 || $args{'parsed'}->{'day'} > 18) )
351 ) {
352 2 $args{'parsed'}->{'time_zone'} = DateTime::TimeZone::UTC->new();
353 }
354  
355 # DT->new() does not like undef time_zone params, which are generated
356 # by the regexps
357 #
358 else {
359 4 delete $args{'parsed'}->{'time_zone'};
360 }
361 }
362  
363 # Numerical time zone
364 #
365
366 elsif($args{'parsed'}->{'time_zone'} =~ m/^([-\+])(\d+)(?::(\d+))?(?::(\d+))?$/) {
367 14 my $tz;
368 14 ▶ if (length($2) == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $2 == 2) { } 10 4 14
369 # regular hour notation
370 10 ▶ my ($min, $sec) = ($3 || '00', $4 || '00');
Condition100%4/4
$3 || '00'
l!l
64
$4 || '00'
l!l
28
MC/DC100%1/1
$3 || '00'
$3
MC/DC100%1/1
$4 || '00'
$4
Truth table100%2/2
A
A= $3
Aresult
11
00
Truth table100%2/2
A
A= $4
Aresult
11
00
371 10 $tz = sprintf "%s%02d:%02d:%02d", $1, $2, $min, $sec;
372 } else {
373 4 $tz = "$1$2";
374 }
375 14 $args{'parsed'}->{'time_zone'} = $tz;
376 }
377
378 # Non-numerical time zone returned, which can be ambiguous :(
379 #
380 else
381 {
382 # XXX This barfs because 'self' may not necessarily be initialized
383 # Need to fix it
384 0 ▶ my $stz = $args{'self'}->server_tz($args{'args'} ? @{$args{'args'}} : ());
Branch: 1 branch
BranchTrueFalseTotal
$args{'args'} ? : 0 0 0
385 0 ▶ $args{'parsed'}->{'time_zone'} = $stz || 'floating';
Condition0%0/2
$stz || 'floating'
l!l
00
MC/DC0%0/1
$stz || 'floating'
$stz
Truth table0%0/2
A
A= $stz
Aresult
11
00
386 }
387  
388 22 return 1;
389 }
390  
391 # Fix fractional seconds
392 #
393 22 ▶sub _fix_nanosecond {
Subroutine _fix_nanosecond: called CC=2 SCAR=6.9
394 22 my %args = @_;
395 22 ▶ if(defined $args{'parsed'}->{'nanosecond'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'parsed'}{'nanosecond'}) { } 8 14 22
396 8 $args{'parsed'}->{'nanosecond'} = sprintf '%.0f', $args{'parsed'}->{'nanosecond'} * 1.0E9;
397 } else {
398 14 delete $args{'parsed'}->{'nanosecond'}
399 };
400 22 return 1;
401 }
402  
403 # Parser generation
404 #
405 23 DateTime::Format::Builder->create_class(
406 parsers => {
407 parse_date => [
408 $pg_dateonly_iso,
409 $pg_dateonly_sql,
410 $pg_dateonly_german,
411 $pg_infinity,
412 ],
413 parse_timetz => [
414 $pg_timeonly,
415 ],
416 parse_timestamptz => [
417 $pg_datetime_iso,
418 $pg_datetime_iso_concat_date,
419 $pg_datetime_pg_eu,
420 $pg_datetime_pg_us,
421 $pg_datetime_sql,
422 $pg_datetime_german,
423 $pg_infinity,
424 ],
425 parse_datetime => [
426 $pg_datetime_iso,
427 $pg_datetime_iso_concat_date,
428 $pg_datetime_pg_eu,
429 $pg_datetime_pg_us,
430 $pg_datetime_sql,
431 $pg_datetime_german,
432 $pg_dateonly_iso,
433 $pg_dateonly_german,
434 $pg_dateonly_sql,
435 $pg_timeonly,
436 $pg_infinity,
437 ],
438 }
439 );
440  
441 =head1 METHODS
442  
443 This class provides the following methods. The parse_datetime, parse_duration,
444 format_datetime, and format_duration methods are general-purpose methods
445 provided for compatibility with other C<DateTime::Format> modules.
446  
447 The other methods are specific to the corresponding PostgreSQL date/time data
448 types. The names of these methods are derived from the name of the PostgreSQL
449 data type. (Note: Prior to PostgreSQL 7.3, the TIMESTAMP type was equivalent
450 to the TIMESTAMP WITH TIME ZONE type. This data type corresponds to the
451 format/parse_timestamp_with_time_zone method but not to the
452 format/parse_timestamp method.)
453  
454 =head2 PARSING METHODS
455  
456 This class provides the following parsing methods.
457  
458 As a general rule, the parsing methods accept input in any format that the
459 PostgreSQL server can produce. However, if PostgreSQL's DateStyle is set to
460 'SQL' or 'PostgreSQL', dates can only be parsed correctly if the 'european'
461 option is set correctly (i.e. same as the PostgreSQL server). The same is true
462 for time zones and the 'australian_timezones' option in all modes but 'ISO'.
463  
464 The default DateStyle, 'ISO', will always produce unambiguous results
465 and is also parsed most efficiently by this parser class. I strongly
466 recommend using this setting unless you have a good reason not to.
467  
468 =over 4
469  
470 =item * parse_datetime($string,...)
471  
472 Given a string containing a date and/or time representation, this method
473 will return a new C<DateTime> object.
474  
475 If the input string does not contain a date, it is set to 1970-01-01.
476 If the input string does not contain a time, it is set to 00:00:00.
477 If the input string does not contain a time zone, it is set to the
478 floating time zone.
479  
480 If given an improperly formatted string, this method may die.
481  
482 =cut
483  
484 # sub parse_datetime {
485 # *** created automatically ***
486 # }
487  
488 =item * parse_timestamptz($string,...)
489  
490 =item * parse_timestamp_with_time_zone($string,...)
491  
492 Given a string containing a timestamp (date and time) representation,
493 this method will return a new C<DateTime> object. This method is
494 suitable for the TIMESTAMPTZ (or TIMESTAMP WITH TIME ZONE) type.
495  
496 If the input string does not contain a time zone, it is set to the
497 floating time zone.
498  
499 Please note that PostgreSQL does not actually store a time zone along
500 with the TIMESTAMP WITH TIME ZONE (or TIMESTAMPTZ) type but will just
501 return a time stamp converted for the server's local time zone.
502  
503 If given an improperly formatted string, this method may die.
504  
505 =cut
506  
507 # sub parse_timestamptz {
508 # *** created automatically ***
509 # }
510  
511 23 *parse_timestamp_with_time_zone = \&parse_timestamptz;
512  
513 =item * parse_timestamp($string,...)
514  
515 =item * parse_timestamp_without_time_zone($string,...)
516  
517 Similar to the functions above, but always returns a C<DateTime> object
518 with a floating time zone. This method is suitable for the TIMESTAMP (or
519 TIMESTAMP WITHOUT TIME ZONE) type.
520  
521 If the server does return a time zone, it is ignored.
522  
523 If given an improperly formatted string, this method may die.
524  
525 =cut
526  
527 2 ▶sub parse_timestamp {
Subroutine parse_timestamp: called CC=1 SCAR=0.0
Pod documented
528 2 parse_timestamptz(@_,'_force_tz' => DateTime::TimeZone::Floating->new());
529 }
530  
531 23 *parse_timestamp_without_time_zone = \&parse_timestamp;
532  
533 =item * parse_timetz($string,...)
534  
535 =item * parse_time_with_time_zone($string,...)
536  
537 Given a string containing a time representation, this method will return
538 a new C<DateTime> object. The date is set to 1970-01-01. This method is
539 suitable for the TIMETZ (or TIME WITH TIME ZONE) type.
540  
541 If the input string does not contain a time zone, it is set to the
542 floating time zone.
543  
544 Please note that PostgreSQL stores a numerical offset with its TIME WITH
545 TIME ZONE (or TIMETZ) type. It does not store a time zone name (such as
546 'Europe/Rome').
547  
548 If given an improperly formatted string, this method may die.
549  
550 =cut
551  
552 # sub parse_timetz {
553 # *** created automatically ***
554 # }
555  
556 23 *parse_time_with_time_zone = \&parse_timetz;
557  
558 =item * parse_time($string,...)
559  
560 =item * parse_time_without_time_zone($string,...)
561  
562 Similar to the functions above, but always returns an C<DateTime> object
563 with a floating time zone. If the server returns a time zone, it is
564 ignored. This method is suitable for use with the TIME (or TIME WITHOUT
565 TIME ZONE) type.
566  
567 This ensures that the resulting C<DateTime> object will always have the
568 time zone expected by your application.
569  
570 If given an improperly formatted string, this method may die.
571  
572 =cut
573  
574 2 ▶sub parse_time {
Subroutine parse_time: called CC=1 SCAR=0.0
Pod documented
575 2 parse_timetz(@_,'_force_tz' => 'floating');
576 }
577  
578 23 *parse_time_without_time_zone = \&parse_time;
579  
580 =item * parse_date($string,...)
581  
582 Given a string containing a date representation, this method will return
583 a new C<DateTime> object. The time is set to 00:00:00 (floating time
584 zone). This method is suitable for the DATE type.
585  
586 If given an improperly formatted string, this method may die.
587  
588 =cut
589  
590 # sub parse_date {
591 # *** generated automatically ***
592 # }
593  
594 =item * parse_duration($string)
595  
596 =item * parse_interval($string)
597  
598 Given a string containing a duration (SQL type INTERVAL) representation,
599 this method will return a new C<DateTime::Duration> object.
600  
601 If given an improperly formatted string, this method may die.
602  
603 =cut
604  
605 89 ▶sub parse_duration {
Subroutine parse_duration: called CC=10 SCAR=23.0
Pod documented
606 89 my ($self, $string_to_parse) = @_;
607  
608 # NB: We can't just pass our values to new() because it treats all
609 # arguments as negative if we have a single negative component.
610 # PostgreSQL might return mixed signs, e.g. '1 mon -1day'.
611 89 my $du = DateTime::Duration->new;
612  
613 89 my %units = ( map(($_, ["seconds", 1]), qw(s second seconds sec secs)),
614 map(($_, ["minutes", 1]), qw(m minute minutes min mins)),
615 map(($_, ["hours", 1]), qw(h hr hour hours)),
616 map(($_, ["days", 1]), qw(d day days)),
617 map(($_, ["weeks", 1]), qw(w week weeks)),
618 map(($_, ["months", 1]), qw(M mon mons month months)),
619 map(($_, ["years", 1]), qw(y yr yrs year years)),
620 map(($_, ["years", 10]), qw(decade decades dec decs)),
621 map(($_, ["years", 100]), qw(c cent century centuries)),
622 map(($_, ["years", 1000]), qw(millennium millennia millenniums mil mils)) );
623  
624 89 (my $string = $string_to_parse) =~ s/^@\s*//;
625 89 $string =~ s/\+(\d+)/$1/g;
626  
627 # Method used later on duration object
628 89 my $arith_method = "add";
629 89 ▶ if ( $string =~ s/ago// ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($string =~ s/ago//) 8 81 89
630 8 $arith_method = "subtract";
631 }
632  
633 89 my $sign = 0;
634 89 my %done;
635  
636 89 $string =~ s/\b(\d+):(\d\d):(\d\d)(\.\d+)?\b/$1h $2m $3$4s/g;
637 89 $string =~ s/\b(\d+):(\d\d)\b/$1h $2m/g;
638 89 $string =~ s/(-\d+h)\s+(\d+m)\s+(\d+(?:\.\d+)?s)\s*/$1 -$2 -$3 /;
639 89 $string =~ s/(-\d+h)\s+(\d+m)\s*/$1 -$2 /;
640  
641 89 ▶ while ($string =~ s/^\s*(-?\d+(?:[.,]\d+)?)\s*([a-zA-Z]+)(?:\s*(?:,|and)\s*)*//i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($string =~ s/^\s*(-?\d+(?:[.,]\d+)?)\s*([a-zA-Z]+)(?:\s*(?:,|and)\s*)*//i) 174 87 261
642 174 my($amount, $unit) = ($1, $2);
643 174 ▶ if (length($unit) != 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $unit != 1) 98 76 174
644 98 $unit = lc($unit);
645 }
646  
647 174 my $udata = $units{$unit};
648 174 ▶ if (! $udata) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($udata) 1 173 174
649 1 Carp::croak("Unknown timespec: $string_to_parse");
650 }
651 173 my ($base_unit, $num) = @$udata;
652 173 my $key = $base_unit . "-" . $num;
653 173 ▶ if (exists $done{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $done{$key}) 1 172 173
654 1 Carp::croak("Unknown timespec: $string_to_parse");
655 }
656 172 $done{$key} = 1;
657  
658 172 my @extra_args;
659  
660 172 $amount =~ s/,/./;
661 172 ▶ if ($amount =~ s/\.(\d+)$//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($amount =~ s/\.(\d+)$//) 2 170 172
662 2 my $fractional = $1;
663 # We only handle fractional seconds right now. If you
664 # need support for silly formats (from my perspective ;-P)
665 # like '1.5 weeks', please provide me with a comprehensive
666 # test for all possible combinations of fractional times.
667 2 ▶ if ($base_unit ne "seconds") {
Branch: 1 branch
BranchTrueFalseTotal
if ($base_unit ne "seconds") 0 2 2
668 0 Carp::croak("Fractional input detected: currently only fractional seconds are supported")
669 }
670  
671 # From the spec, Pg can take up to 6 digits for fractional part
672 # that is microseconds. If we're missing 0's,
673 # we should pad them
674 2 $fractional .= '0'x (9 - length($fractional));
675 2 ▶ my $sign = ($amount > 0) ? 1 : -1;
Branch: 1 branch
BranchTrueFalseTotal
$amount > 0 ? : 1 1 2
676 2 push @extra_args, ("nanoseconds" => $sign * $fractional);
677 }
678  
679 172 $du->$arith_method($base_unit => $amount * $num, @extra_args);
680 }
681  
682 87 ▶ if ($string =~ /\S/) { # OK to have extra spaces, but nothing else
Branch: 1 branch
BranchTrueFalseTotal
if ($string =~ /\S/) 2 85 87
683 2 Carp::croak "Unknown timespec: $string_to_parse";
684 }
685  
686 85 return $du;
687 }
688  
689 23 *parse_interval = \&parse_duration;
690  
691 =back
692  
693 =head2 FORMATTING METHODS
694  
695 This class provides the following formatting methods.
696  
697 The output is always in the format mandated by the SQL standard (derived
698 from ISO 8601), which is parsed by PostgreSQL unambiguously in all
699 DateStyle modes.
700  
701 =over 4
702  
703 =item * format_datetime($datetime,...)
704  
705 Given a C<DateTime> object, this method returns a string appropriate as
706 input for all date and date/time types of PostgreSQL. It will contain
707 date and time.
708  
709 If the time zone of the C<DateTime> part is floating, the resulting
710 string will contain no time zone, which will result in the server's time
711 zone being used. Otherwise, the numerical offset of the time zone is
712 used.
713  
714 =cut
715  
716 23 *format_datetime = \&format_timestamptz;
717  
718 =item * format_time($datetime,...)
719  
720 =item * format_time_without_time_zone($datetime,...)
721  
722 Given a C<DateTime> object, this method returns a string appropriate as
723 input for the TIME type (also known as TIME WITHOUT TIME ZONE), which
724 will contain the local time of the C<DateTime> object and no time zone.
725  
726 =cut
727  
728 sub _format_fractional
729 11 ▶{
Subroutine _format_fractional: called CC=2 SCAR=6.9
730 11 my $ns = shift->nanosecond;
731 11 ▶ return $ns ? sprintf(".%09d", "$ns") : ''
Branch: 1 branch
BranchTrueFalseTotal
$ns ? : 3 8 11
732 }
733  
734 sub format_time
735 0 ▶{
Subroutine format_time: not called CC=1 SCAR=6.9
Pod documented
736 0 my ($self,$dt,%param) = @_;
737 0 return $dt->hms(':')._format_fractional($dt);
738 }
739  
740 23 *format_time_without_time_zone = \&format_time;
741  
742 =item * format_timetz($datetime)
743  
744 =item * format_time_with_time_zone($datetime)
745  
746 Given a C<DateTime> object, this method returns a string appropriate as
747 input for the TIME WITH TIME ZONE type (also known as TIMETZ), which
748 will contain the local part of the C<DateTime> object and a numerical
749 time zone.
750  
751 You should not use the TIME WITH TIME ZONE type to store dates with
752 floating time zones. If the time zone of the C<DateTime> part is
753 floating, the resulting string will contain no time zone, which will
754 result in the server's time zone being used.
755  
756 =cut
757  
758 sub _format_time_zone
759 11 ▶{
Subroutine _format_time_zone: called CC=2 SCAR=6.9
760 11 my $dt = shift;
761 11 ▶ return '' if $dt->time_zone->is_floating;
Branch: 1 branch
BranchTrueFalseTotal
if $dt->time_zone->is_floating 1 10 11
762 10 return &DateTime::TimeZone::offset_as_string($dt->offset);
763 }
764  
765 sub format_timetz
766 0 ▶{
Subroutine format_timetz: not called CC=1 SCAR=6.9
Pod documented
767 0 my ($self,$dt) = @_;
768 0 return $dt->hms(':')._format_fractional($dt)._format_time_zone($dt);
769 }
770  
771 23 *format_time_with_time_zone = \&format_timetz;
772  
773 =item * format_date($datetime)
774  
775 Given a C<DateTime> object, this method returns a string appropriate as
776 input for the DATE type, which will contain the date part of the
777 C<DateTime> object.
778  
779 =cut
780  
781 sub format_date
782 5 ▶{
Subroutine format_date: called CC=4 SCAR=13.9
Pod documented
783 5 my ($self,$dt) = @_;
784 5 ▶ if($dt->is_infinite) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dt->is_infinite) { } 2 3 5
elsif ($dt->year <= 0) { } 1 2 3
785 2 ▶ return $dt->isa('DateTime::Infinite::Future') ? 'infinity' : '-infinity';
Branch: 1 branch
BranchTrueFalseTotal
$dt->isa('DateTime::Infinite::Future') ? : 1 1 2
786 } elsif($dt->year()<=0) {
787 1 return sprintf('%04d-%02d-%02d BC',
788 1-$dt->year(),
789 $dt->month(),
790 $dt->day());
791 } else {
792 2 return $dt->ymd('-');
793 }
794 }
795  
796 =item * format_timestamp($datetime)
797  
798 =item * format_timestamp_without_time_zone($datetime)
799  
800 Given a C<DateTime> object, this method returns a string appropriate as
801 input for the TIMESTAMP type (also known as TIMESTAMP WITHOUT TIME
802 ZONE), which will contain the local time of the C<DateTime> object and
803 no time zone.
804  
805 =cut
806  
807 sub format_timestamp
808 2 ▶{
Subroutine format_timestamp: called CC=4 SCAR=17.1
Pod documented
809 2 my ($self,$dt,%param) = @_;
810 2 ▶ if($dt->is_infinite) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dt->is_infinite) { } 2 0 2
elsif ($dt->year <= 0) { } 0 0 0
811 2 ▶ return $dt->isa('DateTime::Infinite::Future') ? 'infinity' : '-infinity';
Branch: 1 branch
BranchTrueFalseTotal
$dt->isa('DateTime::Infinite::Future') ? : 1 1 2
812 } elsif($dt->year()<=0) {
813 0 return sprintf('%04d-%02d-%02d %s BC',
814 1-$dt->year(),
815 $dt->month(),
816 $dt->day(),
817 $dt->hms(':')._format_fractional($dt));
818 } else {
819 0 return $dt->ymd('-').' '.$dt->hms(':')._format_fractional($dt);
820 }
821 }
822  
823 23 *format_timestamp_without_time_zone = \&format_timestamp;
824  
825 =item * format_timestamptz($datetime)
826  
827 =item * format_timestamp_with_time_zone($datetime)
828  
829 Given a C<DateTime> object, this method returns a string appropriate as
830 input for the TIMESTAMP WITH TIME ZONE type, which will contain the
831 local part of the C<DateTime> object and a numerical time zone.
832  
833 You should not use the TIMESTAMP WITH TIME ZONE type to store dates with
834 floating time zones. If the time zone of the C<DateTime> part is
835 floating, the resulting string will contain no time zone, which will
836 result in the server's time zone being used.
837  
838 =cut
839  
840 sub format_timestamptz
841 13 ▶{
Subroutine format_timestamptz: called CC=4 SCAR=13.9
Pod documented
842 13 my ($self,$dt,%param) = @_;
843 13 ▶ if($dt->is_infinite) {
Branch: 2 branches
BranchTrueFalseTotal
if ($dt->is_infinite) { } 2 11 13
elsif ($dt->year <= 0) { } 2 9 11
844 2 ▶ return $dt->isa('DateTime::Infinite::Future') ? 'infinity' : '-infinity';
Branch: 1 branch
BranchTrueFalseTotal
$dt->isa('DateTime::Infinite::Future') ? : 1 1 2
845 } elsif($dt->year()<=0) {
846 2 return sprintf('%04d-%02d-%02d',
847 1-$dt->year(),
848 $dt->month(),
849 $dt->day()).
850 ' '.
851 $dt->hms(':').
852 _format_fractional($dt).
853 _format_time_zone($dt).
854 ' BC';
855 } else {
856 9 return $dt->ymd('-').' '.$dt->hms(':').
857 _format_fractional($dt).
858 _format_time_zone($dt);
859 }
860 }
861  
862 23 *format_timestamp_with_time_zone = \&format_timestamptz;
863  
864 =item * format_duration($du)
865  
866 =item * format_interval($du)
867  
868 Given a C<DateTime::Duration> object, this method returns a string appropriate
869 as input for the INTERVAL type.
870  
871 =cut
872  
873 5 ▶sub format_duration {
Subroutine format_duration: called CC=8 SCAR=21.5
Pod documented
874 5 ▶ shift if UNIVERSAL::isa($_[0], __PACKAGE__) || $_[0] eq __PACKAGE__;
Branch: 1 branch
BranchTrueFalseTotal
if UNIVERSAL::isa($_[0], __PACKAGE__) or $_[0] eq __PACKAGE__ 5 0 5
Condition33%1/3
UNIVERSAL::isa($_[0], __PACKAGE__) or $_[0] eq __PACKAGE__
l!l&&r!l&&!r
500
MC/DC0%0/2
UNIVERSAL::isa($_[0], __PACKAGE__) or $_[0] eq __PACKAGE__
UNIVERSAL::isa($_[0], __PACKAGE__) $_[0] eq __PACKAGE__
Truth table33%1/3
A or B
A= UNIVERSAL::isa($_[0], __PACKAGE__)B= $_[0] eq __PACKAGE__
ABresult
1X1
011
000
875 5 my($du,%param) = @_;
876 5 ▶ croak 'DateTime::Duration object expected' unless UNIVERSAL::isa($du,'DateTime::Duration');
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($du, "DateTime::Duration") 0 5 5
877  
878 5 my %deltas = $du->deltas();
879 5 my $output = '@';
880  
881 5 ▶ if($deltas{'nanoseconds'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($deltas{"nanoseconds"}) 2 3 5
882 $deltas{'seconds'} =
883 2 sprintf('%f', $deltas{'seconds'} + $deltas{'nanoseconds'} /
884 DateTime::Duration::MAX_NANOSECONDS);
885 }
886  
887 5 foreach(qw(months days minutes seconds)) {
888 20 ▶ $output .= ' '.$deltas{$_}.' '.$_ if $deltas{$_};
Branch: 1 branch
BranchTrueFalseTotal
if $deltas{$_} 8 12 20
889 }
890  
891 5 ▶ $output .= ' 0' if(length($output)<=2);
Branch: 1 branch
BranchTrueFalseTotal
if length $output <= 2 0 5 5
892 5 return $output;
893 }
894  
895 23 *format_interval = \&format_duration;
896  
897 =back
898  
899 =cut
900  
901  
902  
903 23 1;
904  
905 __END__
↑ Summary