Commit Graph

38 Commits

Author SHA1 Message Date
Tom Lane a7145f6bc8 Fix integer-overflow edge case detection in interval_mul and pgbench.
This patch adopts the overflow check logic introduced by commit cbdb8b4c0
into two more places.  interval_mul() failed to notice if it computed a
new microseconds value that was one more than INT64_MAX, and pgbench's
double-to-int64 logic had the same sorts of edge-case problems that
cbdb8b4c0 fixed in the core code.

To make this easier to get right in future, put the guts of the checks
into new macros in c.h, and add commentary about how to use the macros
correctly.

Back-patch to all supported branches, as we did with the previous fix.

Yuya Watari

Discussion: https://postgr.es/m/CAJ2pMkbkkFw2hb9Qb1Zj8d06EhWAQXFLy73St4qWv6aX=vqnjw@mail.gmail.com
2019-11-07 11:22:58 -05:00
Tom Lane df1a699e5b Fix integer-overflow problems in interval comparison.
When using integer timestamps, the interval-comparison functions tried
to compute the overall magnitude of an interval as an int64 number of
microseconds.  As reported by Frazer McLean, this overflows for intervals
exceeding about 296000 years, which is bad since we nominally allow
intervals many times larger than that.  That results in wrong comparison
results, and possibly in corrupted btree indexes for columns containing
such large interval values.

To fix, compute the magnitude as int128 instead.  Although some compilers
have native support for int128 calculations, many don't, so create our
own support functions that can do 128-bit addition and multiplication
if the compiler support isn't there.  These support functions are designed
with an eye to allowing the int128 code paths in numeric.c to be rewritten
for use on all platforms, although this patch doesn't do that, or even
provide all the int128 primitives that will be needed for it.

Back-patch as far as 9.4.  Earlier releases did not guard against overflow
of interval values at all (commit 146604ec4 fixed that), so it seems not
very exciting to worry about overly-large intervals for them.

Before 9.6, we did not assume that unreferenced "static inline" functions
would not draw compiler warnings, so omit functions not directly referenced
by timestamp.c, the only present consumer of int128.h.  (We could have
omitted these functions in HEAD too, but since they were written and
debugged on the way to the present patch, and they look likely to be needed
by numeric.c, let's keep them in HEAD.)  I did not bother to try to prevent
such warnings in a --disable-integer-datetimes build, though.

Before 9.5, configure will never define HAVE_INT128, so the part of
int128.h that exploits a native int128 implementation is dead code in the
9.4 branch.  I didn't bother to remove it, thinking that keeping the file
looking similar in different branches is more useful.

In HEAD only, add a simple test harness for int128.h in src/tools/.

In back branches, this does not change the float-timestamps code path.
That's not subject to the same kind of overflow risk, since it computes
the interval magnitude as float8.  (No doubt, when this code was originally
written, overflow was disregarded for exactly that reason.)  There is a
precision hazard instead :-(, but we'll avert our eyes from that question,
since no complaints have been reported and that code's deprecated anyway.

Kyotaro Horiguchi and Tom Lane

Discussion: https://postgr.es/m/1490104629.422698.918452336.26FA96B7@webmail.messagingengine.com
2017-04-05 23:51:27 -04:00
Tom Lane f0774abde8 Fix interval_transform so it doesn't throw away non-no-op casts.
interval_transform() contained two separate bugs that caused it to
sometimes mistakenly decide that a cast from interval to restricted
interval is a no-op and throw it away.

First, it was wrong to rely on dt.h's field type macros to have an
ordering consistent with the field's significance; in one case they do
not.  This led to mistakenly treating YEAR as less significant than MONTH,
so that a cast from INTERVAL MONTH to INTERVAL YEAR was incorrectly
discarded.

Second, fls(1<<k) produces k+1 not k, so comparing its output directly
to SECOND was wrong.  This led to supposing that a cast to INTERVAL
MINUTE was really a cast to INTERVAL SECOND and so could be discarded.

To fix, get rid of the use of fls(), and make a function based on
intervaltypmodout to produce a field ID code adapted to the need here.

Per bug #14479 from Piotr Stefaniak.  Back-patch to 9.2 where transform
functions were introduced, because this code was born broken.

Discussion: https://postgr.es/m/20161227172307.10135.7747@wrigleys.postgresql.org
2016-12-27 15:43:54 -05:00
Bruce Momjian 417f92484d interval: tighten precision specification
interval precision can only be specified after the "interval" keyword if
no units are specified.

Previously we incorrectly checked the units to see if the precision was
legal, causing confusion.

Report by Alvaro Herrera
2014-10-18 10:31:00 -04:00
Jeff Davis 348aa75a67 Fix interval test, which was broken for floating-point timestamps.
Commit 4318daecc9 introduced a test that
couldn't be made consistent between integer and floating-point
timestamps.

It was designed to test the longest possible interval output length,
so removing four zeros from the number of hours, as this patch does,
is not ideal. But the test still has some utility for its original
purpose, and there aren't a lot of other good options.

Noah Misch suggested a different approach where we test that the
output either matches what we expect from integer timestamps or what
we expect from floating-point timestamps. That seemed to obscure an
otherwise simple test, however.

Reviewed by Tom Lane and Noah Misch.
2014-05-06 19:53:59 -07:00
Alvaro Herrera 84df54b22e Constructors for interval, timestamp, timestamptz
Author: Pavel Stěhule, editorialized somewhat by Álvaro Herrera
Reviewed-by: Tomáš Vondra, Marko Tiikkaja
With input from Fabrízio de Royes Mello, Jim Nasby
2014-03-04 15:09:43 -03:00
Noah Misch 4318daecc9 Fix handling of wide datetime input/output.
Many server functions use the MAXDATELEN constant to size a buffer for
parsing or displaying a datetime value.  It was much too small for the
longest possible interval output and slightly too small for certain
valid timestamp input, particularly input with a long timezone name.
The long input was rejected needlessly; the long output caused
interval_out() to overrun its buffer.  ECPG's pgtypes library has a copy
of the vulnerable functions, which bore the same vulnerabilities along
with some of its own.  In contrast to the server, certain long inputs
caused stack overflow rather than failing cleanly.  Back-patch to 8.4
(all supported versions).

Reported by Daniel Schüssler, reviewed by Tom Lane.

Security: CVE-2014-0063
2014-02-17 09:33:31 -05:00
Tom Lane 3152bf722f Fix bugs with parsing signed hh:mm and hh:mm:ss fields in interval input.
DecodeInterval() failed to honor the "range" parameter (the special SQL
syntax for indicating which fields appear in the literal string) if the
time was signed.  This seems inappropriate, so make it work like the
not-signed case.  The inconsistency was introduced in my commit
f867339c01, which as noted in its log message
was only really focused on making SQL-compliant literals work per spec.
Including a sign here is not per spec, but if we're going to allow it
then it's reasonable to expect it to work like the not-signed case.

Also, remove bogus setting of tmask, which caused subsequent processing to
think that what had been given was a timezone and not an hh:mm(:ss) field,
thus confusing checks for redundant fields.  This seems to be an aboriginal
mistake in Lockhart's commit 2cf1642461.

Add regression test cases to illustrate the changed behaviors.

Back-patch as far as 8.4, where support for spec-compliant interval
literals was added.

Range problem reported and diagnosed by Amit Kapila, tmask problem by me.
2012-08-03 17:40:43 -04:00
Peter Eisentraut fc946c39ae Remove useless whitespace at end of lines 2010-11-23 22:34:55 +02:00
Tom Lane 5cca35a68b Make handling of INTERVAL DAY TO MINUTE and INTERVAL DAY TO SECOND input
more consistent with other cases, by having an unlabeled integer field
be treated as a number of minutes or seconds respectively.  These cases
are outside the spec (which insists on full "dd hh:mm" or "dd hh:mm:ss"
input respectively), so it's not much help to us in deciding what to do.
But with this change, it's uniformly the case that an unlabeled integer
will be considered as being a number of the interval's rightmost field.
The change also takes us back to the 8.3 behavior of throwing error
for certain ambiguous inputs such as INTERVAL '1 2' DAY TO MINUTE.
Per recent discussion.
2009-06-10 05:05:03 +00:00
Tom Lane bac2ad38ea Change AdjustIntervalForTypmod to not discard higher-order field values on the
grounds that they don't fit into the specified interval qualifier (typmod).
This behavior, while of long standing, is clearly wrong per spec --- for
example the value INTERVAL '999' SECOND means 999 seconds and should not be
reduced to less than 60 seconds.

In some cases there could be grounds to raise an error if higher-order field
values are not given as zero; for example '1 year 1 month'::INTERVAL MONTH
should arguably be taken as an error rather than equivalent to 13 months.
However our internal representation doesn't allow us to do that in a fashion
that would consistently reject all and only the cases that a strict reading
of the spec would suggest.  Also, seeing that for example INTERVAL '13' MONTH
will print out as '1 year 1 mon', we have to be careful not to create a
situation where valid data will fail to dump and reload.  The present patch
therefore takes the attitude of not throwing an error in any such case.
We might want to revisit that in future but it would take more redesign
than seems prudent in late beta.

Per a complaint from Sebastien Flaesch and subsequent discussion.  While
at other times we might have just postponed such an issue to the next
development cycle, 8.4 already has changed the parsing of interval literals
quite a bit in an effort to accept all spec-compliant cases correctly.
This seems like a change that should be part of that rather than coming
along later.
2009-06-01 23:55:15 +00:00
Tom Lane 1c2d408c01 Rewrite interval_hash() so that the hashcodes are equal for values that
interval_eq() considers equal.  I'm not sure how that fundamental requirement
escaped us through multiple revisions of this hash function, but there it is;
it's been wrong since interval_hash was first written for PG 7.1.
Per bug #4748 from Roman Kononov.

Backpatch to all supported releases.

This patch changes the contents of hash indexes for interval columns.  That's
no particular problem for PG 8.4, since we've broken on-disk compatibility
of hash indexes already; but it will require a migration warning note in
the next minor releases of all existing branches: "if you have any hash
indexes on columns of type interval, REINDEX them after updating".
2009-04-04 04:53:25 +00:00
Tom Lane d1ab3eb712 Clean up the ancient decision to show only two fractional-seconds digits
in "postgres_verbose" intervalstyle, and the equally arbitrary decision to
show at least two fractional-seconds digits in most other datetime display
styles.  This results in some minor changes in the expected regression test
outputs.

Also, coalesce a lot of repetitive code in datetime.c into subroutines,
for clarity and ease of maintenance.  In particular this roughly halves
the number of #ifdef HAVE_INT64_TIMESTAMP segments.

Ron Mayer, with some additional kibitzing from Tom Lane
2008-11-12 01:36:20 +00:00
Tom Lane a4917bef0e Add support for input and output of interval values formatted per ISO 8601;
specifically, we can input either the "format with designators" or the
"alternative format", and we can output the former when IntervalStyle is set
to iso_8601.

Ron Mayer
2008-11-11 02:42:33 +00:00
Tom Lane df7641e25a Add a new GUC variable called "IntervalStyle" that decouples interval output
from DateStyle, and create a new interval style that produces output matching
the SQL standard (at least for interval values that fall within the standard's
restrictions).  IntervalStyle is also used to resolve the conflict between the
standard and traditional Postgres rules for interpreting negative interval
input.

Ron Mayer
2008-11-09 00:28:35 +00:00
Tom Lane b73c0c2a51 Clean up a couple of weird corner cases in interval parsing: make -yyyy-mm be
interpreted as expected (the sign should affect months too), and get rid of
hard-wired assumption that unmarked signed values must be hours (if integers)
or seconds (if floats).  The former was just a bug in my previous patch,
while the latter may have made sense at one time but seems illogical now
that we support determination of the units from typmod information.
Ron Mayer and myself.
2008-09-16 22:31:21 +00:00
Tom Lane 70530c808b Adjust the parser to accept the typename syntax INTERVAL ... SECOND(n)
and the literal syntax INTERVAL 'string' ... SECOND(n), as required by the
SQL standard.  Our old syntax put (n) directly after INTERVAL, which was
a mistake, but will still be accepted for backward compatibility as well
as symmetry with the TIMESTAMP cases.

Change intervaltypmodout to show it in the spec's way, too.  (This could
potentially affect clients, if there are any that analyze the typmod of an
INTERVAL in any detail.)

Also fix interval input to handle 'min:sec.frac' properly; I had overlooked
this case in my previous patch.

Document the use of the interval fields qualifier, which up to now we had
never mentioned in the docs.  (I think the omission was intentional because
it didn't work per spec; but it does now, or at least close enough to be
credible.)
2008-09-11 15:27:30 +00:00
Tom Lane f867339c01 Make our parsing of INTERVAL literals spec-compliant (or at least a heck of
a lot closer than it was before).  To do this, tweak coerce_type() to pass
through the typmod information when invoking interval_in() on an UNKNOWN
constant; then fix DecodeInterval to pay attention to the typmod when deciding
how to interpret a units-less integer value.  I changed one or two other
details as well.  I believe the code now reacts as expected by spec for all
the literal syntaxes that are specifically enumerated in the spec.  There
are corner cases involving strings that don't exactly match the set of fields
called out by the typmod, for which we might want to tweak the behavior some
more; but I think this is an area of user friendliness rather than spec
compliance.  There remain some non-compliant details about the SQL syntax
(as opposed to what's inside the literal string); but at least we'll throw
error rather than silently doing the wrong thing in those cases.
2008-09-10 18:29:41 +00:00
Tom Lane b153c09209 Add a bunch of new error location reports to parse-analysis error messages.
There are still some weak spots around JOIN USING and relation alias lists,
but most errors reported within backend/parser/ now have locations.
2008-09-01 20:42:46 +00:00
Neil Conway 6af04882de Fix a bug in input processing for the "interval" type. Previously,
"microsecond" and "millisecond" units were not considered valid input
by themselves, which caused inputs like "1 millisecond" to be rejected
erroneously.

Update the docs, add regression tests, and backport to 8.2 and 8.1
2007-05-29 04:58:43 +00:00
Bruce Momjian 6ca4ea8a80 Add interval division/multiplication regression tests.
Michael Glaesemann
2006-09-06 02:05:41 +00:00
Tom Lane 57bfb27e60 Fix interval input parser so that fractional weeks and months are
cascaded first to days and only what is leftover into seconds.  This
seems to satisfy the principle of least surprise given the general
conversion to three-part interval values --- it was an oversight that
these cases weren't dealt with in 8.1.  Michael Glaesemann
2006-09-04 01:26:28 +00:00
Bruce Momjian fc51c9186a Properly round months into days and into seconds for interval
multiplication/division queries like select '41 mon 10:00:00'::interval
/ 10 as "pos".

Report from Michael Glaesemann
2006-09-03 03:34:04 +00:00
Bruce Momjian d69b163247 Attached is the new patch. To summarize:
- new function justify_interval(interval)
   - modified function justify_hours(interval)
   - modified function justify_days(interval)

These functions are defined to meet the requirements as discussed in
this thread.  Specifically:

   - justify_hours makes certain the sign bit on the hours
     matches the sign bit on the days.  It only checks the
     sign bit on the days, and not the months, when
     determining if the hours should be positive or negative.
     After the call, -24 < hours < 24.

   - justify_days makes certain the sign bit on the days
     matches the sign bit on the months.  It's behavior does
     not depend on the hours, nor does it modify the hours.
     After the call, -30 < days < 30.

   - justify_interval makes sure the sign bits on all three
     fields months, days, and hours are all the same.  After
     the call, -24 < hours < 24 AND -30 < days < 30.

Mark Dilger
2006-03-06 22:49:17 +00:00
Tom Lane 6a9b93a0e1 Remove justify_hours call from interval_mul and interval_div, and make
some small stylistic improvements in these functions.  Also fix several
places where TMODULO() was being used with wrong-sized quotient argument,
creating a risk of overflow --- interval2tm was actually capable of going
into an infinite loop because of this.
2005-10-25 17:13:07 +00:00
Bruce Momjian b2b6548c79 Please find attached diffs for documentation and simple regression
tests for the new interval->day changes. I added tests for
justify_hours() and justify_days() to interval.sql, as they take
interval input and produce interval output. If there's a more
appropriate place for them, please let me know.

Michael Glaesemann
2005-07-30 14:52:04 +00:00
Bruce Momjian db05f4a7eb Add 'day' field to INTERVAL so 1 day interval can be distinguished from
24 hours. This is very helpful for daylight savings time:

	select '2005-05-03 00:00:00 EST'::timestamp with time zone + '24 hours';
	      ?column?
	----------------------
	2005-05-04 01:00:00-04

	select '2005-05-03 00:00:00 EST'::timestamp with time zone + '1 day';
	      ?column?
	----------------------
	2005-05-04 01:00:00-04

Michael Glaesemann
2005-07-20 16:42:32 +00:00
Neil Conway 63e0d612f5 Adjust datetime parsing to be more robust. We now pass the length of the
working buffer into ParseDateTime() and reject too-long input there,
rather than checking the length of the input string before calling
ParseDateTime(). The old method was bogus because ParseDateTime() can use
a variable amount of working space, depending on the content of the
input string (e.g. how many fields need to be NUL terminated). This fixes
a minor stack overrun -- I don't _think_ it's exploitable, although I
won't claim to be an expert.

Along the way, fix a bug reported by Mark Dilger: the working buffer
allocated by interval_in() was too short, which resulted in rejecting
some perfectly valid interval input values. I added a regression test for
this fix.
2005-05-26 02:04:14 +00:00
Neil Conway f5ab0a14ea Add a "USING" clause to DELETE, which is equivalent to the FROM clause
in UPDATE. We also now issue a NOTICE if a query has _any_ implicit
range table entries -- in the past, we would only warn about implicit
RTEs in SELECTs with at least one explicit RTE.

As a result of the warning change, 25 of the regression tests had to
be updated. I also took the opportunity to remove some bogus whitespace
differences between some of the float4 and float8 variants. I believe
I have correctly updated all the platform-specific variants, but let
me know if that's not the case.

Original patch for DELETE ... USING from Euler Taveira de Oliveira,
reworked by Neil Conway.
2005-04-07 01:51:41 +00:00
Peter Eisentraut feb4f44d29 Message editing: remove gratuitous variations in message wording, standardize
terms, add some clarifications, fix some untranslatable attempts at dynamic
message building.
2003-09-25 06:58:07 +00:00
Tom Lane b6a1d25b0a Error message editing in utils/adt. Again thanks to Joe Conway for doing
the bulk of the heavy lifting ...
2003-07-27 04:53:12 +00:00
Tom Lane 621691d816 In ISO datestyle, never emit just HH:MM, always emit HH:MM:SS or
HH:MM:SS.SSS... when there is a nonzero part-of-a-day field in an
interval value.  The seconds part used to be suppressed if zero,
but there's no equivalent behavior for timestamp, and since we're
modeling this format on timestamp it's probably wrong.  Per complaint
and patch from Larry Rosenman.
2003-06-25 21:14:15 +00:00
Tom Lane cb7fb3ca95 First phase of FE/BE protocol modifications: new StartupPacket layout
with variable-width fields.  No more truncation of long user names.
Also, libpq can now send its environment-variable-driven SET commands
as part of the startup packet, saving round trips to server.
2003-04-17 22:26:02 +00:00
Tom Lane 78b674ba35 Add regression test to catch future breakage of avg(interval). This
aggregate seems uniquely fragile, because it's the only one with an
agginitval that's at all likely to change in format.
2001-05-18 16:02:01 +00:00
Thomas G. Lockhart 6acdebbd3a Fix up "Postgres-style" time interval representation when fields have
mixed-signs. Previous effort left way too many minus signs, and was at
 least as broken as the one before that :(
Clean up "ISO-style" time interval representation to omit zero fields if
 there is at least one non-zero field. Supress some leading plus signs
 when not necessary for clarity.
Replace every #ifdef __CYGWIN__ block with a cleaner TIMEZONE_GLOBAL macro
 defined in datetime.h.
2001-01-18 07:22:43 +00:00
Thomas G. Lockhart d74c52c357 Allow more timezone-like interpretation of INTERVALs. 2000-11-11 19:56:43 +00:00
Thomas G. Lockhart 07272c6f8b Add tests for more INTERVAL syntax.
Add more tests for JOIN syntax.
All tests pass on my Linux box (except for the usual couple of lines
 for geometry).
2000-11-06 16:03:47 +00:00
Thomas G. Lockhart 8997675c4b All regression tests pass except for rules.sql (unrelated).
Implement "date/time grand unification".
 Transform datetime and timespan into timestamp and interval.
 Deprecate datetime and timespan, though translate to new types in gram.y.
 Transform all datetime and timespan catalog entries into new types.
 Make "INTERVAL" reserved word allowed as a column identifier in gram.y.
 Remove dt.h, dt.c files, and retarget datetime.h, datetime.c as utility
  routines for all date/time types.
 date.{h,c} now deals with date, time types.
 timestamp.{h,c} now deals with timestamp, interval types.
 nabstime.{h,c} now deals with abstime, reltime, tinterval types.
Make NUMERIC a known native type for purposes of type coersion. Not tested.
2000-02-16 17:27:27 +00:00
Renamed from src/test/regress/expected/timespan.out (Browse further)