PostgreSQL Source Code git master
datetime.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include "access/htup_details.h"
#include "access/xact.h"
#include "common/int.h"
#include "common/string.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "parser/scansup.h"
#include "utils/builtins.h"
#include "utils/date.h"
#include "utils/datetime.h"
#include "utils/guc.h"
#include "utils/tzparser.h"
Include dependency graph for datetime.c:

Go to the source code of this file.

Data Structures

struct  TzAbbrevCache
 

Macros

#define APPEND_CHAR(bufptr, end, newchar)
 

Typedefs

typedef struct TzAbbrevCache TzAbbrevCache
 

Functions

static int DecodeNumber (int flen, char *str, bool haveTextMonth, int fmask, int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
 
static int DecodeNumberField (int len, char *str, int fmask, int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
 
static int DecodeTimeCommon (char *str, int fmask, int range, int *tmask, struct pg_itm *itm)
 
static int DecodeTime (char *str, int fmask, int range, int *tmask, struct pg_tm *tm, fsec_t *fsec)
 
static int DecodeTimeForInterval (char *str, int fmask, int range, int *tmask, struct pg_itm_in *itm_in)
 
static const datetkndatebsearch (const char *key, const datetkn *base, int nel)
 
static int DecodeDate (char *str, int fmask, int *tmask, bool *is2digits, struct pg_tm *tm)
 
static char * AppendSeconds (char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
 
static bool int64_multiply_add (int64 val, int64 multiplier, int64 *sum)
 
static bool AdjustFractMicroseconds (double frac, int64 scale, struct pg_itm_in *itm_in)
 
static bool AdjustFractDays (double frac, int scale, struct pg_itm_in *itm_in)
 
static bool AdjustFractYears (double frac, int scale, struct pg_itm_in *itm_in)
 
static bool AdjustMicroseconds (int64 val, double fval, int64 scale, struct pg_itm_in *itm_in)
 
static bool AdjustDays (int64 val, int scale, struct pg_itm_in *itm_in)
 
static bool AdjustMonths (int64 val, struct pg_itm_in *itm_in)
 
static bool AdjustYears (int64 val, int scale, struct pg_itm_in *itm_in)
 
static int DetermineTimeZoneOffsetInternal (struct pg_tm *tm, pg_tz *tzp, pg_time_t *tp)
 
static bool DetermineTimeZoneAbbrevOffsetInternal (pg_time_t t, const char *abbr, pg_tz *tzp, int *offset, int *isdst)
 
static pg_tzFetchDynamicTimeZone (TimeZoneAbbrevTable *tbl, const datetkn *tp, DateTimeErrorExtra *extra)
 
int date2j (int year, int month, int day)
 
void j2date (int jd, int *year, int *month, int *day)
 
int j2day (int date)
 
void GetCurrentDateTime (struct pg_tm *tm)
 
void GetCurrentTimeUsec (struct pg_tm *tm, fsec_t *fsec, int *tzp)
 
static char * AppendTimestampSeconds (char *cp, struct pg_tm *tm, fsec_t fsec)
 
static int ParseFraction (char *cp, double *frac)
 
static int ParseFractionalSecond (char *cp, fsec_t *fsec)
 
int ParseDateTime (const char *timestr, char *workbuf, size_t buflen, char **field, int *ftype, int maxfields, int *numfields)
 
int DecodeDateTime (char **field, int *ftype, int nf, int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp, DateTimeErrorExtra *extra)
 
int DetermineTimeZoneOffset (struct pg_tm *tm, pg_tz *tzp)
 
int DetermineTimeZoneAbbrevOffset (struct pg_tm *tm, const char *abbr, pg_tz *tzp)
 
int DetermineTimeZoneAbbrevOffsetTS (TimestampTz ts, const char *abbr, pg_tz *tzp, int *isdst)
 
static bool TimeZoneAbbrevIsKnown (const char *abbr, pg_tz *tzp, bool *isfixed, int *offset, int *isdst)
 
int DecodeTimeOnly (char **field, int *ftype, int nf, int *dtype, struct pg_tm *tm, fsec_t *fsec, int *tzp, DateTimeErrorExtra *extra)
 
int ValidateDate (int fmask, bool isjulian, bool is2digits, bool bc, struct pg_tm *tm)
 
int DecodeTimezone (const char *str, int *tzp)
 
int DecodeTimezoneAbbrev (int field, const char *lowtoken, int *ftype, int *offset, pg_tz **tz, DateTimeErrorExtra *extra)
 
void ClearTimeZoneAbbrevCache (void)
 
int DecodeSpecial (int field, const char *lowtoken, int *val)
 
int DecodeTimezoneName (const char *tzname, int *offset, pg_tz **tz)
 
pg_tzDecodeTimezoneNameToTz (const char *tzname)
 
int DecodeTimezoneAbbrevPrefix (const char *str, int *offset, pg_tz **tz)
 
static void ClearPgItmIn (struct pg_itm_in *itm_in)
 
int DecodeInterval (char **field, int *ftype, int nf, int range, int *dtype, struct pg_itm_in *itm_in)
 
static int ParseISO8601Number (char *str, char **endptr, int64 *ipart, double *fpart)
 
static int ISO8601IntegerWidth (char *fieldstart)
 
int DecodeISO8601Interval (char *str, int *dtype, struct pg_itm_in *itm_in)
 
int DecodeUnits (int field, const char *lowtoken, int *val)
 
void DateTimeParseError (int dterr, DateTimeErrorExtra *extra, const char *str, const char *datatype, Node *escontext)
 
static char * EncodeTimezone (char *str, int tz, int style)
 
void EncodeDateOnly (struct pg_tm *tm, int style, char *str)
 
void EncodeTimeOnly (struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, int style, char *str)
 
void EncodeDateTime (struct pg_tm *tm, fsec_t fsec, bool print_tz, int tz, const char *tzn, int style, char *str)
 
static char * AddISO8601IntPart (char *cp, int64 value, char units)
 
static char * AddPostgresIntPart (char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
 
static char * AddVerboseIntPart (char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
 
void EncodeInterval (struct pg_itm *itm, int style, char *str)
 
static bool CheckDateTokenTable (const char *tablename, const datetkn *base, int nel)
 
bool CheckDateTokenTables (void)
 
NodeTemporalSimplify (int32 max_precis, Node *node)
 
TimeZoneAbbrevTableConvertTimeZoneAbbrevs (struct tzEntry *abbrevs, int n)
 
void InstallTimeZoneAbbrevs (TimeZoneAbbrevTable *tbl)
 
Datum pg_timezone_abbrevs_zone (PG_FUNCTION_ARGS)
 
Datum pg_timezone_abbrevs_abbrevs (PG_FUNCTION_ARGS)
 
Datum pg_timezone_names (PG_FUNCTION_ARGS)
 

Variables

const int day_tab [2][13]
 
const char *const months []
 
const char *const days []
 
static const datetkn datetktbl []
 
static const int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0]
 
static const datetkn deltatktbl []
 
static const int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0]
 
static TimeZoneAbbrevTablezoneabbrevtbl = NULL
 
static const datetkndatecache [MAXDATEFIELDS] = {NULL}
 
static const datetkndeltacache [MAXDATEFIELDS] = {NULL}
 
static TzAbbrevCache tzabbrevcache [MAXDATEFIELDS]
 

Macro Definition Documentation

◆ APPEND_CHAR

#define APPEND_CHAR (   bufptr,
  end,
  newchar 
)
Value:
do \
{ \
if (((bufptr) + 1) >= (end)) \
return DTERR_BAD_FORMAT; \
*(bufptr)++ = newchar; \
} while (0)
#define DTERR_BAD_FORMAT
Definition: datetime.h:282

Typedef Documentation

◆ TzAbbrevCache

typedef struct TzAbbrevCache TzAbbrevCache

Function Documentation

◆ AddISO8601IntPart()

static char * AddISO8601IntPart ( char *  cp,
int64  value,
char  units 
)
static

Definition at line 4635 of file datetime.c.

4636{
4637 if (value == 0)
4638 return cp;
4639 sprintf(cp, "%" PRId64 "%c", value, units);
4640 return cp + strlen(cp);
4641}
static struct @171 value
#define sprintf
Definition: port.h:262

References sprintf, and value.

Referenced by EncodeInterval().

◆ AddPostgresIntPart()

static char * AddPostgresIntPart ( char *  cp,
int64  value,
const char *  units,
bool *  is_zero,
bool *  is_before 
)
static

Definition at line 4645 of file datetime.c.

4647{
4648 if (value == 0)
4649 return cp;
4650 sprintf(cp, "%s%s%" PRId64 " %s%s",
4651 (!*is_zero) ? " " : "",
4652 (*is_before && value > 0) ? "+" : "",
4653 value,
4654 units,
4655 (value != 1) ? "s" : "");
4656
4657 /*
4658 * Each nonzero field sets is_before for (only) the next one. This is a
4659 * tad bizarre but it's how it worked before...
4660 */
4661 *is_before = (value < 0);
4662 *is_zero = false;
4663 return cp + strlen(cp);
4664}

References sprintf, and value.

Referenced by EncodeInterval().

◆ AddVerboseIntPart()

static char * AddVerboseIntPart ( char *  cp,
int64  value,
const char *  units,
bool *  is_zero,
bool *  is_before 
)
static

Definition at line 4668 of file datetime.c.

4670{
4671 if (value == 0)
4672 return cp;
4673 /* first nonzero value sets is_before */
4674 if (*is_zero)
4675 {
4676 *is_before = (value < 0);
4677 value = i64abs(value);
4678 }
4679 else if (*is_before)
4680 value = -value;
4681 sprintf(cp, " %" PRId64 " %s%s", value, units, (value == 1) ? "" : "s");
4682 *is_zero = false;
4683 return cp + strlen(cp);
4684}

References sprintf, and value.

Referenced by EncodeInterval().

◆ AdjustDays()

static bool AdjustDays ( int64  val,
int  scale,
struct pg_itm_in itm_in 
)
static

Definition at line 643 of file datetime.c.

644{
645 int days;
646
647 if (val < INT_MIN || val > INT_MAX)
648 return false;
649 return !pg_mul_s32_overflow((int32) val, scale, &days) &&
650 !pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
651}
const char *const days[]
Definition: datetime.c:84
int32_t int32
Definition: c.h:539
long val
Definition: informix.c:689
static bool pg_mul_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:187
static bool pg_add_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:151
static int scale
Definition: pgbench.c:182
int tm_mday
Definition: timestamp.h:85

References days, pg_add_s32_overflow(), pg_mul_s32_overflow(), scale, pg_itm_in::tm_mday, and val.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustFractDays()

static bool AdjustFractDays ( double  frac,
int  scale,
struct pg_itm_in itm_in 
)
static

Definition at line 579 of file datetime.c.

581{
582 int extra_days;
583
584 /* Fast path for common case */
585 if (frac == 0)
586 return true;
587
588 /*
589 * We assume the input frac has abs value less than 1, so overflow of frac
590 * or extra_days is not an issue.
591 */
592 frac *= scale;
593 extra_days = (int) frac;
594
595 /* ... but this could overflow, if tm_mday is already nonzero */
596 if (pg_add_s32_overflow(itm_in->tm_mday, extra_days, &itm_in->tm_mday))
597 return false;
598
599 /* Handle any fractional day */
600 frac -= extra_days;
601 return AdjustFractMicroseconds(frac, USECS_PER_DAY, itm_in);
602}
static bool AdjustFractMicroseconds(double frac, int64 scale, struct pg_itm_in *itm_in)
Definition: datetime.c:547
#define USECS_PER_DAY
Definition: timestamp.h:131

References AdjustFractMicroseconds(), pg_add_s32_overflow(), scale, pg_itm_in::tm_mday, and USECS_PER_DAY.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustFractMicroseconds()

static bool AdjustFractMicroseconds ( double  frac,
int64  scale,
struct pg_itm_in itm_in 
)
static

Definition at line 547 of file datetime.c.

549{
550 int64 usec;
551
552 /* Fast path for common case */
553 if (frac == 0)
554 return true;
555
556 /*
557 * We assume the input frac has abs value less than 1, so overflow of frac
558 * or usec is not an issue for interesting values of scale.
559 */
560 frac *= scale;
561 usec = (int64) frac;
562
563 /* Round off any fractional microsecond */
564 frac -= usec;
565 if (frac > 0.5)
566 usec++;
567 else if (frac < -0.5)
568 usec--;
569
570 return !pg_add_s64_overflow(itm_in->tm_usec, usec, &itm_in->tm_usec);
571}
int64_t int64
Definition: c.h:540
static bool pg_add_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:235
int64 tm_usec
Definition: timestamp.h:84

References pg_add_s64_overflow(), scale, and pg_itm_in::tm_usec.

Referenced by AdjustFractDays(), AdjustMicroseconds(), DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustFractYears()

static bool AdjustFractYears ( double  frac,
int  scale,
struct pg_itm_in itm_in 
)
static

Definition at line 611 of file datetime.c.

613{
614 /*
615 * As above, we assume abs(frac) < 1, so this can't overflow for any
616 * interesting value of scale.
617 */
618 int extra_months = (int) rint(frac * scale * MONTHS_PER_YEAR);
619
620 return !pg_add_s32_overflow(itm_in->tm_mon, extra_months, &itm_in->tm_mon);
621}
#define MONTHS_PER_YEAR
Definition: timestamp.h:108
int tm_mon
Definition: timestamp.h:86

References MONTHS_PER_YEAR, pg_add_s32_overflow(), scale, and pg_itm_in::tm_mon.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustMicroseconds()

static bool AdjustMicroseconds ( int64  val,
double  fval,
int64  scale,
struct pg_itm_in itm_in 
)
static

Definition at line 628 of file datetime.c.

630{
631 /* Handle the integer part */
632 if (!int64_multiply_add(val, scale, &itm_in->tm_usec))
633 return false;
634 /* Handle the float part */
635 return AdjustFractMicroseconds(fval, scale, itm_in);
636}
static bool int64_multiply_add(int64 val, int64 multiplier, int64 *sum)
Definition: datetime.c:532

References AdjustFractMicroseconds(), int64_multiply_add(), scale, pg_itm_in::tm_usec, and val.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustMonths()

static bool AdjustMonths ( int64  val,
struct pg_itm_in itm_in 
)
static

Definition at line 659 of file datetime.c.

660{
661 if (val < INT_MIN || val > INT_MAX)
662 return false;
663 return !pg_add_s32_overflow(itm_in->tm_mon, (int32) val, &itm_in->tm_mon);
664}

References pg_add_s32_overflow(), pg_itm_in::tm_mon, and val.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustYears()

static bool AdjustYears ( int64  val,
int  scale,
struct pg_itm_in itm_in 
)
static

Definition at line 671 of file datetime.c.

673{
674 int years;
675
676 if (val < INT_MIN || val > INT_MAX)
677 return false;
678 return !pg_mul_s32_overflow((int32) val, scale, &years) &&
679 !pg_add_s32_overflow(itm_in->tm_year, years, &itm_in->tm_year);
680}
int tm_year
Definition: timestamp.h:87

References pg_add_s32_overflow(), pg_mul_s32_overflow(), scale, pg_itm_in::tm_year, and val.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AppendSeconds()

static char * AppendSeconds ( char *  cp,
int  sec,
fsec_t  fsec,
int  precision,
bool  fillzeros 
)
static

Definition at line 458 of file datetime.c.

459{
460 Assert(precision >= 0);
461
462 if (fillzeros)
463 cp = pg_ultostr_zeropad(cp, abs(sec), 2);
464 else
465 cp = pg_ultostr(cp, abs(sec));
466
467 /* fsec_t is just an int32 */
468 if (fsec != 0)
469 {
470 int32 value = abs(fsec);
471 char *end = &cp[precision + 1];
472 bool gotnonzero = false;
473
474 *cp++ = '.';
475
476 /*
477 * Append the fractional seconds part. Note that we don't want any
478 * trailing zeros here, so since we're building the number in reverse
479 * we'll skip appending zeros until we've output a non-zero digit.
480 */
481 while (precision--)
482 {
483 int32 oldval = value;
485
486 value /= 10;
487 remainder = oldval - value * 10;
488
489 /* check if we got a non-zero */
490 if (remainder)
491 gotnonzero = true;
492
493 if (gotnonzero)
494 cp[precision] = '0' + remainder;
495 else
496 end = &cp[precision];
497 }
498
499 /*
500 * If we still have a non-zero value then precision must have not been
501 * enough to print the number. We punt the problem to pg_ultostr(),
502 * which will generate a correct answer in the minimum valid width.
503 */
504 if (value)
505 return pg_ultostr(cp, abs(fsec));
506
507 return end;
508 }
509 else
510 return cp;
511}
Assert(PointerIsAligned(start, uint64))
size_t remainder
char * pg_ultostr_zeropad(char *str, uint32 value, int32 minwidth)
Definition: numutils.c:1267
char * pg_ultostr(char *str, uint32 value)
Definition: numutils.c:1307

References Assert(), pg_ultostr(), pg_ultostr_zeropad(), remainder, and value.

Referenced by AppendTimestampSeconds(), EncodeInterval(), and EncodeTimeOnly().

◆ AppendTimestampSeconds()

static char * AppendTimestampSeconds ( char *  cp,
struct pg_tm tm,
fsec_t  fsec 
)
static

Definition at line 521 of file datetime.c.

522{
523 return AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
524}
static char * AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
Definition: datetime.c:458
#define MAX_TIMESTAMP_PRECISION
Definition: timestamp.h:92
static struct pg_tm tm
Definition: localtime.c:104
int tm_sec
Definition: pgtime.h:36

References AppendSeconds(), MAX_TIMESTAMP_PRECISION, tm, and pg_tm::tm_sec.

Referenced by EncodeDateTime().

◆ CheckDateTokenTable()

static bool CheckDateTokenTable ( const char *  tablename,
const datetkn base,
int  nel 
)
static

Definition at line 4901 of file datetime.c.

4902{
4903 bool ok = true;
4904 int i;
4905
4906 for (i = 0; i < nel; i++)
4907 {
4908 /* check for token strings that don't fit */
4909 if (strlen(base[i].token) > TOKMAXLEN)
4910 {
4911 /* %.*s is safe since all our tokens are ASCII */
4912 elog(LOG, "token too long in %s table: \"%.*s\"",
4913 tablename,
4914 TOKMAXLEN + 1, base[i].token);
4915 ok = false;
4916 break; /* don't risk applying strcmp */
4917 }
4918 /* check for out of order */
4919 if (i > 0 &&
4920 strcmp(base[i - 1].token, base[i].token) >= 0)
4921 {
4922 elog(LOG, "ordering error in %s table: \"%s\" >= \"%s\"",
4923 tablename,
4924 base[i - 1].token,
4925 base[i].token);
4926 ok = false;
4927 }
4928 }
4929 return ok;
4930}
#define LOG
Definition: elog.h:31
#define elog(elevel,...)
Definition: elog.h:226
#define TOKMAXLEN
Definition: datetime.h:204
int i
Definition: isn.c:77

References elog, i, LOG, and TOKMAXLEN.

Referenced by CheckDateTokenTables(), and ConvertTimeZoneAbbrevs().

◆ CheckDateTokenTables()

bool CheckDateTokenTables ( void  )

Definition at line 4933 of file datetime.c.

4934{
4935 bool ok = true;
4936
4937 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4938 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4939
4940 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4941 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4942 return ok;
4943}
static bool CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
Definition: datetime.c:4901
static const datetkn datetktbl[]
Definition: datetime.c:105
static const int szdeltatktbl
Definition: datetime.c:252
static const int szdatetktbl
Definition: datetime.c:181
int date2j(int year, int month, int day)
Definition: datetime.c:296
static const datetkn deltatktbl[]
Definition: datetime.c:187
#define UNIX_EPOCH_JDATE
Definition: timestamp.h:234
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:235

References Assert(), CheckDateTokenTable(), date2j(), datetktbl, deltatktbl, POSTGRES_EPOCH_JDATE, szdatetktbl, szdeltatktbl, and UNIX_EPOCH_JDATE.

Referenced by PostmasterMain().

◆ ClearPgItmIn()

static void ClearPgItmIn ( struct pg_itm_in itm_in)
inlinestatic

Definition at line 3462 of file datetime.c.

3463{
3464 itm_in->tm_usec = 0;
3465 itm_in->tm_mday = 0;
3466 itm_in->tm_mon = 0;
3467 itm_in->tm_year = 0;
3468}

References pg_itm_in::tm_mday, pg_itm_in::tm_mon, pg_itm_in::tm_usec, and pg_itm_in::tm_year.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ ClearTimeZoneAbbrevCache()

void ClearTimeZoneAbbrevCache ( void  )

Definition at line 3227 of file datetime.c.

3228{
3229 memset(tzabbrevcache, 0, sizeof(tzabbrevcache));
3230}
static TzAbbrevCache tzabbrevcache[MAXDATEFIELDS]
Definition: datetime.c:272

References tzabbrevcache.

Referenced by assign_timezone().

◆ ConvertTimeZoneAbbrevs()

TimeZoneAbbrevTable * ConvertTimeZoneAbbrevs ( struct tzEntry abbrevs,
int  n 
)

Definition at line 4995 of file datetime.c.

4996{
4998 Size tbl_size;
4999 int i;
5000
5001 /* Space for fixed fields and datetkn array */
5002 tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
5003 n * sizeof(datetkn);
5004 tbl_size = MAXALIGN(tbl_size);
5005 /* Count up space for dynamic abbreviations */
5006 for (i = 0; i < n; i++)
5007 {
5008 struct tzEntry *abbr = abbrevs + i;
5009
5010 if (abbr->zone != NULL)
5011 {
5012 Size dsize;
5013
5014 dsize = offsetof(DynamicZoneAbbrev, zone) +
5015 strlen(abbr->zone) + 1;
5016 tbl_size += MAXALIGN(dsize);
5017 }
5018 }
5019
5020 /* Alloc the result ... */
5021 tbl = guc_malloc(LOG, tbl_size);
5022 if (!tbl)
5023 return NULL;
5024
5025 /* ... and fill it in */
5026 tbl->tblsize = tbl_size;
5027 tbl->numabbrevs = n;
5028 /* in this loop, tbl_size reprises the space calculation above */
5029 tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
5030 n * sizeof(datetkn);
5031 tbl_size = MAXALIGN(tbl_size);
5032 for (i = 0; i < n; i++)
5033 {
5034 struct tzEntry *abbr = abbrevs + i;
5035 datetkn *dtoken = tbl->abbrevs + i;
5036
5037 /* use strlcpy to truncate name if necessary */
5038 strlcpy(dtoken->token, abbr->abbrev, TOKMAXLEN + 1);
5039 if (abbr->zone != NULL)
5040 {
5041 /* Allocate a DynamicZoneAbbrev for this abbreviation */
5042 DynamicZoneAbbrev *dtza;
5043 Size dsize;
5044
5045 dtza = (DynamicZoneAbbrev *) ((char *) tbl + tbl_size);
5046 dtza->tz = NULL;
5047 strcpy(dtza->zone, abbr->zone);
5048
5049 dtoken->type = DYNTZ;
5050 /* value is offset from table start to DynamicZoneAbbrev */
5051 dtoken->value = (int32) tbl_size;
5052
5053 dsize = offsetof(DynamicZoneAbbrev, zone) +
5054 strlen(abbr->zone) + 1;
5055 tbl_size += MAXALIGN(dsize);
5056 }
5057 else
5058 {
5059 dtoken->type = abbr->is_dst ? DTZ : TZ;
5060 dtoken->value = abbr->offset;
5061 }
5062 }
5063
5064 /* Assert the two loops above agreed on size calculations */
5065 Assert(tbl->tblsize == tbl_size);
5066
5067 /* Check the ordering, if testing */
5068 Assert(CheckDateTokenTable("timezone abbreviations", tbl->abbrevs, n));
5069
5070 return tbl;
5071}
#define MAXALIGN(LEN)
Definition: c.h:815
size_t Size
Definition: c.h:615
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:636
#define TZ
Definition: datetime.h:95
#define DTZ
Definition: datetime.h:96
#define DYNTZ
Definition: datetime.h:97
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char zone[FLEXIBLE_ARRAY_MEMBER]
Definition: datetime.h:227
datetkn abbrevs[FLEXIBLE_ARRAY_MEMBER]
Definition: datetime.h:219
char token[TOKMAXLEN+1]
Definition: datetime.h:209
int32 value
Definition: datetime.h:211
char type
Definition: datetime.h:210
char * zone
Definition: tzparser.h:27
int offset
Definition: tzparser.h:29
char * abbrev
Definition: tzparser.h:26
bool is_dst
Definition: tzparser.h:30
Definition: zic.c:99

References tzEntry::abbrev, TimeZoneAbbrevTable::abbrevs, Assert(), CheckDateTokenTable(), DTZ, DYNTZ, guc_malloc(), i, tzEntry::is_dst, LOG, MAXALIGN, TimeZoneAbbrevTable::numabbrevs, tzEntry::offset, strlcpy(), TimeZoneAbbrevTable::tblsize, datetkn::token, TOKMAXLEN, datetkn::type, TZ, DynamicZoneAbbrev::tz, datetkn::value, DynamicZoneAbbrev::zone, and tzEntry::zone.

Referenced by load_tzoffsets().

◆ date2j()

int date2j ( int  year,
int  month,
int  day 
)

Definition at line 296 of file datetime.c.

297{
298 int julian;
299 int century;
300
301 if (month > 2)
302 {
303 month += 1;
304 year += 4800;
305 }
306 else
307 {
308 month += 13;
309 year += 4799;
310 }
311
312 century = year / 100;
313 julian = year * 365 - 32167;
314 julian += year / 4 - century + century / 4;
315 julian += 7834 * month / 256 + day;
316
317 return julian;
318} /* date2j() */

Referenced by CheckDateTokenTables(), date2isoweek(), date2isoyear(), date2isoyearday(), date_in(), DCH_to_char(), DecodeDateTime(), DetermineTimeZoneOffsetInternal(), EncodeDateTime(), extract_date(), GetSQLCurrentDate(), isoweek2j(), make_date(), make_timestamp_internal(), parse_datetime(), PGTYPESdate_dayofweek(), PGTYPESdate_defmt_asc(), PGTYPESdate_fmt_asc(), PGTYPESdate_from_asc(), PGTYPESdate_julmdy(), PGTYPESdate_mdyjul(), PGTYPESdate_to_asc(), PGTYPESdate_today(), timestamp2date_safe(), timestamp2tm(), timestamp_part_common(), timestamp_pl_interval(), timestamp_to_char(), timestamptz2date_safe(), timestamptz_part_common(), timestamptz_pl_interval_internal(), timestamptz_to_char(), tm2timestamp(), to_date(), and ValidateDate().

◆ datebsearch()

static const datetkn * datebsearch ( const char *  key,
const datetkn base,
int  nel 
)
static

Definition at line 4275 of file datetime.c.

4276{
4277 if (nel > 0)
4278 {
4279 const datetkn *last = base + nel - 1,
4280 *position;
4281 int result;
4282
4283 while (last >= base)
4284 {
4285 position = base + ((last - base) >> 1);
4286 /* precheck the first character for a bit of extra speed */
4287 result = (int) key[0] - (int) position->token[0];
4288 if (result == 0)
4289 {
4290 /* use strncmp so that we match truncated tokens */
4291 result = strncmp(key, position->token, TOKMAXLEN);
4292 if (result == 0)
4293 return position;
4294 }
4295 if (result < 0)
4296 last = position - 1;
4297 else
4298 base = position + 1;
4299 }
4300 }
4301 return NULL;
4302}

References sort-test::key, and TOKMAXLEN.

Referenced by DecodeSpecial(), DecodeTimezoneAbbrev(), DecodeTimezoneAbbrevPrefix(), DecodeUnits(), and ParseDateTime().

◆ DateTimeParseError()

void DateTimeParseError ( int  dterr,
DateTimeErrorExtra extra,
const char *  str,
const char *  datatype,
Node escontext 
)

Definition at line 4214 of file datetime.c.

4217{
4218 switch (dterr)
4219 {
4221 errsave(escontext,
4222 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
4223 errmsg("date/time field value out of range: \"%s\"",
4224 str)));
4225 break;
4227 /* <nanny>same as above, but add hint about DateStyle</nanny> */
4228 errsave(escontext,
4229 (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
4230 errmsg("date/time field value out of range: \"%s\"",
4231 str),
4232 errhint("Perhaps you need a different \"DateStyle\" setting.")));
4233 break;
4235 errsave(escontext,
4236 (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
4237 errmsg("interval field value out of range: \"%s\"",
4238 str)));
4239 break;
4241 errsave(escontext,
4242 (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
4243 errmsg("time zone displacement out of range: \"%s\"",
4244 str)));
4245 break;
4246 case DTERR_BAD_TIMEZONE:
4247 errsave(escontext,
4248 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4249 errmsg("time zone \"%s\" not recognized",
4250 extra->dtee_timezone)));
4251 break;
4253 errsave(escontext,
4254 (errcode(ERRCODE_CONFIG_FILE_ERROR),
4255 errmsg("time zone \"%s\" not recognized",
4256 extra->dtee_timezone),
4257 errdetail("This time zone name appears in the configuration file for time zone abbreviation \"%s\".",
4258 extra->dtee_abbrev)));
4259 break;
4260 case DTERR_BAD_FORMAT:
4261 default:
4262 errsave(escontext,
4263 (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
4264 errmsg("invalid input syntax for type %s: \"%s\"",
4265 datatype, str)));
4266 break;
4267 }
4268}
int errdetail(const char *fmt,...)
Definition: elog.c:1216
int errhint(const char *fmt,...)
Definition: elog.c:1330
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define errsave(context,...)
Definition: elog.h:262
const char * str
#define DTERR_BAD_ZONE_ABBREV
Definition: datetime.h:288
#define DTERR_INTERVAL_OVERFLOW
Definition: datetime.h:285
#define DTERR_BAD_TIMEZONE
Definition: datetime.h:287
#define DTERR_TZDISP_OVERFLOW
Definition: datetime.h:286
#define DTERR_FIELD_OVERFLOW
Definition: datetime.h:283
#define DTERR_MD_FIELD_OVERFLOW
Definition: datetime.h:284
const char * dtee_timezone
Definition: datetime.h:293
const char * dtee_abbrev
Definition: datetime.h:295

References DateTimeErrorExtra::dtee_abbrev, DateTimeErrorExtra::dtee_timezone, DTERR_BAD_FORMAT, DTERR_BAD_TIMEZONE, DTERR_BAD_ZONE_ABBREV, DTERR_FIELD_OVERFLOW, DTERR_INTERVAL_OVERFLOW, DTERR_MD_FIELD_OVERFLOW, DTERR_TZDISP_OVERFLOW, errcode(), errdetail(), errhint(), errmsg(), errsave, and str.

Referenced by date_in(), DecodeTimezoneName(), do_to_timestamp(), interval_in(), pg_timezone_abbrevs_abbrevs(), time_in(), timestamp_in(), timestamptz_in(), and timetz_in().

◆ DecodeDate()

static int DecodeDate ( char *  str,
int  fmask,
int *  tmask,
bool *  is2digits,
struct pg_tm tm 
)
static

Definition at line 2451 of file datetime.c.

2453{
2454 fsec_t fsec;
2455 int nf = 0;
2456 int i,
2457 len;
2458 int dterr;
2459 bool haveTextMonth = false;
2460 int type,
2461 val,
2462 dmask = 0;
2463 char *field[MAXDATEFIELDS];
2464
2465 *tmask = 0;
2466
2467 /* parse this string... */
2468 while (*str != '\0' && nf < MAXDATEFIELDS)
2469 {
2470 /* skip field separators */
2471 while (*str != '\0' && !isalnum((unsigned char) *str))
2472 str++;
2473
2474 if (*str == '\0')
2475 return DTERR_BAD_FORMAT; /* end of string after separator */
2476
2477 field[nf] = str;
2478 if (isdigit((unsigned char) *str))
2479 {
2480 while (isdigit((unsigned char) *str))
2481 str++;
2482 }
2483 else if (isalpha((unsigned char) *str))
2484 {
2485 while (isalpha((unsigned char) *str))
2486 str++;
2487 }
2488
2489 /* Just get rid of any non-digit, non-alpha characters... */
2490 if (*str != '\0')
2491 *str++ = '\0';
2492 nf++;
2493 }
2494
2495 /* look first for text fields, since that will be unambiguous month */
2496 for (i = 0; i < nf; i++)
2497 {
2498 if (isalpha((unsigned char) *field[i]))
2499 {
2500 type = DecodeSpecial(i, field[i], &val);
2501 if (type == IGNORE_DTF)
2502 continue;
2503
2504 dmask = DTK_M(type);
2505 switch (type)
2506 {
2507 case MONTH:
2508 tm->tm_mon = val;
2509 haveTextMonth = true;
2510 break;
2511
2512 default:
2513 return DTERR_BAD_FORMAT;
2514 }
2515 if (fmask & dmask)
2516 return DTERR_BAD_FORMAT;
2517
2518 fmask |= dmask;
2519 *tmask |= dmask;
2520
2521 /* mark this field as being completed */
2522 field[i] = NULL;
2523 }
2524 }
2525
2526 /* now pick up remaining numeric fields */
2527 for (i = 0; i < nf; i++)
2528 {
2529 if (field[i] == NULL)
2530 continue;
2531
2532 if ((len = strlen(field[i])) <= 0)
2533 return DTERR_BAD_FORMAT;
2534
2535 dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2536 &dmask, tm,
2537 &fsec, is2digits);
2538 if (dterr)
2539 return dterr;
2540
2541 if (fmask & dmask)
2542 return DTERR_BAD_FORMAT;
2543
2544 fmask |= dmask;
2545 *tmask |= dmask;
2546 }
2547
2548 if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2549 return DTERR_BAD_FORMAT;
2550
2551 /* validation of the field values must wait until ValidateDate() */
2552
2553 return 0;
2554}
static int DecodeNumber(int flen, char *str, bool haveTextMonth, int fmask, int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
Definition: datetime.c:2780
int DecodeSpecial(int field, const char *lowtoken, int *val)
Definition: datetime.c:3246
int32 fsec_t
Definition: timestamp.h:41
#define MAXDATEFIELDS
Definition: datetime.h:202
#define MONTH
Definition: datetime.h:91
#define IGNORE_DTF
Definition: datetime.h:98
#define DTK_M(t)
Definition: datetime.h:187
#define DTK_DATE_M
Definition: datetime.h:191
#define DOY
Definition: datetime.h:105
const void size_t len
int tm_mon
Definition: pgtime.h:40
const char * type

References DecodeNumber(), DecodeSpecial(), DOY, DTERR_BAD_FORMAT, DTK_DATE_M, DTK_M, i, IGNORE_DTF, len, MAXDATEFIELDS, MONTH, str, tm, pg_tm::tm_mon, type, TZ, and val.

Referenced by DecodeDateTime(), and DecodeTimeOnly().

◆ DecodeDateTime()

int DecodeDateTime ( char **  field,
int *  ftype,
int  nf,
int *  dtype,
struct pg_tm tm,
fsec_t fsec,
int *  tzp,
DateTimeErrorExtra extra 
)

Definition at line 997 of file datetime.c.

1000{
1001 int fmask = 0,
1002 tmask,
1003 type;
1004 int ptype = 0; /* "prefix type" for ISO and Julian formats */
1005 int i;
1006 int val;
1007 int dterr;
1008 int mer = HR24;
1009 bool haveTextMonth = false;
1010 bool isjulian = false;
1011 bool is2digits = false;
1012 bool bc = false;
1013 pg_tz *namedTz = NULL;
1014 pg_tz *abbrevTz = NULL;
1015 pg_tz *valtz;
1016 char *abbrev = NULL;
1017 struct pg_tm cur_tm;
1018
1019 /*
1020 * We'll insist on at least all of the date fields, but initialize the
1021 * remaining fields in case they are not set later...
1022 */
1023 *dtype = DTK_DATE;
1024 tm->tm_hour = 0;
1025 tm->tm_min = 0;
1026 tm->tm_sec = 0;
1027 *fsec = 0;
1028 /* don't know daylight savings time status apriori */
1029 tm->tm_isdst = -1;
1030 if (tzp != NULL)
1031 *tzp = 0;
1032
1033 for (i = 0; i < nf; i++)
1034 {
1035 switch (ftype[i])
1036 {
1037 case DTK_DATE:
1038
1039 /*
1040 * Integral julian day with attached time zone? All other
1041 * forms with JD will be separated into distinct fields, so we
1042 * handle just this case here.
1043 */
1044 if (ptype == DTK_JULIAN)
1045 {
1046 char *cp;
1047 int jday;
1048
1049 if (tzp == NULL)
1050 return DTERR_BAD_FORMAT;
1051
1052 errno = 0;
1053 jday = strtoint(field[i], &cp, 10);
1054 if (errno == ERANGE || jday < 0)
1055 return DTERR_FIELD_OVERFLOW;
1056
1057 j2date(jday, &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1058 isjulian = true;
1059
1060 /* Get the time zone from the end of the string */
1061 dterr = DecodeTimezone(cp, tzp);
1062 if (dterr)
1063 return dterr;
1064
1065 tmask = DTK_DATE_M | DTK_TIME_M | DTK_M(TZ);
1066 ptype = 0;
1067 break;
1068 }
1069
1070 /*
1071 * Already have a date? Then this might be a time zone name
1072 * with embedded punctuation (e.g. "America/New_York") or a
1073 * run-together time with trailing time zone (e.g. hhmmss-zz).
1074 * - thomas 2001-12-25
1075 *
1076 * We consider it a time zone if we already have month & day.
1077 * This is to allow the form "mmm dd hhmmss tz year", which
1078 * we've historically accepted.
1079 */
1080 else if (ptype != 0 ||
1081 ((fmask & (DTK_M(MONTH) | DTK_M(DAY))) ==
1082 (DTK_M(MONTH) | DTK_M(DAY))))
1083 {
1084 /* No time zone accepted? Then quit... */
1085 if (tzp == NULL)
1086 return DTERR_BAD_FORMAT;
1087
1088 if (isdigit((unsigned char) *field[i]) || ptype != 0)
1089 {
1090 char *cp;
1091
1092 /*
1093 * Allow a preceding "t" field, but no other units.
1094 */
1095 if (ptype != 0)
1096 {
1097 /* Sanity check; should not fail this test */
1098 if (ptype != DTK_TIME)
1099 return DTERR_BAD_FORMAT;
1100 ptype = 0;
1101 }
1102
1103 /*
1104 * Starts with a digit but we already have a time
1105 * field? Then we are in trouble with a date and time
1106 * already...
1107 */
1108 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1109 return DTERR_BAD_FORMAT;
1110
1111 if ((cp = strchr(field[i], '-')) == NULL)
1112 return DTERR_BAD_FORMAT;
1113
1114 /* Get the time zone from the end of the string */
1115 dterr = DecodeTimezone(cp, tzp);
1116 if (dterr)
1117 return dterr;
1118 *cp = '\0';
1119
1120 /*
1121 * Then read the rest of the field as a concatenated
1122 * time
1123 */
1124 dterr = DecodeNumberField(strlen(field[i]), field[i],
1125 fmask,
1126 &tmask, tm,
1127 fsec, &is2digits);
1128 if (dterr < 0)
1129 return dterr;
1130
1131 /*
1132 * modify tmask after returning from
1133 * DecodeNumberField()
1134 */
1135 tmask |= DTK_M(TZ);
1136 }
1137 else
1138 {
1139 namedTz = pg_tzset(field[i]);
1140 if (!namedTz)
1141 {
1142 extra->dtee_timezone = field[i];
1143 return DTERR_BAD_TIMEZONE;
1144 }
1145 /* we'll apply the zone setting below */
1146 tmask = DTK_M(TZ);
1147 }
1148 }
1149 else
1150 {
1151 dterr = DecodeDate(field[i], fmask,
1152 &tmask, &is2digits, tm);
1153 if (dterr)
1154 return dterr;
1155 }
1156 break;
1157
1158 case DTK_TIME:
1159
1160 /*
1161 * This might be an ISO time following a "t" field.
1162 */
1163 if (ptype != 0)
1164 {
1165 /* Sanity check; should not fail this test */
1166 if (ptype != DTK_TIME)
1167 return DTERR_BAD_FORMAT;
1168 ptype = 0;
1169 }
1170 dterr = DecodeTime(field[i], fmask, INTERVAL_FULL_RANGE,
1171 &tmask, tm, fsec);
1172 if (dterr)
1173 return dterr;
1174
1175 /* check for time overflow */
1177 *fsec))
1178 return DTERR_FIELD_OVERFLOW;
1179 break;
1180
1181 case DTK_TZ:
1182 {
1183 int tz;
1184
1185 if (tzp == NULL)
1186 return DTERR_BAD_FORMAT;
1187
1188 dterr = DecodeTimezone(field[i], &tz);
1189 if (dterr)
1190 return dterr;
1191 *tzp = tz;
1192 tmask = DTK_M(TZ);
1193 }
1194 break;
1195
1196 case DTK_NUMBER:
1197
1198 /*
1199 * Deal with cases where previous field labeled this one
1200 */
1201 if (ptype != 0)
1202 {
1203 char *cp;
1204 int value;
1205
1206 errno = 0;
1207 value = strtoint(field[i], &cp, 10);
1208 if (errno == ERANGE)
1209 return DTERR_FIELD_OVERFLOW;
1210 if (*cp != '.' && *cp != '\0')
1211 return DTERR_BAD_FORMAT;
1212
1213 switch (ptype)
1214 {
1215 case DTK_JULIAN:
1216 /* previous field was a label for "julian date" */
1217 if (value < 0)
1218 return DTERR_FIELD_OVERFLOW;
1219 tmask = DTK_DATE_M;
1221 isjulian = true;
1222
1223 /* fractional Julian Day? */
1224 if (*cp == '.')
1225 {
1226 double time;
1227
1228 dterr = ParseFraction(cp, &time);
1229 if (dterr)
1230 return dterr;
1231 time *= USECS_PER_DAY;
1232 dt2time(time,
1233 &tm->tm_hour, &tm->tm_min,
1234 &tm->tm_sec, fsec);
1235 tmask |= DTK_TIME_M;
1236 }
1237 break;
1238
1239 case DTK_TIME:
1240 /* previous field was "t" for ISO time */
1241 dterr = DecodeNumberField(strlen(field[i]), field[i],
1242 (fmask | DTK_DATE_M),
1243 &tmask, tm,
1244 fsec, &is2digits);
1245 if (dterr < 0)
1246 return dterr;
1247 if (tmask != DTK_TIME_M)
1248 return DTERR_BAD_FORMAT;
1249 break;
1250
1251 default:
1252 return DTERR_BAD_FORMAT;
1253 break;
1254 }
1255
1256 ptype = 0;
1257 *dtype = DTK_DATE;
1258 }
1259 else
1260 {
1261 char *cp;
1262 int flen;
1263
1264 flen = strlen(field[i]);
1265 cp = strchr(field[i], '.');
1266
1267 /* Embedded decimal and no date yet? */
1268 if (cp != NULL && !(fmask & DTK_DATE_M))
1269 {
1270 dterr = DecodeDate(field[i], fmask,
1271 &tmask, &is2digits, tm);
1272 if (dterr)
1273 return dterr;
1274 }
1275 /* embedded decimal and several digits before? */
1276 else if (cp != NULL && flen - strlen(cp) > 2)
1277 {
1278 /*
1279 * Interpret as a concatenated date or time Set the
1280 * type field to allow decoding other fields later.
1281 * Example: 20011223 or 040506
1282 */
1283 dterr = DecodeNumberField(flen, field[i], fmask,
1284 &tmask, tm,
1285 fsec, &is2digits);
1286 if (dterr < 0)
1287 return dterr;
1288 }
1289
1290 /*
1291 * Is this a YMD or HMS specification, or a year number?
1292 * YMD and HMS are required to be six digits or more, so
1293 * if it is 5 digits, it is a year. If it is six or more
1294 * digits, we assume it is YMD or HMS unless no date and
1295 * no time values have been specified. This forces 6+
1296 * digit years to be at the end of the string, or to use
1297 * the ISO date specification.
1298 */
1299 else if (flen >= 6 && (!(fmask & DTK_DATE_M) ||
1300 !(fmask & DTK_TIME_M)))
1301 {
1302 dterr = DecodeNumberField(flen, field[i], fmask,
1303 &tmask, tm,
1304 fsec, &is2digits);
1305 if (dterr < 0)
1306 return dterr;
1307 }
1308 /* otherwise it is a single date/time field... */
1309 else
1310 {
1311 dterr = DecodeNumber(flen, field[i],
1312 haveTextMonth, fmask,
1313 &tmask, tm,
1314 fsec, &is2digits);
1315 if (dterr)
1316 return dterr;
1317 }
1318 }
1319 break;
1320
1321 case DTK_STRING:
1322 case DTK_SPECIAL:
1323 /* timezone abbrevs take precedence over built-in tokens */
1324 dterr = DecodeTimezoneAbbrev(i, field[i],
1325 &type, &val, &valtz, extra);
1326 if (dterr)
1327 return dterr;
1328 if (type == UNKNOWN_FIELD)
1329 type = DecodeSpecial(i, field[i], &val);
1330 if (type == IGNORE_DTF)
1331 continue;
1332
1333 tmask = DTK_M(type);
1334 switch (type)
1335 {
1336 case RESERV:
1337 switch (val)
1338 {
1339 case DTK_NOW:
1340 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1341 *dtype = DTK_DATE;
1342 GetCurrentTimeUsec(tm, fsec, tzp);
1343 break;
1344
1345 case DTK_YESTERDAY:
1346 tmask = DTK_DATE_M;
1347 *dtype = DTK_DATE;
1348 GetCurrentDateTime(&cur_tm);
1349 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) - 1,
1350 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1351 break;
1352
1353 case DTK_TODAY:
1354 tmask = DTK_DATE_M;
1355 *dtype = DTK_DATE;
1356 GetCurrentDateTime(&cur_tm);
1357 tm->tm_year = cur_tm.tm_year;
1358 tm->tm_mon = cur_tm.tm_mon;
1359 tm->tm_mday = cur_tm.tm_mday;
1360 break;
1361
1362 case DTK_TOMORROW:
1363 tmask = DTK_DATE_M;
1364 *dtype = DTK_DATE;
1365 GetCurrentDateTime(&cur_tm);
1366 j2date(date2j(cur_tm.tm_year, cur_tm.tm_mon, cur_tm.tm_mday) + 1,
1367 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
1368 break;
1369
1370 case DTK_ZULU:
1371 tmask = (DTK_TIME_M | DTK_M(TZ));
1372 *dtype = DTK_DATE;
1373 tm->tm_hour = 0;
1374 tm->tm_min = 0;
1375 tm->tm_sec = 0;
1376 if (tzp != NULL)
1377 *tzp = 0;
1378 break;
1379
1380 case DTK_EPOCH:
1381 case DTK_LATE:
1382 case DTK_EARLY:
1383 tmask = (DTK_DATE_M | DTK_TIME_M | DTK_M(TZ));
1384 *dtype = val;
1385 /* caller ignores tm for these dtype codes */
1386 break;
1387
1388 default:
1389 elog(ERROR, "unrecognized RESERV datetime token: %d",
1390 val);
1391 }
1392
1393 break;
1394
1395 case MONTH:
1396
1397 /*
1398 * already have a (numeric) month? then see if we can
1399 * substitute...
1400 */
1401 if ((fmask & DTK_M(MONTH)) && !haveTextMonth &&
1402 !(fmask & DTK_M(DAY)) && tm->tm_mon >= 1 &&
1403 tm->tm_mon <= 31)
1404 {
1405 tm->tm_mday = tm->tm_mon;
1406 tmask = DTK_M(DAY);
1407 }
1408 haveTextMonth = true;
1409 tm->tm_mon = val;
1410 break;
1411
1412 case DTZMOD:
1413
1414 /*
1415 * daylight savings time modifier (solves "MET DST"
1416 * syntax)
1417 */
1418 tmask |= DTK_M(DTZ);
1419 tm->tm_isdst = 1;
1420 if (tzp == NULL)
1421 return DTERR_BAD_FORMAT;
1422 *tzp -= val;
1423 break;
1424
1425 case DTZ:
1426
1427 /*
1428 * set mask for TZ here _or_ check for DTZ later when
1429 * getting default timezone
1430 */
1431 tmask |= DTK_M(TZ);
1432 tm->tm_isdst = 1;
1433 if (tzp == NULL)
1434 return DTERR_BAD_FORMAT;
1435 *tzp = -val;
1436 break;
1437
1438 case TZ:
1439 tm->tm_isdst = 0;
1440 if (tzp == NULL)
1441 return DTERR_BAD_FORMAT;
1442 *tzp = -val;
1443 break;
1444
1445 case DYNTZ:
1446 tmask |= DTK_M(TZ);
1447 if (tzp == NULL)
1448 return DTERR_BAD_FORMAT;
1449 /* we'll determine the actual offset later */
1450 abbrevTz = valtz;
1451 abbrev = field[i];
1452 break;
1453
1454 case AMPM:
1455 mer = val;
1456 break;
1457
1458 case ADBC:
1459 bc = (val == BC);
1460 break;
1461
1462 case DOW:
1463 tm->tm_wday = val;
1464 break;
1465
1466 case UNITS:
1467 tmask = 0;
1468 /* reject consecutive unhandled units */
1469 if (ptype != 0)
1470 return DTERR_BAD_FORMAT;
1471 ptype = val;
1472 break;
1473
1474 case ISOTIME:
1475
1476 /*
1477 * This is a filler field "t" indicating that the next
1478 * field is time. Try to verify that this is sensible.
1479 */
1480 tmask = 0;
1481
1482 /* No preceding date? Then quit... */
1483 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1484 return DTERR_BAD_FORMAT;
1485
1486 /* reject consecutive unhandled units */
1487 if (ptype != 0)
1488 return DTERR_BAD_FORMAT;
1489 ptype = val;
1490 break;
1491
1492 case UNKNOWN_FIELD:
1493
1494 /*
1495 * Before giving up and declaring error, check to see
1496 * if it is an all-alpha timezone name.
1497 */
1498 namedTz = pg_tzset(field[i]);
1499 if (!namedTz)
1500 return DTERR_BAD_FORMAT;
1501 /* we'll apply the zone setting below */
1502 tmask = DTK_M(TZ);
1503 break;
1504
1505 default:
1506 return DTERR_BAD_FORMAT;
1507 }
1508 break;
1509
1510 default:
1511 return DTERR_BAD_FORMAT;
1512 }
1513
1514 if (tmask & fmask)
1515 return DTERR_BAD_FORMAT;
1516 fmask |= tmask;
1517 } /* end loop over fields */
1518
1519 /* reject if prefix type appeared and was never handled */
1520 if (ptype != 0)
1521 return DTERR_BAD_FORMAT;
1522
1523 /* do additional checking for normal date specs (but not "infinity" etc) */
1524 if (*dtype == DTK_DATE)
1525 {
1526 /* do final checking/adjustment of Y/M/D fields */
1527 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
1528 if (dterr)
1529 return dterr;
1530
1531 /* handle AM/PM */
1532 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
1533 return DTERR_FIELD_OVERFLOW;
1534 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
1535 tm->tm_hour = 0;
1536 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
1537 tm->tm_hour += HOURS_PER_DAY / 2;
1538
1539 /* check for incomplete input */
1540 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
1541 {
1542 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1543 return 1;
1544 return DTERR_BAD_FORMAT;
1545 }
1546
1547 /*
1548 * If we had a full timezone spec, compute the offset (we could not do
1549 * it before, because we need the date to resolve DST status).
1550 */
1551 if (namedTz != NULL)
1552 {
1553 /* daylight savings time modifier disallowed with full TZ */
1554 if (fmask & DTK_M(DTZMOD))
1555 return DTERR_BAD_FORMAT;
1556
1557 *tzp = DetermineTimeZoneOffset(tm, namedTz);
1558 }
1559
1560 /*
1561 * Likewise, if we had a dynamic timezone abbreviation, resolve it
1562 * now.
1563 */
1564 if (abbrevTz != NULL)
1565 {
1566 /* daylight savings time modifier disallowed with dynamic TZ */
1567 if (fmask & DTK_M(DTZMOD))
1568 return DTERR_BAD_FORMAT;
1569
1570 *tzp = DetermineTimeZoneAbbrevOffset(tm, abbrev, abbrevTz);
1571 }
1572
1573 /* timezone not specified? then use session timezone */
1574 if (tzp != NULL && !(fmask & DTK_M(TZ)))
1575 {
1576 /*
1577 * daylight savings time modifier but no standard timezone? then
1578 * error
1579 */
1580 if (fmask & DTK_M(DTZMOD))
1581 return DTERR_BAD_FORMAT;
1582
1584 }
1585 }
1586
1587 return 0;
1588}
static int DecodeDate(char *str, int fmask, int *tmask, bool *is2digits, struct pg_tm *tm)
Definition: datetime.c:2451
static int DecodeNumberField(int len, char *str, int fmask, int *tmask, struct pg_tm *tm, fsec_t *fsec, bool *is2digits)
Definition: datetime.c:2965
static int ParseFraction(char *cp, double *frac)
Definition: datetime.c:690
int DetermineTimeZoneOffset(struct pg_tm *tm, pg_tz *tzp)
Definition: datetime.c:1604
int DecodeTimezoneAbbrev(int field, const char *lowtoken, int *ftype, int *offset, pg_tz **tz, DateTimeErrorExtra *extra)
Definition: datetime.c:3141
static int DecodeTime(char *str, int fmask, int range, int *tmask, struct pg_tm *tm, fsec_t *fsec)
Definition: datetime.c:2725
int ValidateDate(int fmask, bool isjulian, bool is2digits, bool bc, struct pg_tm *tm)
Definition: datetime.c:2561
void j2date(int jd, int *year, int *month, int *day)
Definition: datetime.c:321
void GetCurrentDateTime(struct pg_tm *tm)
Definition: datetime.c:376
int DecodeTimezone(const char *str, int *tzp)
Definition: datetime.c:3057
void GetCurrentTimeUsec(struct pg_tm *tm, fsec_t *fsec, int *tzp)
Definition: datetime.c:397
int DetermineTimeZoneAbbrevOffset(struct pg_tm *tm, const char *abbr, pg_tz *tzp)
Definition: datetime.c:1765
void dt2time(Timestamp jd, int *hour, int *min, int *sec, fsec_t *fsec)
Definition: timestamp.c:1883
#define HOURS_PER_DAY
Definition: timestamp.h:118
bool time_overflows(int hour, int min, int sec, fsec_t fsec)
Definition: date.c:1523
#define ERROR
Definition: elog.h:39
#define DTK_TOMORROW
Definition: datetime.h:156
#define DTK_EPOCH
Definition: datetime.h:152
#define DTK_SPECIAL
Definition: datetime.h:149
#define AMPM
Definition: datetime.h:99
#define DTK_TIME
Definition: datetime.h:145
#define UNKNOWN_FIELD
Definition: datetime.h:124
#define PM
Definition: datetime.h:72
#define DTK_NUMBER
Definition: datetime.h:141
#define DTK_STRING
Definition: datetime.h:142
#define DTK_JULIAN
Definition: datetime.h:173
#define DTK_TIME_M
Definition: datetime.h:192
#define DAY
Definition: datetime.h:93
#define ADBC
Definition: datetime.h:108
#define DTK_LATE
Definition: datetime.h:151
#define DTK_DATE
Definition: datetime.h:144
#define RESERV
Definition: datetime.h:90
#define BC
Definition: datetime.h:76
#define HR24
Definition: datetime.h:73
#define DTK_EARLY
Definition: datetime.h:150
#define DTZMOD
Definition: datetime.h:122
#define DTK_TZ
Definition: datetime.h:146
#define DOW
Definition: datetime.h:106
#define ISOTIME
Definition: datetime.h:115
#define AM
Definition: datetime.h:71
#define DTK_YESTERDAY
Definition: datetime.h:154
#define DTK_ZULU
Definition: datetime.h:157
#define UNITS
Definition: datetime.h:107
#define DTK_TODAY
Definition: datetime.h:155
#define DTK_NOW
Definition: datetime.h:153
pg_tz * pg_tzset(const char *tzname)
Definition: pgtz.c:234
PGDLLIMPORT pg_tz * session_timezone
Definition: pgtz.c:28
int strtoint(const char *restrict str, char **restrict endptr, int base)
Definition: string.c:50
Definition: pgtime.h:35
int tm_hour
Definition: pgtime.h:38
int tm_mday
Definition: pgtime.h:39
int tm_min
Definition: pgtime.h:37
int tm_wday
Definition: pgtime.h:42
int tm_isdst
Definition: pgtime.h:44
int tm_year
Definition: pgtime.h:41
Definition: pgtz.h:66
#define INTERVAL_FULL_RANGE
Definition: timestamp.h:76

References ADBC, AM, AMPM, BC, date2j(), DAY, DecodeDate(), DecodeNumber(), DecodeNumberField(), DecodeSpecial(), DecodeTime(), DecodeTimezone(), DecodeTimezoneAbbrev(), DetermineTimeZoneAbbrevOffset(), DetermineTimeZoneOffset(), DOW, dt2time(), DateTimeErrorExtra::dtee_timezone, DTERR_BAD_FORMAT, DTERR_BAD_TIMEZONE, DTERR_FIELD_OVERFLOW, DTK_DATE, DTK_DATE_M, DTK_EARLY, DTK_EPOCH, DTK_JULIAN, DTK_LATE, DTK_M, DTK_NOW, DTK_NUMBER, DTK_SPECIAL, DTK_STRING, DTK_TIME, DTK_TIME_M, DTK_TODAY, DTK_TOMORROW, DTK_TZ, DTK_YESTERDAY, DTK_ZULU, DTZ, DTZMOD, DYNTZ, elog, ERROR, GetCurrentDateTime(), GetCurrentTimeUsec(), HOURS_PER_DAY, HR24, i, IGNORE_DTF, INTERVAL_FULL_RANGE, ISOTIME, j2date(), MONTH, ParseFraction(), pg_tzset(), PM, RESERV, session_timezone, strtoint(), time_overflows(), tm, pg_tm::tm_hour, pg_tm::tm_isdst, pg_tm::tm_mday, pg_tm::tm_min, pg_tm::tm_mon, pg_tm::tm_sec, pg_tm::tm_wday, pg_tm::tm_year, type, TZ, UNITS, UNKNOWN_FIELD, USECS_PER_DAY, val, ValidateDate(), and value.

Referenced by check_recovery_target_time(), date_in(), PGTYPESdate_from_asc(), PGTYPEStimestamp_from_asc(), timestamp_in(), and timestamptz_in().

◆ DecodeInterval()

int DecodeInterval ( char **  field,
int *  ftype,
int  nf,
int  range,
int *  dtype,
struct pg_itm_in itm_in 
)

Definition at line 3486 of file datetime.c.

3488{
3489 bool force_negative = false;
3490 bool is_before = false;
3491 bool parsing_unit_val = false;
3492 char *cp;
3493 int fmask = 0,
3494 tmask,
3495 type,
3496 uval;
3497 int i;
3498 int dterr;
3499 int64 val;
3500 double fval;
3501
3502 *dtype = DTK_DELTA;
3503 type = IGNORE_DTF;
3504 ClearPgItmIn(itm_in);
3505
3506 /*----------
3507 * The SQL standard defines the interval literal
3508 * '-1 1:00:00'
3509 * to mean "negative 1 days and negative 1 hours", while Postgres
3510 * traditionally treats this as meaning "negative 1 days and positive
3511 * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3512 * to all fields if there are no other explicit signs.
3513 *
3514 * We leave the signs alone if there are additional explicit signs.
3515 * This protects us against misinterpreting postgres-style dump output,
3516 * since the postgres-style output code has always put an explicit sign on
3517 * all fields following a negative field. But note that SQL-spec output
3518 * is ambiguous and can be misinterpreted on load! (So it's best practice
3519 * to dump in postgres style, not SQL style.)
3520 *----------
3521 */
3522 if (IntervalStyle == INTSTYLE_SQL_STANDARD && nf > 0 && *field[0] == '-')
3523 {
3524 force_negative = true;
3525 /* Check for additional explicit signs */
3526 for (i = 1; i < nf; i++)
3527 {
3528 if (*field[i] == '-' || *field[i] == '+')
3529 {
3530 force_negative = false;
3531 break;
3532 }
3533 }
3534 }
3535
3536 /* read through list backwards to pick up units before values */
3537 for (i = nf - 1; i >= 0; i--)
3538 {
3539 switch (ftype[i])
3540 {
3541 case DTK_TIME:
3542 dterr = DecodeTimeForInterval(field[i], fmask, range,
3543 &tmask, itm_in);
3544 if (dterr)
3545 return dterr;
3546 if (force_negative &&
3547 itm_in->tm_usec > 0)
3548 itm_in->tm_usec = -itm_in->tm_usec;
3549 type = DTK_DAY;
3550 parsing_unit_val = false;
3551 break;
3552
3553 case DTK_TZ:
3554
3555 /*
3556 * Timezone means a token with a leading sign character and at
3557 * least one digit; there could be ':', '.', '-' embedded in
3558 * it as well.
3559 */
3560 Assert(*field[i] == '-' || *field[i] == '+');
3561
3562 /*
3563 * Check for signed hh:mm or hh:mm:ss. If so, process exactly
3564 * like DTK_TIME case above, plus handling the sign.
3565 */
3566 if (strchr(field[i] + 1, ':') != NULL &&
3567 DecodeTimeForInterval(field[i] + 1, fmask, range,
3568 &tmask, itm_in) == 0)
3569 {
3570 if (*field[i] == '-')
3571 {
3572 /* flip the sign on time field */
3573 if (itm_in->tm_usec == PG_INT64_MIN)
3574 return DTERR_FIELD_OVERFLOW;
3575 itm_in->tm_usec = -itm_in->tm_usec;
3576 }
3577
3578 if (force_negative &&
3579 itm_in->tm_usec > 0)
3580 itm_in->tm_usec = -itm_in->tm_usec;
3581
3582 /*
3583 * Set the next type to be a day, if units are not
3584 * specified. This handles the case of '1 +02:03' since we
3585 * are reading right to left.
3586 */
3587 type = DTK_DAY;
3588 parsing_unit_val = false;
3589 break;
3590 }
3591
3592 /*
3593 * Otherwise, fall through to DTK_NUMBER case, which can
3594 * handle signed float numbers and signed year-month values.
3595 */
3596
3597 /* FALLTHROUGH */
3598
3599 case DTK_DATE:
3600 case DTK_NUMBER:
3601 if (type == IGNORE_DTF)
3602 {
3603 /* use typmod to decide what rightmost field is */
3604 switch (range)
3605 {
3606 case INTERVAL_MASK(YEAR):
3607 type = DTK_YEAR;
3608 break;
3609 case INTERVAL_MASK(MONTH):
3611 type = DTK_MONTH;
3612 break;
3613 case INTERVAL_MASK(DAY):
3614 type = DTK_DAY;
3615 break;
3616 case INTERVAL_MASK(HOUR):
3618 type = DTK_HOUR;
3619 break;
3620 case INTERVAL_MASK(MINUTE):
3623 type = DTK_MINUTE;
3624 break;
3625 case INTERVAL_MASK(SECOND):
3629 type = DTK_SECOND;
3630 break;
3631 default:
3632 type = DTK_SECOND;
3633 break;
3634 }
3635 }
3636
3637 errno = 0;
3638 val = strtoi64(field[i], &cp, 10);
3639 if (errno == ERANGE)
3640 return DTERR_FIELD_OVERFLOW;
3641
3642 if (*cp == '-')
3643 {
3644 /* SQL "years-months" syntax */
3645 int val2;
3646
3647 val2 = strtoint(cp + 1, &cp, 10);
3648 if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
3649 return DTERR_FIELD_OVERFLOW;
3650 if (*cp != '\0')
3651 return DTERR_BAD_FORMAT;
3652 type = DTK_MONTH;
3653 if (*field[i] == '-')
3654 val2 = -val2;
3656 return DTERR_FIELD_OVERFLOW;
3657 if (pg_add_s64_overflow(val, val2, &val))
3658 return DTERR_FIELD_OVERFLOW;
3659 fval = 0;
3660 }
3661 else if (*cp == '.')
3662 {
3663 dterr = ParseFraction(cp, &fval);
3664 if (dterr)
3665 return dterr;
3666 if (*field[i] == '-')
3667 fval = -fval;
3668 }
3669 else if (*cp == '\0')
3670 fval = 0;
3671 else
3672 return DTERR_BAD_FORMAT;
3673
3674 tmask = 0; /* DTK_M(type); */
3675
3676 if (force_negative)
3677 {
3678 /* val and fval should be of same sign, but test anyway */
3679 if (val > 0)
3680 val = -val;
3681 if (fval > 0)
3682 fval = -fval;
3683 }
3684
3685 switch (type)
3686 {
3687 case DTK_MICROSEC:
3688 if (!AdjustMicroseconds(val, fval, 1, itm_in))
3689 return DTERR_FIELD_OVERFLOW;
3690 tmask = DTK_M(MICROSECOND);
3691 break;
3692
3693 case DTK_MILLISEC:
3694 if (!AdjustMicroseconds(val, fval, 1000, itm_in))
3695 return DTERR_FIELD_OVERFLOW;
3696 tmask = DTK_M(MILLISECOND);
3697 break;
3698
3699 case DTK_SECOND:
3700 if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
3701 return DTERR_FIELD_OVERFLOW;
3702
3703 /*
3704 * If any subseconds were specified, consider this
3705 * microsecond and millisecond input as well.
3706 */
3707 if (fval == 0)
3708 tmask = DTK_M(SECOND);
3709 else
3710 tmask = DTK_ALL_SECS_M;
3711 break;
3712
3713 case DTK_MINUTE:
3714 if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3715 return DTERR_FIELD_OVERFLOW;
3716 tmask = DTK_M(MINUTE);
3717 break;
3718
3719 case DTK_HOUR:
3720 if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3721 return DTERR_FIELD_OVERFLOW;
3722 tmask = DTK_M(HOUR);
3723 type = DTK_DAY; /* set for next field */
3724 break;
3725
3726 case DTK_DAY:
3727 if (!AdjustDays(val, 1, itm_in) ||
3728 !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3729 return DTERR_FIELD_OVERFLOW;
3730 tmask = DTK_M(DAY);
3731 break;
3732
3733 case DTK_WEEK:
3734 if (!AdjustDays(val, 7, itm_in) ||
3735 !AdjustFractDays(fval, 7, itm_in))
3736 return DTERR_FIELD_OVERFLOW;
3737 tmask = DTK_M(WEEK);
3738 break;
3739
3740 case DTK_MONTH:
3741 if (!AdjustMonths(val, itm_in) ||
3742 !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3743 return DTERR_FIELD_OVERFLOW;
3744 tmask = DTK_M(MONTH);
3745 break;
3746
3747 case DTK_YEAR:
3748 if (!AdjustYears(val, 1, itm_in) ||
3749 !AdjustFractYears(fval, 1, itm_in))
3750 return DTERR_FIELD_OVERFLOW;
3751 tmask = DTK_M(YEAR);
3752 break;
3753
3754 case DTK_DECADE:
3755 if (!AdjustYears(val, 10, itm_in) ||
3756 !AdjustFractYears(fval, 10, itm_in))
3757 return DTERR_FIELD_OVERFLOW;
3758 tmask = DTK_M(DECADE);
3759 break;
3760
3761 case DTK_CENTURY:
3762 if (!AdjustYears(val, 100, itm_in) ||
3763 !AdjustFractYears(fval, 100, itm_in))
3764 return DTERR_FIELD_OVERFLOW;
3765 tmask = DTK_M(CENTURY);
3766 break;
3767
3768 case DTK_MILLENNIUM:
3769 if (!AdjustYears(val, 1000, itm_in) ||
3770 !AdjustFractYears(fval, 1000, itm_in))
3771 return DTERR_FIELD_OVERFLOW;
3772 tmask = DTK_M(MILLENNIUM);
3773 break;
3774
3775 default:
3776 return DTERR_BAD_FORMAT;
3777 }
3778 parsing_unit_val = false;
3779 break;
3780
3781 case DTK_STRING:
3782 case DTK_SPECIAL:
3783 /* reject consecutive unhandled units */
3784 if (parsing_unit_val)
3785 return DTERR_BAD_FORMAT;
3786 type = DecodeUnits(i, field[i], &uval);
3787 if (type == UNKNOWN_FIELD)
3788 type = DecodeSpecial(i, field[i], &uval);
3789 if (type == IGNORE_DTF)
3790 continue;
3791
3792 tmask = 0; /* DTK_M(type); */
3793 switch (type)
3794 {
3795 case UNITS:
3796 type = uval;
3797 parsing_unit_val = true;
3798 break;
3799
3800 case AGO:
3801
3802 /*
3803 * "ago" is only allowed to appear at the end of the
3804 * interval.
3805 */
3806 if (i != nf - 1)
3807 return DTERR_BAD_FORMAT;
3808 is_before = true;
3809 type = uval;
3810 break;
3811
3812 case RESERV:
3813 tmask = (DTK_DATE_M | DTK_TIME_M);
3814
3815 /*
3816 * Only reserved words corresponding to infinite
3817 * intervals are accepted.
3818 */
3819 if (uval != DTK_LATE && uval != DTK_EARLY)
3820 return DTERR_BAD_FORMAT;
3821
3822 /*
3823 * Infinity cannot be followed by anything else. We
3824 * could allow "ago" to reverse the sign of infinity
3825 * but using signed infinity is more intuitive.
3826 */
3827 if (i != nf - 1)
3828 return DTERR_BAD_FORMAT;
3829
3830 *dtype = uval;
3831 break;
3832
3833 default:
3834 return DTERR_BAD_FORMAT;
3835 }
3836 break;
3837
3838 default:
3839 return DTERR_BAD_FORMAT;
3840 }
3841
3842 if (tmask & fmask)
3843 return DTERR_BAD_FORMAT;
3844 fmask |= tmask;
3845 }
3846
3847 /* ensure that at least one time field has been found */
3848 if (fmask == 0)
3849 return DTERR_BAD_FORMAT;
3850
3851 /* reject if unit appeared and was never handled */
3852 if (parsing_unit_val)
3853 return DTERR_BAD_FORMAT;
3854
3855 /* finally, AGO negates everything */
3856 if (is_before)
3857 {
3858 if (itm_in->tm_usec == PG_INT64_MIN ||
3859 itm_in->tm_mday == INT_MIN ||
3860 itm_in->tm_mon == INT_MIN ||
3861 itm_in->tm_year == INT_MIN)
3862 return DTERR_FIELD_OVERFLOW;
3863
3864 itm_in->tm_usec = -itm_in->tm_usec;
3865 itm_in->tm_mday = -itm_in->tm_mday;
3866 itm_in->tm_mon = -itm_in->tm_mon;
3867 itm_in->tm_year = -itm_in->tm_year;
3868 }
3869
3870 return 0;
3871}
int DecodeUnits(int field, const char *lowtoken, int *val)
Definition: datetime.c:4169
static bool AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:643
static bool AdjustFractYears(double frac, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:611
static bool AdjustMicroseconds(int64 val, double fval, int64 scale, struct pg_itm_in *itm_in)
Definition: datetime.c:628
static int DecodeTimeForInterval(char *str, int fmask, int range, int *tmask, struct pg_itm_in *itm_in)
Definition: datetime.c:2754
static bool AdjustYears(int64 val, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:671
static bool AdjustMonths(int64 val, struct pg_itm_in *itm_in)
Definition: datetime.c:659
static bool AdjustFractDays(double frac, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:579
static void ClearPgItmIn(struct pg_itm_in *itm_in)
Definition: datetime.c:3462
#define PG_INT64_MIN
Definition: c.h:601
#define USECS_PER_HOUR
Definition: timestamp.h:132
#define USECS_PER_SEC
Definition: timestamp.h:134
#define USECS_PER_MINUTE
Definition: timestamp.h:133
#define DAYS_PER_MONTH
Definition: timestamp.h:116
int IntervalStyle
Definition: globals.c:127
#define MILLENNIUM
Definition: datetime.h:120
#define DTK_DECADE
Definition: datetime.h:168
#define DTK_SECOND
Definition: datetime.h:160
#define DTK_DELTA
Definition: datetime.h:159
#define MICROSECOND
Definition: datetime.h:104
#define HOUR
Definition: datetime.h:100
#define WEEK
Definition: datetime.h:117
#define DECADE
Definition: datetime.h:118
#define YEAR
Definition: datetime.h:92
#define DTK_CENTURY
Definition: datetime.h:169
#define MILLISECOND
Definition: datetime.h:103
#define DTK_DAY
Definition: datetime.h:163
#define CENTURY
Definition: datetime.h:119
#define DTK_MILLENNIUM
Definition: datetime.h:170
#define SECOND
Definition: datetime.h:102
#define DTK_ALL_SECS_M
Definition: datetime.h:190
#define DTK_HOUR
Definition: datetime.h:162
#define DTK_WEEK
Definition: datetime.h:164
#define MINUTE
Definition: datetime.h:101
#define DTK_MICROSEC
Definition: datetime.h:172
#define DTK_YEAR
Definition: datetime.h:167
#define AGO
Definition: datetime.h:110
#define DTK_MILLISEC
Definition: datetime.h:171
#define DTK_MONTH
Definition: datetime.h:165
#define DTK_MINUTE
Definition: datetime.h:161
static bool pg_mul_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:293
#define INTSTYLE_SQL_STANDARD
Definition: miscadmin.h:259
static struct cvec * range(struct vars *v, chr a, chr b, int cases)
Definition: regc_locale.c:412
#define INTERVAL_MASK(b)
Definition: timestamp.h:73

References AdjustDays(), AdjustFractDays(), AdjustFractMicroseconds(), AdjustFractYears(), AdjustMicroseconds(), AdjustMonths(), AdjustYears(), AGO, Assert(), CENTURY, ClearPgItmIn(), DAY, DAYS_PER_MONTH, DECADE, DecodeSpecial(), DecodeTimeForInterval(), DecodeUnits(), DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_ALL_SECS_M, DTK_CENTURY, DTK_DATE, DTK_DATE_M, DTK_DAY, DTK_DECADE, DTK_DELTA, DTK_EARLY, DTK_HOUR, DTK_LATE, DTK_M, DTK_MICROSEC, DTK_MILLENNIUM, DTK_MILLISEC, DTK_MINUTE, DTK_MONTH, DTK_NUMBER, DTK_SECOND, DTK_SPECIAL, DTK_STRING, DTK_TIME, DTK_TIME_M, DTK_TZ, DTK_WEEK, DTK_YEAR, HOUR, i, IGNORE_DTF, INTERVAL_MASK, IntervalStyle, INTSTYLE_SQL_STANDARD, MICROSECOND, MILLENNIUM, MILLISECOND, MINUTE, MONTH, MONTHS_PER_YEAR, ParseFraction(), pg_add_s64_overflow(), PG_INT64_MIN, pg_mul_s64_overflow(), range(), RESERV, SECOND, strtoint(), pg_itm_in::tm_mday, pg_itm_in::tm_mon, pg_itm_in::tm_usec, pg_itm_in::tm_year, type, UNITS, UNKNOWN_FIELD, USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, val, WEEK, and YEAR.

Referenced by interval_in().

◆ DecodeISO8601Interval()

int DecodeISO8601Interval ( char *  str,
int *  dtype,
struct pg_itm_in itm_in 
)

Definition at line 3951 of file datetime.c.

3953{
3954 bool datepart = true;
3955 bool havefield = false;
3956
3957 *dtype = DTK_DELTA;
3958 ClearPgItmIn(itm_in);
3959
3960 if (strlen(str) < 2 || str[0] != 'P')
3961 return DTERR_BAD_FORMAT;
3962
3963 str++;
3964 while (*str)
3965 {
3966 char *fieldstart;
3967 int64 val;
3968 double fval;
3969 char unit;
3970 int dterr;
3971
3972 if (*str == 'T') /* T indicates the beginning of the time part */
3973 {
3974 datepart = false;
3975 havefield = false;
3976 str++;
3977 continue;
3978 }
3979
3980 fieldstart = str;
3981 dterr = ParseISO8601Number(str, &str, &val, &fval);
3982 if (dterr)
3983 return dterr;
3984
3985 /*
3986 * Note: we could step off the end of the string here. Code below
3987 * *must* exit the loop if unit == '\0'.
3988 */
3989 unit = *str++;
3990
3991 if (datepart)
3992 {
3993 switch (unit) /* before T: Y M W D */
3994 {
3995 case 'Y':
3996 if (!AdjustYears(val, 1, itm_in) ||
3997 !AdjustFractYears(fval, 1, itm_in))
3998 return DTERR_FIELD_OVERFLOW;
3999 break;
4000 case 'M':
4001 if (!AdjustMonths(val, itm_in) ||
4002 !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
4003 return DTERR_FIELD_OVERFLOW;
4004 break;
4005 case 'W':
4006 if (!AdjustDays(val, 7, itm_in) ||
4007 !AdjustFractDays(fval, 7, itm_in))
4008 return DTERR_FIELD_OVERFLOW;
4009 break;
4010 case 'D':
4011 if (!AdjustDays(val, 1, itm_in) ||
4012 !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
4013 return DTERR_FIELD_OVERFLOW;
4014 break;
4015 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
4016 case '\0':
4017 if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
4018 {
4019 if (!AdjustYears(val / 10000, 1, itm_in) ||
4020 !AdjustMonths((val / 100) % 100, itm_in) ||
4021 !AdjustDays(val % 100, 1, itm_in) ||
4022 !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
4023 return DTERR_FIELD_OVERFLOW;
4024 if (unit == '\0')
4025 return 0;
4026 datepart = false;
4027 havefield = false;
4028 continue;
4029 }
4030 /* Else fall through to extended alternative format */
4031 /* FALLTHROUGH */
4032 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
4033 * Extended */
4034 if (havefield)
4035 return DTERR_BAD_FORMAT;
4036
4037 if (!AdjustYears(val, 1, itm_in) ||
4038 !AdjustFractYears(fval, 1, itm_in))
4039 return DTERR_FIELD_OVERFLOW;
4040 if (unit == '\0')
4041 return 0;
4042 if (unit == 'T')
4043 {
4044 datepart = false;
4045 havefield = false;
4046 continue;
4047 }
4048
4049 dterr = ParseISO8601Number(str, &str, &val, &fval);
4050 if (dterr)
4051 return dterr;
4052 if (!AdjustMonths(val, itm_in) ||
4053 !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
4054 return DTERR_FIELD_OVERFLOW;
4055 if (*str == '\0')
4056 return 0;
4057 if (*str == 'T')
4058 {
4059 datepart = false;
4060 havefield = false;
4061 continue;
4062 }
4063 if (*str != '-')
4064 return DTERR_BAD_FORMAT;
4065 str++;
4066
4067 dterr = ParseISO8601Number(str, &str, &val, &fval);
4068 if (dterr)
4069 return dterr;
4070 if (!AdjustDays(val, 1, itm_in) ||
4071 !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
4072 return DTERR_FIELD_OVERFLOW;
4073 if (*str == '\0')
4074 return 0;
4075 if (*str == 'T')
4076 {
4077 datepart = false;
4078 havefield = false;
4079 continue;
4080 }
4081 return DTERR_BAD_FORMAT;
4082 default:
4083 /* not a valid date unit suffix */
4084 return DTERR_BAD_FORMAT;
4085 }
4086 }
4087 else
4088 {
4089 switch (unit) /* after T: H M S */
4090 {
4091 case 'H':
4092 if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
4093 return DTERR_FIELD_OVERFLOW;
4094 break;
4095 case 'M':
4096 if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
4097 return DTERR_FIELD_OVERFLOW;
4098 break;
4099 case 'S':
4100 if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
4101 return DTERR_FIELD_OVERFLOW;
4102 break;
4103 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
4104 if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
4105 {
4106 if (!AdjustMicroseconds(val / 10000, 0, USECS_PER_HOUR, itm_in) ||
4107 !AdjustMicroseconds((val / 100) % 100, 0, USECS_PER_MINUTE, itm_in) ||
4108 !AdjustMicroseconds(val % 100, 0, USECS_PER_SEC, itm_in) ||
4109 !AdjustFractMicroseconds(fval, 1, itm_in))
4110 return DTERR_FIELD_OVERFLOW;
4111 return 0;
4112 }
4113 /* Else fall through to extended alternative format */
4114 /* FALLTHROUGH */
4115 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
4116 * Extended */
4117 if (havefield)
4118 return DTERR_BAD_FORMAT;
4119
4120 if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
4121 return DTERR_FIELD_OVERFLOW;
4122 if (unit == '\0')
4123 return 0;
4124
4125 dterr = ParseISO8601Number(str, &str, &val, &fval);
4126 if (dterr)
4127 return dterr;
4128 if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
4129 return DTERR_FIELD_OVERFLOW;
4130 if (*str == '\0')
4131 return 0;
4132 if (*str != ':')
4133 return DTERR_BAD_FORMAT;
4134 str++;
4135
4136 dterr = ParseISO8601Number(str, &str, &val, &fval);
4137 if (dterr)
4138 return dterr;
4139 if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
4140 return DTERR_FIELD_OVERFLOW;
4141 if (*str == '\0')
4142 return 0;
4143 return DTERR_BAD_FORMAT;
4144
4145 default:
4146 /* not a valid time unit suffix */
4147 return DTERR_BAD_FORMAT;
4148 }
4149 }
4150
4151 havefield = true;
4152 }
4153
4154 return 0;
4155}
static int ISO8601IntegerWidth(char *fieldstart)
Definition: datetime.c:3924
static int ParseISO8601Number(char *str, char **endptr, int64 *ipart, double *fpart)
Definition: datetime.c:3882

References AdjustDays(), AdjustFractDays(), AdjustFractMicroseconds(), AdjustFractYears(), AdjustMicroseconds(), AdjustMonths(), AdjustYears(), ClearPgItmIn(), DAYS_PER_MONTH, DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_DELTA, ISO8601IntegerWidth(), ParseISO8601Number(), str, USECS_PER_DAY, USECS_PER_HOUR, USECS_PER_MINUTE, USECS_PER_SEC, and val.

Referenced by interval_in().

◆ DecodeNumber()

static int DecodeNumber ( int  flen,
char *  str,
bool  haveTextMonth,
int  fmask,
int *  tmask,
struct pg_tm tm,
fsec_t fsec,
bool *  is2digits 
)
static

Definition at line 2780 of file datetime.c.

2782{
2783 int val;
2784 char *cp;
2785 int dterr;
2786
2787 *tmask = 0;
2788
2789 errno = 0;
2790 val = strtoint(str, &cp, 10);
2791 if (errno == ERANGE)
2792 return DTERR_FIELD_OVERFLOW;
2793 if (cp == str)
2794 return DTERR_BAD_FORMAT;
2795
2796 if (*cp == '.')
2797 {
2798 /*
2799 * More than two digits before decimal point? Then could be a date or
2800 * a run-together time: 2001.360 20011225 040506.789
2801 */
2802 if (cp - str > 2)
2803 {
2804 dterr = DecodeNumberField(flen, str,
2805 (fmask | DTK_DATE_M),
2806 tmask, tm,
2807 fsec, is2digits);
2808 if (dterr < 0)
2809 return dterr;
2810 return 0;
2811 }
2812
2813 dterr = ParseFractionalSecond(cp, fsec);
2814 if (dterr)
2815 return dterr;
2816 }
2817 else if (*cp != '\0')
2818 return DTERR_BAD_FORMAT;
2819
2820 /* Special case for day of year */
2821 if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2822 val <= 366)
2823 {
2824 *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2825 tm->tm_yday = val;
2826 /* tm_mon and tm_mday can't actually be set yet ... */
2827 return 0;
2828 }
2829
2830 /* Switch based on what we have so far */
2831 switch (fmask & DTK_DATE_M)
2832 {
2833 case 0:
2834
2835 /*
2836 * Nothing so far; make a decision about what we think the input
2837 * is. There used to be lots of heuristics here, but the
2838 * consensus now is to be paranoid. It *must* be either
2839 * YYYY-MM-DD (with a more-than-two-digit year field), or the
2840 * field order defined by DateOrder.
2841 */
2842 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2843 {
2844 *tmask = DTK_M(YEAR);
2845 tm->tm_year = val;
2846 }
2847 else if (DateOrder == DATEORDER_DMY)
2848 {
2849 *tmask = DTK_M(DAY);
2850 tm->tm_mday = val;
2851 }
2852 else
2853 {
2854 *tmask = DTK_M(MONTH);
2855 tm->tm_mon = val;
2856 }
2857 break;
2858
2859 case (DTK_M(YEAR)):
2860 /* Must be at second field of YY-MM-DD */
2861 *tmask = DTK_M(MONTH);
2862 tm->tm_mon = val;
2863 break;
2864
2865 case (DTK_M(MONTH)):
2866 if (haveTextMonth)
2867 {
2868 /*
2869 * We are at the first numeric field of a date that included a
2870 * textual month name. We want to support the variants
2871 * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2872 * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2873 * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2874 */
2875 if (flen >= 3 || DateOrder == DATEORDER_YMD)
2876 {
2877 *tmask = DTK_M(YEAR);
2878 tm->tm_year = val;
2879 }
2880 else
2881 {
2882 *tmask = DTK_M(DAY);
2883 tm->tm_mday = val;
2884 }
2885 }
2886 else
2887 {
2888 /* Must be at second field of MM-DD-YY */
2889 *tmask = DTK_M(DAY);
2890 tm->tm_mday = val;
2891 }
2892 break;
2893
2894 case (DTK_M(YEAR) | DTK_M(MONTH)):
2895 if (haveTextMonth)
2896 {
2897 /* Need to accept DD-MON-YYYY even in YMD mode */
2898 if (flen >= 3 && *is2digits)
2899 {
2900 /* Guess that first numeric field is day was wrong */
2901 *tmask = DTK_M(DAY); /* YEAR is already set */
2902 tm->tm_mday = tm->tm_year;
2903 tm->tm_year = val;
2904 *is2digits = false;
2905 }
2906 else
2907 {
2908 *tmask = DTK_M(DAY);
2909 tm->tm_mday = val;
2910 }
2911 }
2912 else
2913 {
2914 /* Must be at third field of YY-MM-DD */
2915 *tmask = DTK_M(DAY);
2916 tm->tm_mday = val;
2917 }
2918 break;
2919
2920 case (DTK_M(DAY)):
2921 /* Must be at second field of DD-MM-YY */
2922 *tmask = DTK_M(MONTH);
2923 tm->tm_mon = val;
2924 break;
2925
2926 case (DTK_M(MONTH) | DTK_M(DAY)):
2927 /* Must be at third field of DD-MM-YY or MM-DD-YY */
2928 *tmask = DTK_M(YEAR);
2929 tm->tm_year = val;
2930 break;
2931
2932 case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2933 /* we have all the date, so it must be a time field */
2934 dterr = DecodeNumberField(flen, str, fmask,
2935 tmask, tm,
2936 fsec, is2digits);
2937 if (dterr < 0)
2938 return dterr;
2939 return 0;
2940
2941 default:
2942 /* Anything else is bogus input */
2943 return DTERR_BAD_FORMAT;
2944 }
2945
2946 /*
2947 * When processing a year field, mark it for adjustment if it's only one
2948 * or two digits.
2949 */
2950 if (*tmask == DTK_M(YEAR))
2951 *is2digits = (flen <= 2);
2952
2953 return 0;
2954}
static int ParseFractionalSecond(char *cp, fsec_t *fsec)
Definition: datetime.c:728
int DateOrder
Definition: globals.c:126
#define DATEORDER_DMY
Definition: miscadmin.h:244
#define DATEORDER_YMD
Definition: miscadmin.h:243
int tm_yday
Definition: pgtime.h:43

References DateOrder, DATEORDER_DMY, DATEORDER_YMD, DAY, DecodeNumberField(), DOY, DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_DATE_M, DTK_M, MONTH, ParseFractionalSecond(), str, strtoint(), tm, pg_tm::tm_mday, pg_tm::tm_mon, pg_tm::tm_yday, pg_tm::tm_year, val, and YEAR.

Referenced by DecodeDate(), DecodeDateTime(), and DecodeTimeOnly().

◆ DecodeNumberField()

static int DecodeNumberField ( int  len,
char *  str,
int  fmask,
int *  tmask,
struct pg_tm tm,
fsec_t fsec,
bool *  is2digits 
)
static

Definition at line 2965 of file datetime.c.

2967{
2968 char *cp;
2969
2970 /*
2971 * This function was originally meant to cope only with DTK_NUMBER fields,
2972 * but we now sometimes abuse it to parse (parts of) DTK_DATE fields,
2973 * which can contain letters and other punctuation. Reject if it's not a
2974 * valid DTK_NUMBER, that is digits and decimal point(s). (ParseFraction
2975 * will reject if there's more than one decimal point.)
2976 */
2977 if (strspn(str, "0123456789.") != len)
2978 return DTERR_BAD_FORMAT;
2979
2980 /*
2981 * Have a decimal point? Then this is a date or something with a seconds
2982 * field...
2983 */
2984 if ((cp = strchr(str, '.')) != NULL)
2985 {
2986 int dterr;
2987
2988 /* Convert the fraction and store at *fsec */
2989 dterr = ParseFractionalSecond(cp, fsec);
2990 if (dterr)
2991 return dterr;
2992 /* Now truncate off the fraction for further processing */
2993 *cp = '\0';
2994 len = strlen(str);
2995 }
2996 /* No decimal point and no complete date yet? */
2997 else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2998 {
2999 if (len >= 6)
3000 {
3001 *tmask = DTK_DATE_M;
3002
3003 /*
3004 * Start from end and consider first 2 as Day, next 2 as Month,
3005 * and the rest as Year.
3006 */
3007 tm->tm_mday = atoi(str + (len - 2));
3008 *(str + (len - 2)) = '\0';
3009 tm->tm_mon = atoi(str + (len - 4));
3010 *(str + (len - 4)) = '\0';
3011 tm->tm_year = atoi(str);
3012 if ((len - 4) == 2)
3013 *is2digits = true;
3014
3015 return DTK_DATE;
3016 }
3017 }
3018
3019 /* not all time fields are specified? */
3020 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
3021 {
3022 /* hhmmss */
3023 if (len == 6)
3024 {
3025 *tmask = DTK_TIME_M;
3026 tm->tm_sec = atoi(str + 4);
3027 *(str + 4) = '\0';
3028 tm->tm_min = atoi(str + 2);
3029 *(str + 2) = '\0';
3030 tm->tm_hour = atoi(str);
3031
3032 return DTK_TIME;
3033 }
3034 /* hhmm? */
3035 else if (len == 4)
3036 {
3037 *tmask = DTK_TIME_M;
3038 tm->tm_sec = 0;
3039 tm->tm_min = atoi(str + 2);
3040 *(str + 2) = '\0';
3041 tm->tm_hour = atoi(str);
3042
3043 return DTK_TIME;
3044 }
3045 }
3046
3047 return DTERR_BAD_FORMAT;
3048}

References DTERR_BAD_FORMAT, DTK_DATE, DTK_DATE_M, DTK_TIME, DTK_TIME_M, len, ParseFractionalSecond(), str, tm, pg_tm::tm_hour, pg_tm::tm_mday, pg_tm::tm_min, pg_tm::tm_mon, pg_tm::tm_sec, and pg_tm::tm_year.

Referenced by DecodeDateTime(), DecodeNumber(), and DecodeTimeOnly().

◆ DecodeSpecial()

int DecodeSpecial ( int  field,
const char *  lowtoken,
int *  val 
)

Definition at line 3246 of file datetime.c.

3247{
3248 int type;
3249 const datetkn *tp;
3250
3251 tp = datecache[field];
3252 /* use strncmp so that we match truncated tokens */
3253 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3254 {
3255 tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
3256 }
3257 if (tp == NULL)
3258 {
3260 *val = 0;
3261 }
3262 else
3263 {
3264 datecache[field] = tp;
3265 type = tp->type;
3266 *val = tp->value;
3267 }
3268
3269 return type;
3270}
static const datetkn * datecache[MAXDATEFIELDS]
Definition: datetime.c:258
static const datetkn * datebsearch(const char *key, const datetkn *base, int nel)
Definition: datetime.c:4275

References datebsearch(), datecache, datetktbl, szdatetktbl, datetkn::token, TOKMAXLEN, type, datetkn::type, UNKNOWN_FIELD, val, and datetkn::value.

Referenced by DecodeDate(), DecodeDateTime(), DecodeInterval(), DecodeTimeOnly(), extract_date(), interval_part_common(), time_part_common(), timestamp_part_common(), timestamptz_part_common(), and timetz_part_common().

◆ DecodeTime()

static int DecodeTime ( char *  str,
int  fmask,
int  range,
int *  tmask,
struct pg_tm tm,
fsec_t fsec 
)
static

Definition at line 2725 of file datetime.c.

2727{
2728 struct pg_itm itm;
2729 int dterr;
2730
2731 dterr = DecodeTimeCommon(str, fmask, range,
2732 tmask, &itm);
2733 if (dterr)
2734 return dterr;
2735
2736 if (itm.tm_hour > INT_MAX)
2737 return DTERR_FIELD_OVERFLOW;
2738 tm->tm_hour = (int) itm.tm_hour;
2739 tm->tm_min = itm.tm_min;
2740 tm->tm_sec = itm.tm_sec;
2741 *fsec = itm.tm_usec;
2742
2743 return 0;
2744}
static int DecodeTimeCommon(char *str, int fmask, int range, int *tmask, struct pg_itm *itm)
Definition: datetime.c:2643

References DecodeTimeCommon(), DTERR_FIELD_OVERFLOW, range(), str, tm, pg_itm::tm_hour, pg_tm::tm_hour, pg_itm::tm_min, pg_tm::tm_min, pg_itm::tm_sec, pg_tm::tm_sec, and pg_itm::tm_usec.

Referenced by DecodeDateTime(), DecodeInterval(), and DecodeTimeOnly().

◆ DecodeTimeCommon()

static int DecodeTimeCommon ( char *  str,
int  fmask,
int  range,
int *  tmask,
struct pg_itm itm 
)
static

Definition at line 2643 of file datetime.c.

2645{
2646 char *cp;
2647 int dterr;
2648 fsec_t fsec = 0;
2649
2650 *tmask = DTK_TIME_M;
2651
2652 errno = 0;
2653 itm->tm_hour = strtoi64(str, &cp, 10);
2654 if (errno == ERANGE)
2655 return DTERR_FIELD_OVERFLOW;
2656 if (*cp != ':')
2657 return DTERR_BAD_FORMAT;
2658 errno = 0;
2659 itm->tm_min = strtoint(cp + 1, &cp, 10);
2660 if (errno == ERANGE)
2661 return DTERR_FIELD_OVERFLOW;
2662 if (*cp == '\0')
2663 {
2664 itm->tm_sec = 0;
2665 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2667 {
2668 if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2669 return DTERR_FIELD_OVERFLOW;
2670 itm->tm_sec = itm->tm_min;
2671 itm->tm_min = (int) itm->tm_hour;
2672 itm->tm_hour = 0;
2673 }
2674 }
2675 else if (*cp == '.')
2676 {
2677 /* always assume mm:ss.sss is MINUTE TO SECOND */
2678 dterr = ParseFractionalSecond(cp, &fsec);
2679 if (dterr)
2680 return dterr;
2681 if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2682 return DTERR_FIELD_OVERFLOW;
2683 itm->tm_sec = itm->tm_min;
2684 itm->tm_min = (int) itm->tm_hour;
2685 itm->tm_hour = 0;
2686 }
2687 else if (*cp == ':')
2688 {
2689 errno = 0;
2690 itm->tm_sec = strtoint(cp + 1, &cp, 10);
2691 if (errno == ERANGE)
2692 return DTERR_FIELD_OVERFLOW;
2693 if (*cp == '.')
2694 {
2695 dterr = ParseFractionalSecond(cp, &fsec);
2696 if (dterr)
2697 return dterr;
2698 }
2699 else if (*cp != '\0')
2700 return DTERR_BAD_FORMAT;
2701 }
2702 else
2703 return DTERR_BAD_FORMAT;
2704
2705 /* do a sanity check; but caller must check the range of tm_hour */
2706 if (itm->tm_hour < 0 ||
2707 itm->tm_min < 0 || itm->tm_min > MINS_PER_HOUR - 1 ||
2708 itm->tm_sec < 0 || itm->tm_sec > SECS_PER_MINUTE ||
2709 fsec < 0 || fsec > USECS_PER_SEC)
2710 return DTERR_FIELD_OVERFLOW;
2711
2712 itm->tm_usec = (int) fsec;
2713
2714 return 0;
2715}
#define MINS_PER_HOUR
Definition: timestamp.h:129
#define SECS_PER_MINUTE
Definition: timestamp.h:128
int64 tm_hour
Definition: timestamp.h:70
int tm_sec
Definition: timestamp.h:68
int tm_min
Definition: timestamp.h:69
int tm_usec
Definition: timestamp.h:67

References DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_TIME_M, INTERVAL_MASK, MINS_PER_HOUR, MINUTE, ParseFractionalSecond(), range(), SECOND, SECS_PER_MINUTE, str, strtoint(), pg_itm::tm_hour, pg_itm::tm_min, pg_itm::tm_sec, pg_itm::tm_usec, and USECS_PER_SEC.

Referenced by DecodeTime(), and DecodeTimeForInterval().

◆ DecodeTimeForInterval()

static int DecodeTimeForInterval ( char *  str,
int  fmask,
int  range,
int *  tmask,
struct pg_itm_in itm_in 
)
static

Definition at line 2754 of file datetime.c.

2756{
2757 struct pg_itm itm;
2758 int dterr;
2759
2760 dterr = DecodeTimeCommon(str, fmask, range,
2761 tmask, &itm);
2762 if (dterr)
2763 return dterr;
2764
2765 itm_in->tm_usec = itm.tm_usec;
2766 if (!int64_multiply_add(itm.tm_hour, USECS_PER_HOUR, &itm_in->tm_usec) ||
2767 !int64_multiply_add(itm.tm_min, USECS_PER_MINUTE, &itm_in->tm_usec) ||
2768 !int64_multiply_add(itm.tm_sec, USECS_PER_SEC, &itm_in->tm_usec))
2769 return DTERR_FIELD_OVERFLOW;
2770
2771 return 0;
2772}

References DecodeTimeCommon(), DTERR_FIELD_OVERFLOW, int64_multiply_add(), range(), str, pg_itm::tm_hour, pg_itm::tm_min, pg_itm::tm_sec, pg_itm::tm_usec, pg_itm_in::tm_usec, USECS_PER_HOUR, USECS_PER_MINUTE, and USECS_PER_SEC.

Referenced by DecodeInterval().

◆ DecodeTimeOnly()

int DecodeTimeOnly ( char **  field,
int *  ftype,
int  nf,
int *  dtype,
struct pg_tm tm,
fsec_t fsec,
int *  tzp,
DateTimeErrorExtra extra 
)

Definition at line 1917 of file datetime.c.

1920{
1921 int fmask = 0,
1922 tmask,
1923 type;
1924 int ptype = 0; /* "prefix type" for ISO and Julian formats */
1925 int i;
1926 int val;
1927 int dterr;
1928 bool isjulian = false;
1929 bool is2digits = false;
1930 bool bc = false;
1931 int mer = HR24;
1932 pg_tz *namedTz = NULL;
1933 pg_tz *abbrevTz = NULL;
1934 char *abbrev = NULL;
1935 pg_tz *valtz;
1936
1937 *dtype = DTK_TIME;
1938 tm->tm_hour = 0;
1939 tm->tm_min = 0;
1940 tm->tm_sec = 0;
1941 *fsec = 0;
1942 /* don't know daylight savings time status apriori */
1943 tm->tm_isdst = -1;
1944
1945 if (tzp != NULL)
1946 *tzp = 0;
1947
1948 for (i = 0; i < nf; i++)
1949 {
1950 switch (ftype[i])
1951 {
1952 case DTK_DATE:
1953
1954 /*
1955 * Time zone not allowed? Then should not accept dates or time
1956 * zones no matter what else!
1957 */
1958 if (tzp == NULL)
1959 return DTERR_BAD_FORMAT;
1960
1961 /* Under limited circumstances, we will accept a date... */
1962 if (i == 0 && nf >= 2 &&
1963 (ftype[nf - 1] == DTK_DATE || ftype[1] == DTK_TIME))
1964 {
1965 dterr = DecodeDate(field[i], fmask,
1966 &tmask, &is2digits, tm);
1967 if (dterr)
1968 return dterr;
1969 }
1970 /* otherwise, this is a time and/or time zone */
1971 else
1972 {
1973 if (isdigit((unsigned char) *field[i]))
1974 {
1975 char *cp;
1976
1977 /*
1978 * Starts with a digit but we already have a time
1979 * field? Then we are in trouble with time already...
1980 */
1981 if ((fmask & DTK_TIME_M) == DTK_TIME_M)
1982 return DTERR_BAD_FORMAT;
1983
1984 /*
1985 * Should not get here and fail. Sanity check only...
1986 */
1987 if ((cp = strchr(field[i], '-')) == NULL)
1988 return DTERR_BAD_FORMAT;
1989
1990 /* Get the time zone from the end of the string */
1991 dterr = DecodeTimezone(cp, tzp);
1992 if (dterr)
1993 return dterr;
1994 *cp = '\0';
1995
1996 /*
1997 * Then read the rest of the field as a concatenated
1998 * time
1999 */
2000 dterr = DecodeNumberField(strlen(field[i]), field[i],
2001 (fmask | DTK_DATE_M),
2002 &tmask, tm,
2003 fsec, &is2digits);
2004 if (dterr < 0)
2005 return dterr;
2006 ftype[i] = dterr;
2007
2008 tmask |= DTK_M(TZ);
2009 }
2010 else
2011 {
2012 namedTz = pg_tzset(field[i]);
2013 if (!namedTz)
2014 {
2015 extra->dtee_timezone = field[i];
2016 return DTERR_BAD_TIMEZONE;
2017 }
2018 /* we'll apply the zone setting below */
2019 ftype[i] = DTK_TZ;
2020 tmask = DTK_M(TZ);
2021 }
2022 }
2023 break;
2024
2025 case DTK_TIME:
2026
2027 /*
2028 * This might be an ISO time following a "t" field.
2029 */
2030 if (ptype != 0)
2031 {
2032 if (ptype != DTK_TIME)
2033 return DTERR_BAD_FORMAT;
2034 ptype = 0;
2035 }
2036
2037 dterr = DecodeTime(field[i], (fmask | DTK_DATE_M),
2039 &tmask, tm, fsec);
2040 if (dterr)
2041 return dterr;
2042 break;
2043
2044 case DTK_TZ:
2045 {
2046 int tz;
2047
2048 if (tzp == NULL)
2049 return DTERR_BAD_FORMAT;
2050
2051 dterr = DecodeTimezone(field[i], &tz);
2052 if (dterr)
2053 return dterr;
2054 *tzp = tz;
2055 tmask = DTK_M(TZ);
2056 }
2057 break;
2058
2059 case DTK_NUMBER:
2060
2061 /*
2062 * Deal with cases where previous field labeled this one
2063 */
2064 if (ptype != 0)
2065 {
2066 char *cp;
2067 int value;
2068
2069 errno = 0;
2070 value = strtoint(field[i], &cp, 10);
2071 if (errno == ERANGE)
2072 return DTERR_FIELD_OVERFLOW;
2073 if (*cp != '.' && *cp != '\0')
2074 return DTERR_BAD_FORMAT;
2075
2076 switch (ptype)
2077 {
2078 case DTK_JULIAN:
2079 /* previous field was a label for "julian date" */
2080 if (tzp == NULL)
2081 return DTERR_BAD_FORMAT;
2082 if (value < 0)
2083 return DTERR_FIELD_OVERFLOW;
2084 tmask = DTK_DATE_M;
2086 isjulian = true;
2087
2088 if (*cp == '.')
2089 {
2090 double time;
2091
2092 dterr = ParseFraction(cp, &time);
2093 if (dterr)
2094 return dterr;
2095 time *= USECS_PER_DAY;
2096 dt2time(time,
2097 &tm->tm_hour, &tm->tm_min,
2098 &tm->tm_sec, fsec);
2099 tmask |= DTK_TIME_M;
2100 }
2101 break;
2102
2103 case DTK_TIME:
2104 /* previous field was "t" for ISO time */
2105 dterr = DecodeNumberField(strlen(field[i]), field[i],
2106 (fmask | DTK_DATE_M),
2107 &tmask, tm,
2108 fsec, &is2digits);
2109 if (dterr < 0)
2110 return dterr;
2111 ftype[i] = dterr;
2112
2113 if (tmask != DTK_TIME_M)
2114 return DTERR_BAD_FORMAT;
2115 break;
2116
2117 default:
2118 return DTERR_BAD_FORMAT;
2119 break;
2120 }
2121
2122 ptype = 0;
2123 *dtype = DTK_DATE;
2124 }
2125 else
2126 {
2127 char *cp;
2128 int flen;
2129
2130 flen = strlen(field[i]);
2131 cp = strchr(field[i], '.');
2132
2133 /* Embedded decimal? */
2134 if (cp != NULL)
2135 {
2136 /*
2137 * Under limited circumstances, we will accept a
2138 * date...
2139 */
2140 if (i == 0 && nf >= 2 && ftype[nf - 1] == DTK_DATE)
2141 {
2142 dterr = DecodeDate(field[i], fmask,
2143 &tmask, &is2digits, tm);
2144 if (dterr)
2145 return dterr;
2146 }
2147 /* embedded decimal and several digits before? */
2148 else if (flen - strlen(cp) > 2)
2149 {
2150 /*
2151 * Interpret as a concatenated date or time Set
2152 * the type field to allow decoding other fields
2153 * later. Example: 20011223 or 040506
2154 */
2155 dterr = DecodeNumberField(flen, field[i],
2156 (fmask | DTK_DATE_M),
2157 &tmask, tm,
2158 fsec, &is2digits);
2159 if (dterr < 0)
2160 return dterr;
2161 ftype[i] = dterr;
2162 }
2163 else
2164 return DTERR_BAD_FORMAT;
2165 }
2166 else if (flen > 4)
2167 {
2168 dterr = DecodeNumberField(flen, field[i],
2169 (fmask | DTK_DATE_M),
2170 &tmask, tm,
2171 fsec, &is2digits);
2172 if (dterr < 0)
2173 return dterr;
2174 ftype[i] = dterr;
2175 }
2176 /* otherwise it is a single date/time field... */
2177 else
2178 {
2179 dterr = DecodeNumber(flen, field[i],
2180 false,
2181 (fmask | DTK_DATE_M),
2182 &tmask, tm,
2183 fsec, &is2digits);
2184 if (dterr)
2185 return dterr;
2186 }
2187 }
2188 break;
2189
2190 case DTK_STRING:
2191 case DTK_SPECIAL:
2192 /* timezone abbrevs take precedence over built-in tokens */
2193 dterr = DecodeTimezoneAbbrev(i, field[i],
2194 &type, &val, &valtz, extra);
2195 if (dterr)
2196 return dterr;
2197 if (type == UNKNOWN_FIELD)
2198 type = DecodeSpecial(i, field[i], &val);
2199 if (type == IGNORE_DTF)
2200 continue;
2201
2202 tmask = DTK_M(type);
2203 switch (type)
2204 {
2205 case RESERV:
2206 switch (val)
2207 {
2208 case DTK_NOW:
2209 tmask = DTK_TIME_M;
2210 *dtype = DTK_TIME;
2211 GetCurrentTimeUsec(tm, fsec, NULL);
2212 break;
2213
2214 case DTK_ZULU:
2215 tmask = (DTK_TIME_M | DTK_M(TZ));
2216 *dtype = DTK_TIME;
2217 tm->tm_hour = 0;
2218 tm->tm_min = 0;
2219 tm->tm_sec = 0;
2220 tm->tm_isdst = 0;
2221 break;
2222
2223 default:
2224 return DTERR_BAD_FORMAT;
2225 }
2226
2227 break;
2228
2229 case DTZMOD:
2230
2231 /*
2232 * daylight savings time modifier (solves "MET DST"
2233 * syntax)
2234 */
2235 tmask |= DTK_M(DTZ);
2236 tm->tm_isdst = 1;
2237 if (tzp == NULL)
2238 return DTERR_BAD_FORMAT;
2239 *tzp -= val;
2240 break;
2241
2242 case DTZ:
2243
2244 /*
2245 * set mask for TZ here _or_ check for DTZ later when
2246 * getting default timezone
2247 */
2248 tmask |= DTK_M(TZ);
2249 tm->tm_isdst = 1;
2250 if (tzp == NULL)
2251 return DTERR_BAD_FORMAT;
2252 *tzp = -val;
2253 ftype[i] = DTK_TZ;
2254 break;
2255
2256 case TZ:
2257 tm->tm_isdst = 0;
2258 if (tzp == NULL)
2259 return DTERR_BAD_FORMAT;
2260 *tzp = -val;
2261 ftype[i] = DTK_TZ;
2262 break;
2263
2264 case DYNTZ:
2265 tmask |= DTK_M(TZ);
2266 if (tzp == NULL)
2267 return DTERR_BAD_FORMAT;
2268 /* we'll determine the actual offset later */
2269 abbrevTz = valtz;
2270 abbrev = field[i];
2271 ftype[i] = DTK_TZ;
2272 break;
2273
2274 case AMPM:
2275 mer = val;
2276 break;
2277
2278 case ADBC:
2279 bc = (val == BC);
2280 break;
2281
2282 case UNITS:
2283 tmask = 0;
2284 /* reject consecutive unhandled units */
2285 if (ptype != 0)
2286 return DTERR_BAD_FORMAT;
2287 ptype = val;
2288 break;
2289
2290 case ISOTIME:
2291 tmask = 0;
2292 /* reject consecutive unhandled units */
2293 if (ptype != 0)
2294 return DTERR_BAD_FORMAT;
2295 ptype = val;
2296 break;
2297
2298 case UNKNOWN_FIELD:
2299
2300 /*
2301 * Before giving up and declaring error, check to see
2302 * if it is an all-alpha timezone name.
2303 */
2304 namedTz = pg_tzset(field[i]);
2305 if (!namedTz)
2306 return DTERR_BAD_FORMAT;
2307 /* we'll apply the zone setting below */
2308 tmask = DTK_M(TZ);
2309 break;
2310
2311 default:
2312 return DTERR_BAD_FORMAT;
2313 }
2314 break;
2315
2316 default:
2317 return DTERR_BAD_FORMAT;
2318 }
2319
2320 if (tmask & fmask)
2321 return DTERR_BAD_FORMAT;
2322 fmask |= tmask;
2323 } /* end loop over fields */
2324
2325 /* reject if prefix type appeared and was never handled */
2326 if (ptype != 0)
2327 return DTERR_BAD_FORMAT;
2328
2329 /* do final checking/adjustment of Y/M/D fields */
2330 dterr = ValidateDate(fmask, isjulian, is2digits, bc, tm);
2331 if (dterr)
2332 return dterr;
2333
2334 /* handle AM/PM */
2335 if (mer != HR24 && tm->tm_hour > HOURS_PER_DAY / 2)
2336 return DTERR_FIELD_OVERFLOW;
2337 if (mer == AM && tm->tm_hour == HOURS_PER_DAY / 2)
2338 tm->tm_hour = 0;
2339 else if (mer == PM && tm->tm_hour != HOURS_PER_DAY / 2)
2340 tm->tm_hour += HOURS_PER_DAY / 2;
2341
2342 /* check for time overflow */
2343 if (time_overflows(tm->tm_hour, tm->tm_min, tm->tm_sec, *fsec))
2344 return DTERR_FIELD_OVERFLOW;
2345
2346 if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2347 return DTERR_BAD_FORMAT;
2348
2349 /*
2350 * If we had a full timezone spec, compute the offset (we could not do it
2351 * before, because we may need the date to resolve DST status).
2352 */
2353 if (namedTz != NULL)
2354 {
2355 long int gmtoff;
2356
2357 /* daylight savings time modifier disallowed with full TZ */
2358 if (fmask & DTK_M(DTZMOD))
2359 return DTERR_BAD_FORMAT;
2360
2361 /* if non-DST zone, we do not need to know the date */
2362 if (pg_get_timezone_offset(namedTz, &gmtoff))
2363 {
2364 *tzp = -(int) gmtoff;
2365 }
2366 else
2367 {
2368 /* a date has to be specified */
2369 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2370 return DTERR_BAD_FORMAT;
2371 *tzp = DetermineTimeZoneOffset(tm, namedTz);
2372 }
2373 }
2374
2375 /*
2376 * Likewise, if we had a dynamic timezone abbreviation, resolve it now.
2377 */
2378 if (abbrevTz != NULL)
2379 {
2380 struct pg_tm tt,
2381 *tmp = &tt;
2382
2383 /*
2384 * daylight savings time modifier but no standard timezone? then error
2385 */
2386 if (fmask & DTK_M(DTZMOD))
2387 return DTERR_BAD_FORMAT;
2388
2389 if ((fmask & DTK_DATE_M) == 0)
2390 GetCurrentDateTime(tmp);
2391 else
2392 {
2393 /* a date has to be specified */
2394 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2395 return DTERR_BAD_FORMAT;
2396 tmp->tm_year = tm->tm_year;
2397 tmp->tm_mon = tm->tm_mon;
2398 tmp->tm_mday = tm->tm_mday;
2399 }
2400 tmp->tm_hour = tm->tm_hour;
2401 tmp->tm_min = tm->tm_min;
2402 tmp->tm_sec = tm->tm_sec;
2403 *tzp = DetermineTimeZoneAbbrevOffset(tmp, abbrev, abbrevTz);
2404 tm->tm_isdst = tmp->tm_isdst;
2405 }
2406
2407 /* timezone not specified? then use session timezone */
2408 if (tzp != NULL && !(fmask & DTK_M(TZ)))
2409 {
2410 struct pg_tm tt,
2411 *tmp = &tt;
2412
2413 /*
2414 * daylight savings time modifier but no standard timezone? then error
2415 */
2416 if (fmask & DTK_M(DTZMOD))
2417 return DTERR_BAD_FORMAT;
2418
2419 if ((fmask & DTK_DATE_M) == 0)
2420 GetCurrentDateTime(tmp);
2421 else
2422 {
2423 /* a date has to be specified */
2424 if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2425 return DTERR_BAD_FORMAT;
2426 tmp->tm_year = tm->tm_year;
2427 tmp->tm_mon = tm->tm_mon;
2428 tmp->tm_mday = tm->tm_mday;
2429 }
2430 tmp->tm_hour = tm->tm_hour;
2431 tmp->tm_min = tm->tm_min;
2432 tmp->tm_sec = tm->tm_sec;
2434 tm->tm_isdst = tmp->tm_isdst;
2435 }
2436
2437 return 0;
2438}
bool pg_get_timezone_offset(const pg_tz *tz, long int *gmtoff)
Definition: localtime.c:1966

References ADBC, AM, AMPM, BC, DecodeDate(), DecodeNumber(), DecodeNumberField(), DecodeSpecial(), DecodeTime(), DecodeTimezone(), DecodeTimezoneAbbrev(), DetermineTimeZoneAbbrevOffset(), DetermineTimeZoneOffset(), dt2time(), DateTimeErrorExtra::dtee_timezone, DTERR_BAD_FORMAT, DTERR_BAD_TIMEZONE, DTERR_FIELD_OVERFLOW, DTK_DATE, DTK_DATE_M, DTK_JULIAN, DTK_M, DTK_NOW, DTK_NUMBER, DTK_SPECIAL, DTK_STRING, DTK_TIME, DTK_TIME_M, DTK_TZ, DTK_ZULU, DTZ, DTZMOD, DYNTZ, GetCurrentDateTime(), GetCurrentTimeUsec(), HOURS_PER_DAY, HR24, i, IGNORE_DTF, INTERVAL_FULL_RANGE, ISOTIME, j2date(), ParseFraction(), pg_get_timezone_offset(), pg_tzset(), PM, RESERV, session_timezone, strtoint(), time_overflows(), tm, pg_tm::tm_hour, pg_tm::tm_isdst, pg_tm::tm_mday, pg_tm::tm_min, pg_tm::tm_mon, pg_tm::tm_sec, pg_tm::tm_year, type, TZ, UNITS, UNKNOWN_FIELD, USECS_PER_DAY, val, ValidateDate(), and value.

Referenced by time_in(), and timetz_in().

◆ DecodeTimezone()

int DecodeTimezone ( const char *  str,
int *  tzp 
)

Definition at line 3057 of file datetime.c.

3058{
3059 int tz;
3060 int hr,
3061 min,
3062 sec = 0;
3063 char *cp;
3064
3065 /* leading character must be "+" or "-" */
3066 if (*str != '+' && *str != '-')
3067 return DTERR_BAD_FORMAT;
3068
3069 errno = 0;
3070 hr = strtoint(str + 1, &cp, 10);
3071 if (errno == ERANGE)
3072 return DTERR_TZDISP_OVERFLOW;
3073
3074 /* explicit delimiter? */
3075 if (*cp == ':')
3076 {
3077 errno = 0;
3078 min = strtoint(cp + 1, &cp, 10);
3079 if (errno == ERANGE)
3080 return DTERR_TZDISP_OVERFLOW;
3081 if (*cp == ':')
3082 {
3083 errno = 0;
3084 sec = strtoint(cp + 1, &cp, 10);
3085 if (errno == ERANGE)
3086 return DTERR_TZDISP_OVERFLOW;
3087 }
3088 }
3089 /* otherwise, might have run things together... */
3090 else if (*cp == '\0' && strlen(str) > 3)
3091 {
3092 min = hr % 100;
3093 hr = hr / 100;
3094 /* we could, but don't, support a run-together hhmmss format */
3095 }
3096 else
3097 min = 0;
3098
3099 /* Range-check the values; see notes in datatype/timestamp.h */
3100 if (hr < 0 || hr > MAX_TZDISP_HOUR)
3101 return DTERR_TZDISP_OVERFLOW;
3102 if (min < 0 || min >= MINS_PER_HOUR)
3103 return DTERR_TZDISP_OVERFLOW;
3104 if (sec < 0 || sec >= SECS_PER_MINUTE)
3105 return DTERR_TZDISP_OVERFLOW;
3106
3107 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
3108 if (*str == '-')
3109 tz = -tz;
3110
3111 *tzp = -tz;
3112
3113 if (*cp != '\0')
3114 return DTERR_BAD_FORMAT;
3115
3116 return 0;
3117}
#define MAX_TZDISP_HOUR
Definition: timestamp.h:143

References DTERR_BAD_FORMAT, DTERR_TZDISP_OVERFLOW, MAX_TZDISP_HOUR, MINS_PER_HOUR, SECS_PER_MINUTE, str, and strtoint().

Referenced by DecodeDateTime(), DecodeTimeOnly(), and parse_sane_timezone().

◆ DecodeTimezoneAbbrev()

int DecodeTimezoneAbbrev ( int  field,
const char *  lowtoken,
int *  ftype,
int *  offset,
pg_tz **  tz,
DateTimeErrorExtra extra 
)

Definition at line 3141 of file datetime.c.

3144{
3145 TzAbbrevCache *tzc = &tzabbrevcache[field];
3146 bool isfixed;
3147 int isdst;
3148 const datetkn *tp;
3149
3150 /*
3151 * Do we have a cached result? Use strncmp so that we match truncated
3152 * names, although we shouldn't really see that happen with normal
3153 * abbreviations.
3154 */
3155 if (strncmp(lowtoken, tzc->abbrev, TOKMAXLEN) == 0)
3156 {
3157 *ftype = tzc->ftype;
3158 *offset = tzc->offset;
3159 *tz = tzc->tz;
3160 return 0;
3161 }
3162
3163 /*
3164 * See if the current session_timezone recognizes it. Checking this
3165 * before zoneabbrevtbl allows us to correctly handle abbreviations whose
3166 * meaning varies across zones, such as "LMT".
3167 */
3168 if (session_timezone &&
3170 &isfixed, offset, &isdst))
3171 {
3172 *ftype = (isfixed ? (isdst ? DTZ : TZ) : DYNTZ);
3173 *tz = (isfixed ? NULL : session_timezone);
3174 /* flip sign to agree with the convention used in zoneabbrevtbl */
3175 *offset = -(*offset);
3176 /* cache result; use strlcpy to truncate name if necessary */
3177 strlcpy(tzc->abbrev, lowtoken, TOKMAXLEN + 1);
3178 tzc->ftype = *ftype;
3179 tzc->offset = *offset;
3180 tzc->tz = *tz;
3181 return 0;
3182 }
3183
3184 /* Nope, so look in zoneabbrevtbl */
3185 if (zoneabbrevtbl)
3186 tp = datebsearch(lowtoken, zoneabbrevtbl->abbrevs,
3188 else
3189 tp = NULL;
3190 if (tp == NULL)
3191 {
3192 *ftype = UNKNOWN_FIELD;
3193 *offset = 0;
3194 *tz = NULL;
3195 /* failure results are not cached */
3196 }
3197 else
3198 {
3199 *ftype = tp->type;
3200 if (tp->type == DYNTZ)
3201 {
3202 *offset = 0;
3203 *tz = FetchDynamicTimeZone(zoneabbrevtbl, tp, extra);
3204 if (*tz == NULL)
3205 return DTERR_BAD_ZONE_ABBREV;
3206 }
3207 else
3208 {
3209 *offset = tp->value;
3210 *tz = NULL;
3211 }
3212
3213 /* cache result; use strlcpy to truncate name if necessary */
3214 strlcpy(tzc->abbrev, lowtoken, TOKMAXLEN + 1);
3215 tzc->ftype = *ftype;
3216 tzc->offset = *offset;
3217 tzc->tz = *tz;
3218 }
3219
3220 return 0;
3221}
static TimeZoneAbbrevTable * zoneabbrevtbl
Definition: datetime.c:254
static bool TimeZoneAbbrevIsKnown(const char *abbr, pg_tz *tzp, bool *isfixed, int *offset, int *isdst)
Definition: datetime.c:1874
static pg_tz * FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp, DateTimeErrorExtra *extra)
Definition: datetime.c:5092
pg_tz * tz
Definition: datetime.c:269
char abbrev[TOKMAXLEN+1]
Definition: datetime.c:266

References TzAbbrevCache::abbrev, TimeZoneAbbrevTable::abbrevs, datebsearch(), DTERR_BAD_ZONE_ABBREV, DTZ, DYNTZ, FetchDynamicTimeZone(), TzAbbrevCache::ftype, TimeZoneAbbrevTable::numabbrevs, TzAbbrevCache::offset, session_timezone, strlcpy(), TimeZoneAbbrevIsKnown(), TOKMAXLEN, datetkn::type, TzAbbrevCache::tz, TZ, tzabbrevcache, UNKNOWN_FIELD, datetkn::value, and zoneabbrevtbl.

Referenced by DecodeDateTime(), DecodeTimeOnly(), and DecodeTimezoneName().

◆ DecodeTimezoneAbbrevPrefix()

int DecodeTimezoneAbbrevPrefix ( const char *  str,
int *  offset,
pg_tz **  tz 
)

Definition at line 3371 of file datetime.c.

3372{
3373 char lowtoken[TOKMAXLEN + 1];
3374 int len;
3375
3376 *offset = 0; /* avoid uninitialized vars on failure */
3377 *tz = NULL;
3378
3379 /* Downcase as much of the string as we could need */
3380 for (len = 0; len < TOKMAXLEN; len++)
3381 {
3382 if (*str == '\0' || !isalpha((unsigned char) *str))
3383 break;
3384 lowtoken[len] = pg_tolower((unsigned char) *str++);
3385 }
3386 lowtoken[len] = '\0';
3387
3388 /*
3389 * We could avoid doing repeated binary searches if we cared to duplicate
3390 * datebsearch here, but it's not clear that such an optimization would be
3391 * worth the trouble. In common cases there's probably not anything after
3392 * the zone abbrev anyway. So just search with successively truncated
3393 * strings.
3394 */
3395 while (len > 0)
3396 {
3397 bool isfixed;
3398 int isdst;
3399 const datetkn *tp;
3400
3401 /* See if the current session_timezone recognizes it. */
3402 if (session_timezone &&
3404 &isfixed, offset, &isdst))
3405 {
3406 if (isfixed)
3407 {
3408 /* flip sign to agree with the convention in zoneabbrevtbl */
3409 *offset = -(*offset);
3410 }
3411 else
3412 {
3413 /* Caller must resolve the abbrev's current meaning */
3414 *tz = session_timezone;
3415 }
3416 return len;
3417 }
3418
3419 /* Known in zoneabbrevtbl? */
3420 if (zoneabbrevtbl)
3421 tp = datebsearch(lowtoken, zoneabbrevtbl->abbrevs,
3423 else
3424 tp = NULL;
3425 if (tp != NULL)
3426 {
3427 if (tp->type == DYNTZ)
3428 {
3429 DateTimeErrorExtra extra;
3431 &extra);
3432
3433 if (tzp != NULL)
3434 {
3435 /* Caller must resolve the abbrev's current meaning */
3436 *tz = tzp;
3437 return len;
3438 }
3439 }
3440 else
3441 {
3442 /* Fixed-offset zone abbrev, so it's easy */
3443 *offset = tp->value;
3444 return len;
3445 }
3446 }
3447
3448 /* Nope, try the next shorter string. */
3449 lowtoken[--len] = '\0';
3450 }
3451
3452 /* Did not find a match */
3453 return -1;
3454}
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:118

References TimeZoneAbbrevTable::abbrevs, datebsearch(), DYNTZ, FetchDynamicTimeZone(), len, TimeZoneAbbrevTable::numabbrevs, pg_tolower(), session_timezone, str, TimeZoneAbbrevIsKnown(), TOKMAXLEN, datetkn::type, datetkn::value, and zoneabbrevtbl.

Referenced by DCH_from_char().

◆ DecodeTimezoneName()

int DecodeTimezoneName ( const char *  tzname,
int *  offset,
pg_tz **  tz 
)

Definition at line 3288 of file datetime.c.

3289{
3290 char *lowzone;
3291 int dterr,
3292 type;
3293 DateTimeErrorExtra extra;
3294
3295 /*
3296 * First we look in the timezone abbreviation table (to handle cases like
3297 * "EST"), and if that fails, we look in the timezone database (to handle
3298 * cases like "America/New_York"). This matches the order in which
3299 * timestamp input checks the cases; it's important because the timezone
3300 * database unwisely uses a few zone names that are identical to offset
3301 * abbreviations.
3302 */
3303
3304 /* DecodeTimezoneAbbrev requires lowercase input */
3305 lowzone = downcase_truncate_identifier(tzname,
3306 strlen(tzname),
3307 false);
3308
3309 dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
3310 if (dterr)
3311 DateTimeParseError(dterr, &extra, NULL, NULL, NULL);
3312
3313 if (type == TZ || type == DTZ)
3314 {
3315 /* fixed-offset abbreviation, return the offset */
3316 return TZNAME_FIXED_OFFSET;
3317 }
3318 else if (type == DYNTZ)
3319 {
3320 /* dynamic-offset abbreviation, return its referenced timezone */
3321 return TZNAME_DYNTZ;
3322 }
3323 else
3324 {
3325 /* try it as a full zone name */
3326 *tz = pg_tzset(tzname);
3327 if (*tz == NULL)
3328 ereport(ERROR,
3329 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3330 errmsg("time zone \"%s\" not recognized", tzname)));
3331 return TZNAME_ZONE;
3332 }
3333}
void DateTimeParseError(int dterr, DateTimeErrorExtra *extra, const char *str, const char *datatype, Node *escontext)
Definition: datetime.c:4214
#define ereport(elevel,...)
Definition: elog.h:150
#define TZNAME_ZONE
Definition: datetime.h:301
#define TZNAME_FIXED_OFFSET
Definition: datetime.h:299
#define TZNAME_DYNTZ
Definition: datetime.h:300
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition: scansup.c:37

References DateTimeParseError(), DecodeTimezoneAbbrev(), downcase_truncate_identifier(), DTZ, DYNTZ, ereport, errcode(), errmsg(), ERROR, pg_tzset(), type, TZ, TZNAME_DYNTZ, TZNAME_FIXED_OFFSET, and TZNAME_ZONE.

Referenced by DecodeTimezoneNameToTz(), parse_sane_timezone(), timestamp_zone(), timestamptz_zone(), and timetz_zone().

◆ DecodeTimezoneNameToTz()

pg_tz * DecodeTimezoneNameToTz ( const char *  tzname)

Definition at line 3343 of file datetime.c.

3344{
3345 pg_tz *result;
3346 int offset;
3347
3348 if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
3349 {
3350 /* fixed-offset abbreviation, get a pg_tz descriptor for that */
3351 result = pg_tzset_offset(-offset); /* flip to POSIX sign convention */
3352 }
3353 return result;
3354}
int DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
Definition: datetime.c:3288
pg_tz * pg_tzset_offset(long gmtoffset)
Definition: pgtz.c:320

References DecodeTimezoneName(), pg_tzset_offset(), and TZNAME_FIXED_OFFSET.

Referenced by lookup_timezone().

◆ DecodeUnits()

int DecodeUnits ( int  field,
const char *  lowtoken,
int *  val 
)

Definition at line 4169 of file datetime.c.

4170{
4171 int type;
4172 const datetkn *tp;
4173
4174 tp = deltacache[field];
4175 /* use strncmp so that we match truncated tokens */
4176 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
4177 {
4178 tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
4179 }
4180 if (tp == NULL)
4181 {
4183 *val = 0;
4184 }
4185 else
4186 {
4187 deltacache[field] = tp;
4188 type = tp->type;
4189 *val = tp->value;
4190 }
4191
4192 return type;
4193} /* DecodeUnits() */
static const datetkn * deltacache[MAXDATEFIELDS]
Definition: datetime.c:260

References datebsearch(), deltacache, deltatktbl, szdeltatktbl, datetkn::token, TOKMAXLEN, type, datetkn::type, UNKNOWN_FIELD, val, and datetkn::value.

Referenced by DecodeInterval(), extract_date(), interval_part_common(), interval_trunc(), time_part_common(), timestamp_part_common(), timestamp_trunc(), timestamptz_part_common(), timestamptz_trunc_internal(), and timetz_part_common().

◆ DetermineTimeZoneAbbrevOffset()

int DetermineTimeZoneAbbrevOffset ( struct pg_tm tm,
const char *  abbr,
pg_tz tzp 
)

Definition at line 1765 of file datetime.c.

1766{
1767 pg_time_t t;
1768 int zone_offset;
1769 int abbr_offset;
1770 int abbr_isdst;
1771
1772 /*
1773 * Compute the UTC time we want to probe at. (In event of overflow, we'll
1774 * probe at the epoch, which is a bit random but probably doesn't matter.)
1775 */
1776 zone_offset = DetermineTimeZoneOffsetInternal(tm, tzp, &t);
1777
1778 /*
1779 * Try to match the abbreviation to something in the zone definition.
1780 */
1782 &abbr_offset, &abbr_isdst))
1783 {
1784 /* Success, so use the abbrev-specific answers. */
1785 tm->tm_isdst = abbr_isdst;
1786 return abbr_offset;
1787 }
1788
1789 /*
1790 * No match, so use the answers we already got from
1791 * DetermineTimeZoneOffsetInternal.
1792 */
1793 return zone_offset;
1794}
static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp, pg_time_t *tp)
Definition: datetime.c:1626
static bool DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t, const char *abbr, pg_tz *tzp, int *offset, int *isdst)
Definition: datetime.c:1840
int64 pg_time_t
Definition: pgtime.h:23

References DetermineTimeZoneAbbrevOffsetInternal(), DetermineTimeZoneOffsetInternal(), tm, and pg_tm::tm_isdst.

Referenced by DecodeDateTime(), DecodeTimeOnly(), do_to_timestamp(), parse_sane_timezone(), and timestamp_zone().

◆ DetermineTimeZoneAbbrevOffsetInternal()

static bool DetermineTimeZoneAbbrevOffsetInternal ( pg_time_t  t,
const char *  abbr,
pg_tz tzp,
int *  offset,
int *  isdst 
)
static

Definition at line 1840 of file datetime.c.

1842{
1843 char upabbr[TZ_STRLEN_MAX + 1];
1844 unsigned char *p;
1845 long int gmtoff;
1846
1847 /* We need to force the abbrev to upper case */
1848 strlcpy(upabbr, abbr, sizeof(upabbr));
1849 for (p = (unsigned char *) upabbr; *p; p++)
1850 *p = pg_toupper(*p);
1851
1852 /* Look up the abbrev's meaning at this time in this zone */
1854 &t,
1855 &gmtoff,
1856 isdst,
1857 tzp))
1858 {
1859 /* Change sign to agree with DetermineTimeZoneOffset() */
1860 *offset = (int) -gmtoff;
1861 return true;
1862 }
1863 return false;
1864}
#define TZ_STRLEN_MAX
Definition: pgtime.h:54
bool pg_interpret_timezone_abbrev(const char *abbrev, const pg_time_t *timep, long int *gmtoff, int *isdst, const pg_tz *tz)
Definition: localtime.c:1744
unsigned char pg_toupper(unsigned char ch)
Definition: pgstrcasecmp.c:101

References pg_interpret_timezone_abbrev(), pg_toupper(), strlcpy(), and TZ_STRLEN_MAX.

Referenced by DetermineTimeZoneAbbrevOffset(), and DetermineTimeZoneAbbrevOffsetTS().

◆ DetermineTimeZoneAbbrevOffsetTS()

int DetermineTimeZoneAbbrevOffsetTS ( TimestampTz  ts,
const char *  abbr,
pg_tz tzp,
int *  isdst 
)

Definition at line 1803 of file datetime.c.

1805{
1807 int zone_offset;
1808 int abbr_offset;
1809 int tz;
1810 struct pg_tm tm;
1811 fsec_t fsec;
1812
1813 /*
1814 * If the abbrev matches anything in the zone data, this is pretty easy.
1815 */
1817 &abbr_offset, isdst))
1818 return abbr_offset;
1819
1820 /*
1821 * Else, break down the timestamp so we can use DetermineTimeZoneOffset.
1822 */
1823 if (timestamp2tm(ts, &tz, &tm, &fsec, NULL, tzp) != 0)
1824 ereport(ERROR,
1825 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1826 errmsg("timestamp out of range")));
1827
1828 zone_offset = DetermineTimeZoneOffset(&tm, tzp);
1829 *isdst = tm.tm_isdst;
1830 return zone_offset;
1831}
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1910
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1842

References DetermineTimeZoneAbbrevOffsetInternal(), DetermineTimeZoneOffset(), ereport, errcode(), errmsg(), ERROR, timestamp2tm(), timestamptz_to_time_t(), tm, and pg_tm::tm_isdst.

Referenced by pg_timezone_abbrevs_abbrevs(), timestamptz_zone(), and timetz_zone().

◆ DetermineTimeZoneOffset()

◆ DetermineTimeZoneOffsetInternal()

static int DetermineTimeZoneOffsetInternal ( struct pg_tm tm,
pg_tz tzp,
pg_time_t tp 
)
static

Definition at line 1626 of file datetime.c.

1627{
1628 int date,
1629 sec;
1630 pg_time_t day,
1631 mytime,
1632 prevtime,
1633 boundary,
1634 beforetime,
1635 aftertime;
1636 long int before_gmtoff,
1637 after_gmtoff;
1638 int before_isdst,
1639 after_isdst;
1640 int res;
1641
1642 /*
1643 * First, generate the pg_time_t value corresponding to the given
1644 * y/m/d/h/m/s taken as GMT time. If this overflows, punt and decide the
1645 * timezone is GMT. (For a valid Julian date, integer overflow should be
1646 * impossible with 64-bit pg_time_t, but let's check for safety.)
1647 */
1649 goto overflow;
1651
1652 day = ((pg_time_t) date) * SECS_PER_DAY;
1653 if (day / SECS_PER_DAY != date)
1654 goto overflow;
1656 mytime = day + sec;
1657 /* since sec >= 0, overflow could only be from +day to -mytime */
1658 if (mytime < 0 && day > 0)
1659 goto overflow;
1660
1661 /*
1662 * Find the DST time boundary just before or following the target time. We
1663 * assume that all zones have GMT offsets less than 24 hours, and that DST
1664 * boundaries can't be closer together than 48 hours, so backing up 24
1665 * hours and finding the "next" boundary will work.
1666 */
1667 prevtime = mytime - SECS_PER_DAY;
1668 if (mytime < 0 && prevtime > 0)
1669 goto overflow;
1670
1671 res = pg_next_dst_boundary(&prevtime,
1672 &before_gmtoff, &before_isdst,
1673 &boundary,
1674 &after_gmtoff, &after_isdst,
1675 tzp);
1676 if (res < 0)
1677 goto overflow; /* failure? */
1678
1679 if (res == 0)
1680 {
1681 /* Non-DST zone, life is simple */
1682 tm->tm_isdst = before_isdst;
1683 *tp = mytime - before_gmtoff;
1684 return -(int) before_gmtoff;
1685 }
1686
1687 /*
1688 * Form the candidate pg_time_t values with local-time adjustment
1689 */
1690 beforetime = mytime - before_gmtoff;
1691 if ((before_gmtoff > 0 &&
1692 mytime < 0 && beforetime > 0) ||
1693 (before_gmtoff <= 0 &&
1694 mytime > 0 && beforetime < 0))
1695 goto overflow;
1696 aftertime = mytime - after_gmtoff;
1697 if ((after_gmtoff > 0 &&
1698 mytime < 0 && aftertime > 0) ||
1699 (after_gmtoff <= 0 &&
1700 mytime > 0 && aftertime < 0))
1701 goto overflow;
1702
1703 /*
1704 * If both before or both after the boundary time, we know what to do. The
1705 * boundary time itself is considered to be after the transition, which
1706 * means we can accept aftertime == boundary in the second case.
1707 */
1708 if (beforetime < boundary && aftertime < boundary)
1709 {
1710 tm->tm_isdst = before_isdst;
1711 *tp = beforetime;
1712 return -(int) before_gmtoff;
1713 }
1714 if (beforetime > boundary && aftertime >= boundary)
1715 {
1716 tm->tm_isdst = after_isdst;
1717 *tp = aftertime;
1718 return -(int) after_gmtoff;
1719 }
1720
1721 /*
1722 * It's an invalid or ambiguous time due to timezone transition. In a
1723 * spring-forward transition, prefer the "before" interpretation; in a
1724 * fall-back transition, prefer "after". (We used to define and implement
1725 * this test as "prefer the standard-time interpretation", but that rule
1726 * does not help to resolve the behavior when both times are reported as
1727 * standard time; which does happen, eg Europe/Moscow in Oct 2014. Also,
1728 * in some zones such as Europe/Dublin, there is widespread confusion
1729 * about which time offset is "standard" time, so it's fortunate that our
1730 * behavior doesn't depend on that.)
1731 */
1732 if (beforetime > aftertime)
1733 {
1734 tm->tm_isdst = before_isdst;
1735 *tp = beforetime;
1736 return -(int) before_gmtoff;
1737 }
1738 tm->tm_isdst = after_isdst;
1739 *tp = aftertime;
1740 return -(int) after_gmtoff;
1741
1742overflow:
1743 /* Given date is out of range, so assume UTC */
1744 tm->tm_isdst = 0;
1745 *tp = 0;
1746 return 0;
1747}
#define IS_VALID_JULIAN(y, m, d)
Definition: timestamp.h:227
#define SECS_PER_DAY
Definition: timestamp.h:126
int pg_next_dst_boundary(const pg_time_t *timep, long int *before_gmtoff, int *before_isdst, pg_time_t *boundary, long int *after_gmtoff, int *after_isdst, const pg_tz *tz)
Definition: localtime.c:1611
long date
Definition: pgtypes_date.h:9

References date2j(), IS_VALID_JULIAN, MINS_PER_HOUR, pg_next_dst_boundary(), SECS_PER_DAY, SECS_PER_MINUTE, tm, pg_tm::tm_hour, pg_tm::tm_isdst, pg_tm::tm_mday, pg_tm::tm_min, pg_tm::tm_mon, pg_tm::tm_sec, pg_tm::tm_year, and UNIX_EPOCH_JDATE.

Referenced by DetermineTimeZoneAbbrevOffset(), and DetermineTimeZoneOffset().

◆ EncodeDateOnly()

void EncodeDateOnly ( struct pg_tm tm,
int  style,
char *  str 
)

Definition at line 4349 of file datetime.c.

4350{
4351 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4352
4353 switch (style)
4354 {
4355 case USE_ISO_DATES:
4356 case USE_XSD_DATES:
4357 /* compatible with ISO date formats */
4359 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4360 *str++ = '-';
4362 *str++ = '-';
4364 break;
4365
4366 case USE_SQL_DATES:
4367 /* compatible with Oracle/Ingres date formats */
4368 if (DateOrder == DATEORDER_DMY)
4369 {
4371 *str++ = '/';
4373 }
4374 else
4375 {
4377 *str++ = '/';
4379 }
4380 *str++ = '/';
4382 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4383 break;
4384
4385 case USE_GERMAN_DATES:
4386 /* German-style date format */
4388 *str++ = '.';
4390 *str++ = '.';
4392 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4393 break;
4394
4395 case USE_POSTGRES_DATES:
4396 default:
4397 /* traditional date-only style for Postgres */
4398 if (DateOrder == DATEORDER_DMY)
4399 {
4401 *str++ = '-';
4403 }
4404 else
4405 {
4407 *str++ = '-';
4409 }
4410 *str++ = '-';
4412 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4413 break;
4414 }
4415
4416 if (tm->tm_year <= 0)
4417 {
4418 memcpy(str, " BC", 3); /* Don't copy NUL */
4419 str += 3;
4420 }
4421 *str = '\0';
4422}
#define USE_SQL_DATES
Definition: miscadmin.h:238
#define USE_POSTGRES_DATES
Definition: miscadmin.h:236
#define USE_ISO_DATES
Definition: miscadmin.h:237
#define USE_XSD_DATES
Definition: miscadmin.h:240
#define USE_GERMAN_DATES
Definition: miscadmin.h:239

References Assert(), DateOrder, DATEORDER_DMY, MONTHS_PER_YEAR, pg_ultostr_zeropad(), str, tm, pg_tm::tm_mday, pg_tm::tm_mon, pg_tm::tm_year, USE_GERMAN_DATES, USE_ISO_DATES, USE_POSTGRES_DATES, USE_SQL_DATES, and USE_XSD_DATES.

Referenced by date_out(), JsonEncodeDateTime(), map_sql_value_to_xml_value(), and PGTYPESdate_to_asc().

◆ EncodeDateTime()

void EncodeDateTime ( struct pg_tm tm,
fsec_t  fsec,
bool  print_tz,
int  tz,
const char *  tzn,
int  style,
char *  str 
)

Definition at line 4464 of file datetime.c.

4465{
4466 int day;
4467
4468 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4469
4470 /*
4471 * Negative tm_isdst means we have no valid time zone translation.
4472 */
4473 if (tm->tm_isdst < 0)
4474 print_tz = false;
4475
4476 switch (style)
4477 {
4478 case USE_ISO_DATES:
4479 case USE_XSD_DATES:
4480 /* Compatible with ISO-8601 date formats */
4482 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4483 *str++ = '-';
4485 *str++ = '-';
4487 *str++ = (style == USE_ISO_DATES) ? ' ' : 'T';
4489 *str++ = ':';
4491 *str++ = ':';
4492 str = AppendTimestampSeconds(str, tm, fsec);
4493 if (print_tz)
4494 str = EncodeTimezone(str, tz, style);
4495 break;
4496
4497 case USE_SQL_DATES:
4498 /* Compatible with Oracle/Ingres date formats */
4499 if (DateOrder == DATEORDER_DMY)
4500 {
4502 *str++ = '/';
4504 }
4505 else
4506 {
4508 *str++ = '/';
4510 }
4511 *str++ = '/';
4513 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4514 *str++ = ' ';
4516 *str++ = ':';
4518 *str++ = ':';
4519 str = AppendTimestampSeconds(str, tm, fsec);
4520
4521 /*
4522 * Note: the uses of %.*s in this function would be risky if the
4523 * timezone names ever contain non-ASCII characters, since we are
4524 * not being careful to do encoding-aware clipping. However, all
4525 * TZ abbreviations in the IANA database are plain ASCII.
4526 */
4527 if (print_tz)
4528 {
4529 if (tzn)
4530 {
4531 sprintf(str, " %.*s", MAXTZLEN, tzn);
4532 str += strlen(str);
4533 }
4534 else
4535 str = EncodeTimezone(str, tz, style);
4536 }
4537 break;
4538
4539 case USE_GERMAN_DATES:
4540 /* German variant on European style */
4542 *str++ = '.';
4544 *str++ = '.';
4546 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4547 *str++ = ' ';
4549 *str++ = ':';
4551 *str++ = ':';
4552 str = AppendTimestampSeconds(str, tm, fsec);
4553
4554 if (print_tz)
4555 {
4556 if (tzn)
4557 {
4558 sprintf(str, " %.*s", MAXTZLEN, tzn);
4559 str += strlen(str);
4560 }
4561 else
4562 str = EncodeTimezone(str, tz, style);
4563 }
4564 break;
4565
4566 case USE_POSTGRES_DATES:
4567 default:
4568 /* Backward-compatible with traditional Postgres abstime dates */
4569 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4570 tm->tm_wday = j2day(day);
4571 memcpy(str, days[tm->tm_wday], 3);
4572 str += 3;
4573 *str++ = ' ';
4574 if (DateOrder == DATEORDER_DMY)
4575 {
4577 *str++ = ' ';
4578 memcpy(str, months[tm->tm_mon - 1], 3);
4579 str += 3;
4580 }
4581 else
4582 {
4583 memcpy(str, months[tm->tm_mon - 1], 3);
4584 str += 3;
4585 *str++ = ' ';
4587 }
4588 *str++ = ' ';
4590 *str++ = ':';
4592 *str++ = ':';
4593 str = AppendTimestampSeconds(str, tm, fsec);
4594 *str++ = ' ';
4596 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4597
4598 if (print_tz)
4599 {
4600 if (tzn)
4601 {
4602 sprintf(str, " %.*s", MAXTZLEN, tzn);
4603 str += strlen(str);
4604 }
4605 else
4606 {
4607 /*
4608 * We have a time zone, but no string version. Use the
4609 * numeric form, but be sure to include a leading space to
4610 * avoid formatting something which would be rejected by
4611 * the date/time parser later. - thomas 2001-10-19
4612 */
4613 *str++ = ' ';
4614 str = EncodeTimezone(str, tz, style);
4615 }
4616 }
4617 break;
4618 }
4619
4620 if (tm->tm_year <= 0)
4621 {
4622 memcpy(str, " BC", 3); /* Don't copy NUL */
4623 str += 3;
4624 }
4625 *str = '\0';
4626}
static char * EncodeTimezone(char *str, int tz, int style)
Definition: datetime.c:4311
int j2day(int date)
Definition: datetime.c:354
const char *const months[]
Definition: datetime.c:81
static char * AppendTimestampSeconds(char *cp, struct pg_tm *tm, fsec_t fsec)
Definition: datetime.c:521
#define MAXTZLEN
Definition: miscadmin.h:264

References AppendTimestampSeconds(), Assert(), date2j(), DateOrder, DATEORDER_DMY, days, EncodeTimezone(), j2day(), MAXTZLEN, months, MONTHS_PER_YEAR, pg_ultostr_zeropad(), sprintf, str, tm, pg_tm::tm_hour, pg_tm::tm_isdst, pg_tm::tm_mday, pg_tm::tm_min, pg_tm::tm_mon, pg_tm::tm_wday, pg_tm::tm_year, USE_GERMAN_DATES, USE_ISO_DATES, USE_POSTGRES_DATES, USE_SQL_DATES, and USE_XSD_DATES.

Referenced by JsonEncodeDateTime(), map_sql_value_to_xml_value(), PGTYPEStimestamp_to_asc(), timestamp_out(), timestamptz_out(), and timestamptz_to_str().

◆ EncodeInterval()

void EncodeInterval ( struct pg_itm itm,
int  style,
char *  str 
)

Definition at line 4707 of file datetime.c.

4708{
4709 char *cp = str;
4710 int year = itm->tm_year;
4711 int mon = itm->tm_mon;
4712 int64 mday = itm->tm_mday; /* tm_mday could be INT_MIN */
4713 int64 hour = itm->tm_hour;
4714 int min = itm->tm_min;
4715 int sec = itm->tm_sec;
4716 int fsec = itm->tm_usec;
4717 bool is_before = false;
4718 bool is_zero = true;
4719
4720 /*
4721 * The sign of year and month are guaranteed to match, since they are
4722 * stored internally as "month". But we'll need to check for is_before and
4723 * is_zero when determining the signs of day and hour/minute/seconds
4724 * fields.
4725 */
4726 switch (style)
4727 {
4728 /* SQL Standard interval format */
4730 {
4731 bool has_negative = year < 0 || mon < 0 ||
4732 mday < 0 || hour < 0 ||
4733 min < 0 || sec < 0 || fsec < 0;
4734 bool has_positive = year > 0 || mon > 0 ||
4735 mday > 0 || hour > 0 ||
4736 min > 0 || sec > 0 || fsec > 0;
4737 bool has_year_month = year != 0 || mon != 0;
4738 bool has_day_time = mday != 0 || hour != 0 ||
4739 min != 0 || sec != 0 || fsec != 0;
4740 bool has_day = mday != 0;
4741 bool sql_standard_value = !(has_negative && has_positive) &&
4742 !(has_year_month && has_day_time);
4743
4744 /*
4745 * SQL Standard wants only 1 "<sign>" preceding the whole
4746 * interval ... but can't do that if mixed signs.
4747 */
4748 if (has_negative && sql_standard_value)
4749 {
4750 *cp++ = '-';
4751 year = -year;
4752 mon = -mon;
4753 mday = -mday;
4754 hour = -hour;
4755 min = -min;
4756 sec = -sec;
4757 fsec = -fsec;
4758 }
4759
4760 if (!has_negative && !has_positive)
4761 {
4762 sprintf(cp, "0");
4763 }
4764 else if (!sql_standard_value)
4765 {
4766 /*
4767 * For non sql-standard interval values, force outputting
4768 * the signs to avoid ambiguities with intervals with
4769 * mixed sign components.
4770 */
4771 char year_sign = (year < 0 || mon < 0) ? '-' : '+';
4772 char day_sign = (mday < 0) ? '-' : '+';
4773 char sec_sign = (hour < 0 || min < 0 ||
4774 sec < 0 || fsec < 0) ? '-' : '+';
4775
4776 sprintf(cp, "%c%d-%d %c%" PRId64 " %c%" PRId64 ":%02d:",
4777 year_sign, abs(year), abs(mon),
4778 day_sign, i64abs(mday),
4779 sec_sign, i64abs(hour), abs(min));
4780 cp += strlen(cp);
4781 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4782 *cp = '\0';
4783 }
4784 else if (has_year_month)
4785 {
4786 sprintf(cp, "%d-%d", year, mon);
4787 }
4788 else if (has_day)
4789 {
4790 sprintf(cp, "%" PRId64 " %" PRId64 ":%02d:",
4791 mday, hour, min);
4792 cp += strlen(cp);
4793 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4794 *cp = '\0';
4795 }
4796 else
4797 {
4798 sprintf(cp, "%" PRId64 ":%02d:", hour, min);
4799 cp += strlen(cp);
4800 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4801 *cp = '\0';
4802 }
4803 }
4804 break;
4805
4806 /* ISO 8601 "time-intervals by duration only" */
4807 case INTSTYLE_ISO_8601:
4808 /* special-case zero to avoid printing nothing */
4809 if (year == 0 && mon == 0 && mday == 0 &&
4810 hour == 0 && min == 0 && sec == 0 && fsec == 0)
4811 {
4812 sprintf(cp, "PT0S");
4813 break;
4814 }
4815 *cp++ = 'P';
4816 cp = AddISO8601IntPart(cp, year, 'Y');
4817 cp = AddISO8601IntPart(cp, mon, 'M');
4818 cp = AddISO8601IntPart(cp, mday, 'D');
4819 if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4820 *cp++ = 'T';
4821 cp = AddISO8601IntPart(cp, hour, 'H');
4822 cp = AddISO8601IntPart(cp, min, 'M');
4823 if (sec != 0 || fsec != 0)
4824 {
4825 if (sec < 0 || fsec < 0)
4826 *cp++ = '-';
4827 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4828 *cp++ = 'S';
4829 *cp++ = '\0';
4830 }
4831 break;
4832
4833 /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4834 case INTSTYLE_POSTGRES:
4835 cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4836
4837 /*
4838 * Ideally we should spell out "month" like we do for "year" and
4839 * "day". However, for backward compatibility, we can't easily
4840 * fix this. bjm 2011-05-24
4841 */
4842 cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4843 cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4844 if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4845 {
4846 bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4847
4848 sprintf(cp, "%s%s%02" PRId64 ":%02d:",
4849 is_zero ? "" : " ",
4850 (minus ? "-" : (is_before ? "+" : "")),
4851 i64abs(hour), abs(min));
4852 cp += strlen(cp);
4853 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4854 *cp = '\0';
4855 }
4856 break;
4857
4858 /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4860 default:
4861 strcpy(cp, "@");
4862 cp++;
4863 cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4864 cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4865 cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4866 cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4867 cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4868 if (sec != 0 || fsec != 0)
4869 {
4870 *cp++ = ' ';
4871 if (sec < 0 || (sec == 0 && fsec < 0))
4872 {
4873 if (is_zero)
4874 is_before = true;
4875 else if (!is_before)
4876 *cp++ = '-';
4877 }
4878 else if (is_before)
4879 *cp++ = '-';
4880 cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4881 /* We output "ago", not negatives, so use abs(). */
4882 sprintf(cp, " sec%s",
4883 (abs(sec) != 1 || fsec != 0) ? "s" : "");
4884 is_zero = false;
4885 }
4886 /* identically zero? then put in a unitless zero... */
4887 if (is_zero)
4888 strcat(cp, " 0");
4889 if (is_before)
4890 strcat(cp, " ago");
4891 break;
4892 }
4893}
static char * AddPostgresIntPart(char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
Definition: datetime.c:4645
static char * AddISO8601IntPart(char *cp, int64 value, char units)
Definition: datetime.c:4635
static char * AddVerboseIntPart(char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
Definition: datetime.c:4668
#define MAX_INTERVAL_PRECISION
Definition: timestamp.h:93
#define INTSTYLE_POSTGRES_VERBOSE
Definition: miscadmin.h:258
#define INTSTYLE_ISO_8601
Definition: miscadmin.h:260
#define INTSTYLE_POSTGRES
Definition: miscadmin.h:257
int tm_year
Definition: timestamp.h:73
int tm_mon
Definition: timestamp.h:72
int tm_mday
Definition: timestamp.h:71

References AddISO8601IntPart(), AddPostgresIntPart(), AddVerboseIntPart(), AppendSeconds(), INTSTYLE_ISO_8601, INTSTYLE_POSTGRES, INTSTYLE_POSTGRES_VERBOSE, INTSTYLE_SQL_STANDARD, MAX_INTERVAL_PRECISION, sprintf, str, pg_itm::tm_hour, pg_itm::tm_mday, pg_itm::tm_min, pg_itm::tm_mon, pg_itm::tm_sec, pg_itm::tm_usec, and pg_itm::tm_year.

Referenced by interval_out().

◆ EncodeTimeOnly()

void EncodeTimeOnly ( struct pg_tm tm,
fsec_t  fsec,
bool  print_tz,
int  tz,
int  style,
char *  str 
)

Definition at line 4434 of file datetime.c.

4435{
4437 *str++ = ':';
4439 *str++ = ':';
4440 str = AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
4441 if (print_tz)
4442 str = EncodeTimezone(str, tz, style);
4443 *str = '\0';
4444}
#define MAX_TIME_PRECISION
Definition: date.h:45

References AppendSeconds(), EncodeTimezone(), MAX_TIME_PRECISION, pg_ultostr_zeropad(), str, tm, pg_tm::tm_hour, pg_tm::tm_min, and pg_tm::tm_sec.

Referenced by JsonEncodeDateTime(), time_out(), and timetz_out().

◆ EncodeTimezone()

static char * EncodeTimezone ( char *  str,
int  tz,
int  style 
)
static

Definition at line 4311 of file datetime.c.

4312{
4313 int hour,
4314 min,
4315 sec;
4316
4317 sec = abs(tz);
4318 min = sec / SECS_PER_MINUTE;
4319 sec -= min * SECS_PER_MINUTE;
4320 hour = min / MINS_PER_HOUR;
4321 min -= hour * MINS_PER_HOUR;
4322
4323 /* TZ is negated compared to sign we wish to display ... */
4324 *str++ = (tz <= 0 ? '+' : '-');
4325
4326 if (sec != 0)
4327 {
4328 str = pg_ultostr_zeropad(str, hour, 2);
4329 *str++ = ':';
4330 str = pg_ultostr_zeropad(str, min, 2);
4331 *str++ = ':';
4332 str = pg_ultostr_zeropad(str, sec, 2);
4333 }
4334 else if (min != 0 || style == USE_XSD_DATES)
4335 {
4336 str = pg_ultostr_zeropad(str, hour, 2);
4337 *str++ = ':';
4338 str = pg_ultostr_zeropad(str, min, 2);
4339 }
4340 else
4341 str = pg_ultostr_zeropad(str, hour, 2);
4342 return str;
4343}

References MINS_PER_HOUR, pg_ultostr_zeropad(), SECS_PER_MINUTE, str, and USE_XSD_DATES.

Referenced by EncodeDateTime(), and EncodeTimeOnly().

◆ FetchDynamicTimeZone()

static pg_tz * FetchDynamicTimeZone ( TimeZoneAbbrevTable tbl,
const datetkn tp,
DateTimeErrorExtra extra 
)
static

Definition at line 5092 of file datetime.c.

5094{
5095 DynamicZoneAbbrev *dtza;
5096
5097 /* Just some sanity checks to prevent indexing off into nowhere */
5098 Assert(tp->type == DYNTZ);
5099 Assert(tp->value > 0 && tp->value < tbl->tblsize);
5100
5101 dtza = (DynamicZoneAbbrev *) ((char *) tbl + tp->value);
5102
5103 /* Look up the underlying zone if we haven't already */
5104 if (dtza->tz == NULL)
5105 {
5106 dtza->tz = pg_tzset(dtza->zone);
5107 if (dtza->tz == NULL)
5108 {
5109 /* Ooops, bogus zone name in config file entry */
5110 extra->dtee_timezone = dtza->zone;
5111 extra->dtee_abbrev = tp->token;
5112 }
5113 }
5114 return dtza->tz;
5115}

References Assert(), DateTimeErrorExtra::dtee_abbrev, DateTimeErrorExtra::dtee_timezone, DYNTZ, pg_tzset(), TimeZoneAbbrevTable::tblsize, datetkn::token, datetkn::type, DynamicZoneAbbrev::tz, datetkn::value, and DynamicZoneAbbrev::zone.

Referenced by DecodeTimezoneAbbrev(), DecodeTimezoneAbbrevPrefix(), and pg_timezone_abbrevs_abbrevs().

◆ GetCurrentDateTime()

void GetCurrentDateTime ( struct pg_tm tm)

Definition at line 376 of file datetime.c.

377{
378 fsec_t fsec;
379
380 GetCurrentTimeUsec(tm, &fsec, NULL);
381}

References GetCurrentTimeUsec(), and tm.

Referenced by DecodeDateTime(), DecodeTimeOnly(), GetSQLCurrentDate(), PGTYPESdate_today(), PGTYPEStimestamp_current(), and time_timetz().

◆ GetCurrentTimeUsec()

void GetCurrentTimeUsec ( struct pg_tm tm,
fsec_t fsec,
int *  tzp 
)

Definition at line 397 of file datetime.c.

398{
400
401 /*
402 * The cache key must include both current time and current timezone. By
403 * representing the timezone by just a pointer, we're assuming that
404 * distinct timezone settings could never have the same pointer value.
405 * This is true by virtue of the hashtable used inside pg_tzset();
406 * however, it might need another look if we ever allow entries in that
407 * hash to be recycled.
408 */
409 static TimestampTz cache_ts = 0;
410 static pg_tz *cache_timezone = NULL;
411 static struct pg_tm cache_tm;
412 static fsec_t cache_fsec;
413 static int cache_tz;
414
415 if (cur_ts != cache_ts || session_timezone != cache_timezone)
416 {
417 /*
418 * Make sure cache is marked invalid in case of error after partial
419 * update within timestamp2tm.
420 */
421 cache_timezone = NULL;
422
423 /*
424 * Perform the computation, storing results into cache. We do not
425 * really expect any error here, since current time surely ought to be
426 * within range, but check just for sanity's sake.
427 */
428 if (timestamp2tm(cur_ts, &cache_tz, &cache_tm, &cache_fsec,
429 NULL, session_timezone) != 0)
431 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
432 errmsg("timestamp out of range")));
433
434 /* OK, so mark the cache valid. */
435 cache_ts = cur_ts;
436 cache_timezone = session_timezone;
437 }
438
439 *tm = cache_tm;
440 *fsec = cache_fsec;
441 if (tzp != NULL)
442 *tzp = cache_tz;
443}
int64 TimestampTz
Definition: timestamp.h:39
TimestampTz GetCurrentTransactionStartTimestamp(void)
Definition: xact.c:871

References ereport, errcode(), errmsg(), ERROR, GetCurrentTransactionStartTimestamp(), session_timezone, timestamp2tm(), and tm.

Referenced by DecodeDateTime(), DecodeTimeOnly(), GetCurrentDateTime(), GetSQLCurrentTime(), and GetSQLLocalTime().

◆ InstallTimeZoneAbbrevs()

void InstallTimeZoneAbbrevs ( TimeZoneAbbrevTable tbl)

Definition at line 5079 of file datetime.c.

5080{
5081 zoneabbrevtbl = tbl;
5082 /* reset tzabbrevcache, which may contain results from old table */
5083 memset(tzabbrevcache, 0, sizeof(tzabbrevcache));
5084}

References tzabbrevcache, and zoneabbrevtbl.

Referenced by assign_timezone_abbreviations().

◆ int64_multiply_add()

static bool int64_multiply_add ( int64  val,
int64  multiplier,
int64 sum 
)
static

Definition at line 532 of file datetime.c.

533{
534 int64 product;
535
536 if (pg_mul_s64_overflow(val, multiplier, &product) ||
537 pg_add_s64_overflow(*sum, product, sum))
538 return false;
539 return true;
540}

References pg_add_s64_overflow(), pg_mul_s64_overflow(), and val.

Referenced by AdjustMicroseconds(), and DecodeTimeForInterval().

◆ ISO8601IntegerWidth()

static int ISO8601IntegerWidth ( char *  fieldstart)
static

Definition at line 3924 of file datetime.c.

3925{
3926 /* We might have had a leading '-' */
3927 if (*fieldstart == '-')
3928 fieldstart++;
3929 return strspn(fieldstart, "0123456789");
3930}

Referenced by DecodeISO8601Interval().

◆ j2date()

void j2date ( int  jd,
int *  year,
int *  month,
int *  day 
)

Definition at line 321 of file datetime.c.

322{
323 unsigned int julian;
324 unsigned int quad;
325 unsigned int extra;
326 int y;
327
328 julian = jd;
329 julian += 32044;
330 quad = julian / 146097;
331 extra = (julian - quad * 146097) * 4 + 3;
332 julian += 60 + quad * 3 + extra / 146097;
333 quad = julian / 1461;
334 julian -= quad * 1461;
335 y = julian * 4 / 1461;
336 julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
337 + 123;
338 y += quad * 4;
339 *year = y - 4800;
340 quad = julian * 2141 / 65536;
341 *day = julian - 7834 * quad / 256;
342 *month = (quad + 10) % MONTHS_PER_YEAR + 1;
343} /* j2date() */
int y
Definition: isn.c:76

References MONTHS_PER_YEAR, and y.

Referenced by date2timestamptz_safe(), date_out(), DecodeDateTime(), DecodeTimeOnly(), do_to_timestamp(), executeDateTimeMethod(), extract_date(), isoweek2date(), isoweekdate2date(), JsonEncodeDateTime(), map_sql_value_to_xml_value(), PGTYPESdate_fmt_asc(), PGTYPESdate_julmdy(), PGTYPESdate_to_asc(), timestamp2tm(), timestamp_pl_interval(), timestamptz_pl_interval_internal(), and ValidateDate().

◆ j2day()

int j2day ( int  date)

Definition at line 354 of file datetime.c.

355{
356 date += 1;
357 date %= 7;
358 /* Cope if division truncates towards zero, as it probably does */
359 if (date < 0)
360 date += 7;
361
362 return date;
363} /* j2day() */

Referenced by date2isoweek(), date2isoyear(), EncodeDateTime(), extract_date(), isoweek2j(), timestamp_part_common(), and timestamptz_part_common().

◆ ParseDateTime()

int ParseDateTime ( const char *  timestr,
char *  workbuf,
size_t  buflen,
char **  field,
int *  ftype,
int  maxfields,
int *  numfields 
)

Definition at line 773 of file datetime.c.

775{
776 int nf = 0;
777 const char *cp = timestr;
778 char *bufp = workbuf;
779 const char *bufend = workbuf + buflen;
780
781 /*
782 * Set the character pointed-to by "bufptr" to "newchar", and increment
783 * "bufptr". "end" gives the end of the buffer -- we return an error if
784 * there is no space left to append a character to the buffer. Note that
785 * "bufptr" is evaluated twice.
786 */
787#define APPEND_CHAR(bufptr, end, newchar) \
788 do \
789 { \
790 if (((bufptr) + 1) >= (end)) \
791 return DTERR_BAD_FORMAT; \
792 *(bufptr)++ = newchar; \
793 } while (0)
794
795 /* outer loop through fields */
796 while (*cp != '\0')
797 {
798 /* Ignore spaces between fields */
799 if (isspace((unsigned char) *cp))
800 {
801 cp++;
802 continue;
803 }
804
805 /* Record start of current field */
806 if (nf >= maxfields)
807 return DTERR_BAD_FORMAT;
808 field[nf] = bufp;
809
810 /* leading digit? then date or time */
811 if (isdigit((unsigned char) *cp))
812 {
813 APPEND_CHAR(bufp, bufend, *cp++);
814 while (isdigit((unsigned char) *cp))
815 APPEND_CHAR(bufp, bufend, *cp++);
816
817 /* time field? */
818 if (*cp == ':')
819 {
820 ftype[nf] = DTK_TIME;
821 APPEND_CHAR(bufp, bufend, *cp++);
822 while (isdigit((unsigned char) *cp) ||
823 (*cp == ':') || (*cp == '.'))
824 APPEND_CHAR(bufp, bufend, *cp++);
825 }
826 /* date field? allow embedded text month */
827 else if (*cp == '-' || *cp == '/' || *cp == '.')
828 {
829 /* save delimiting character to use later */
830 char delim = *cp;
831
832 APPEND_CHAR(bufp, bufend, *cp++);
833 /* second field is all digits? then no embedded text month */
834 if (isdigit((unsigned char) *cp))
835 {
836 ftype[nf] = ((delim == '.') ? DTK_NUMBER : DTK_DATE);
837 while (isdigit((unsigned char) *cp))
838 APPEND_CHAR(bufp, bufend, *cp++);
839
840 /*
841 * insist that the delimiters match to get a three-field
842 * date.
843 */
844 if (*cp == delim)
845 {
846 ftype[nf] = DTK_DATE;
847 APPEND_CHAR(bufp, bufend, *cp++);
848 while (isdigit((unsigned char) *cp) || *cp == delim)
849 APPEND_CHAR(bufp, bufend, *cp++);
850 }
851 }
852 else
853 {
854 ftype[nf] = DTK_DATE;
855 while (isalnum((unsigned char) *cp) || *cp == delim)
856 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
857 }
858 }
859
860 /*
861 * otherwise, number only and will determine year, month, day, or
862 * concatenated fields later...
863 */
864 else
865 ftype[nf] = DTK_NUMBER;
866 }
867 /* Leading decimal point? Then fractional seconds... */
868 else if (*cp == '.')
869 {
870 APPEND_CHAR(bufp, bufend, *cp++);
871 while (isdigit((unsigned char) *cp))
872 APPEND_CHAR(bufp, bufend, *cp++);
873
874 ftype[nf] = DTK_NUMBER;
875 }
876
877 /*
878 * text? then date string, month, day of week, special, or timezone
879 */
880 else if (isalpha((unsigned char) *cp))
881 {
882 bool is_date;
883
884 ftype[nf] = DTK_STRING;
885 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
886 while (isalpha((unsigned char) *cp))
887 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
888
889 /*
890 * Dates can have embedded '-', '/', or '.' separators. It could
891 * also be a timezone name containing embedded '/', '+', '-', '_',
892 * or ':' (but '_' or ':' can't be the first punctuation). If the
893 * next character is a digit or '+', we need to check whether what
894 * we have so far is a recognized non-timezone keyword --- if so,
895 * don't believe that this is the start of a timezone.
896 */
897 is_date = false;
898 if (*cp == '-' || *cp == '/' || *cp == '.')
899 is_date = true;
900 else if (*cp == '+' || isdigit((unsigned char) *cp))
901 {
902 *bufp = '\0'; /* null-terminate current field value */
903 /* we need search only the core token table, not TZ names */
904 if (datebsearch(field[nf], datetktbl, szdatetktbl) == NULL)
905 is_date = true;
906 }
907 if (is_date)
908 {
909 ftype[nf] = DTK_DATE;
910 do
911 {
912 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
913 } while (*cp == '+' || *cp == '-' ||
914 *cp == '/' || *cp == '_' ||
915 *cp == '.' || *cp == ':' ||
916 isalnum((unsigned char) *cp));
917 }
918 }
919 /* sign? then special or numeric timezone */
920 else if (*cp == '+' || *cp == '-')
921 {
922 APPEND_CHAR(bufp, bufend, *cp++);
923 /* soak up leading whitespace */
924 while (isspace((unsigned char) *cp))
925 cp++;
926 /* numeric timezone? */
927 /* note that "DTK_TZ" could also be a signed float or yyyy-mm */
928 if (isdigit((unsigned char) *cp))
929 {
930 ftype[nf] = DTK_TZ;
931 APPEND_CHAR(bufp, bufend, *cp++);
932 while (isdigit((unsigned char) *cp) ||
933 *cp == ':' || *cp == '.' || *cp == '-')
934 APPEND_CHAR(bufp, bufend, *cp++);
935 }
936 /* special? */
937 else if (isalpha((unsigned char) *cp))
938 {
939 ftype[nf] = DTK_SPECIAL;
940 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
941 while (isalpha((unsigned char) *cp))
942 APPEND_CHAR(bufp, bufend, pg_tolower((unsigned char) *cp++));
943 }
944 /* otherwise something wrong... */
945 else
946 return DTERR_BAD_FORMAT;
947 }
948 /* ignore other punctuation but use as delimiter */
949 else if (ispunct((unsigned char) *cp))
950 {
951 cp++;
952 continue;
953 }
954 /* otherwise, something is not right... */
955 else
956 return DTERR_BAD_FORMAT;
957
958 /* force in a delimiter after each field */
959 *bufp++ = '\0';
960 nf++;
961 }
962
963 *numfields = nf;
964
965 return 0;
966}
#define APPEND_CHAR(bufptr, end, newchar)

References APPEND_CHAR, datebsearch(), datetktbl, DTERR_BAD_FORMAT, DTK_DATE, DTK_NUMBER, DTK_SPECIAL, DTK_STRING, DTK_TIME, DTK_TZ, pg_tolower(), and szdatetktbl.

Referenced by check_recovery_target_time(), date_in(), interval_in(), PGTYPESdate_from_asc(), PGTYPESinterval_from_asc(), PGTYPEStimestamp_from_asc(), time_in(), timestamp_in(), timestamptz_in(), and timetz_in().

◆ ParseFraction()

static int ParseFraction ( char *  cp,
double *  frac 
)
static

Definition at line 690 of file datetime.c.

691{
692 /* Caller should always pass the start of the fraction part */
693 Assert(*cp == '.');
694
695 /*
696 * We want to allow just "." with no digits, but some versions of strtod
697 * will report EINVAL for that, so special-case it.
698 */
699 if (cp[1] == '\0')
700 {
701 *frac = 0;
702 }
703 else
704 {
705 /*
706 * On the other hand, let's reject anything that's not digits after
707 * the ".". strtod is happy with input like ".123e9", but that'd
708 * break callers' expectation that the result is in 0..1. (It's quite
709 * difficult to get here with such input, but not impossible.)
710 */
711 if (strspn(cp + 1, "0123456789") != strlen(cp + 1))
712 return DTERR_BAD_FORMAT;
713
714 errno = 0;
715 *frac = strtod(cp, &cp);
716 /* check for parse failure (probably redundant given prior check) */
717 if (*cp != '\0' || errno != 0)
718 return DTERR_BAD_FORMAT;
719 }
720 return 0;
721}

References Assert(), and DTERR_BAD_FORMAT.

Referenced by DecodeDateTime(), DecodeInterval(), DecodeTimeOnly(), and ParseFractionalSecond().

◆ ParseFractionalSecond()

static int ParseFractionalSecond ( char *  cp,
fsec_t fsec 
)
static

Definition at line 728 of file datetime.c.

729{
730 double frac;
731 int dterr;
732
733 dterr = ParseFraction(cp, &frac);
734 if (dterr)
735 return dterr;
736 *fsec = rint(frac * 1000000);
737 return 0;
738}

References ParseFraction().

Referenced by DecodeNumber(), DecodeNumberField(), and DecodeTimeCommon().

◆ ParseISO8601Number()

static int ParseISO8601Number ( char *  str,
char **  endptr,
int64 ipart,
double *  fpart 
)
static

Definition at line 3882 of file datetime.c.

3883{
3884 double val;
3885
3886 /*
3887 * Historically this has accepted anything that strtod() would take,
3888 * notably including "e" notation, so continue doing that. This is
3889 * slightly annoying because the precision of double is less than that of
3890 * int64, so we would lose accuracy for inputs larger than 2^53 or so.
3891 * However, historically we rejected inputs outside the int32 range,
3892 * making that concern moot. What we do now is reject abs(val) above
3893 * 1.0e15 (a round number a bit less than 2^50), so that any accepted
3894 * value will have an exact integer part, and thereby a fraction part with
3895 * abs(*fpart) less than 1. In the absence of field complaints it doesn't
3896 * seem worth working harder.
3897 */
3898 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3899 return DTERR_BAD_FORMAT;
3900 errno = 0;
3901 val = strtod(str, endptr);
3902 /* did we not see anything that looks like a double? */
3903 if (*endptr == str || errno != 0)
3904 return DTERR_BAD_FORMAT;
3905 /* watch out for overflow, including infinities; reject NaN too */
3906 if (isnan(val) || val < -1.0e15 || val > 1.0e15)
3907 return DTERR_FIELD_OVERFLOW;
3908 /* be very sure we truncate towards zero (cf dtrunc()) */
3909 if (val >= 0)
3910 *ipart = (int64) floor(val);
3911 else
3912 *ipart = (int64) -floor(-val);
3913 *fpart = val - *ipart;
3914 /* Callers expect this to hold */
3915 Assert(*fpart > -1.0 && *fpart < 1.0);
3916 return 0;
3917}

References Assert(), DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, str, and val.

Referenced by DecodeISO8601Interval().

◆ pg_timezone_abbrevs_abbrevs()

Datum pg_timezone_abbrevs_abbrevs ( PG_FUNCTION_ARGS  )

Definition at line 5211 of file datetime.c.

5212{
5213 FuncCallContext *funcctx;
5214 int *pindex;
5215 Datum result;
5216 HeapTuple tuple;
5217 Datum values[3];
5218 bool nulls[3] = {0};
5219 const datetkn *tp;
5220 char buffer[TOKMAXLEN + 1];
5221 int gmtoffset;
5222 bool is_dst;
5223 unsigned char *p;
5224 struct pg_itm_in itm_in;
5225 Interval *resInterval;
5226
5227 /* stuff done only on the first call of the function */
5228 if (SRF_IS_FIRSTCALL())
5229 {
5230 TupleDesc tupdesc;
5231 MemoryContext oldcontext;
5232
5233 /* create a function context for cross-call persistence */
5234 funcctx = SRF_FIRSTCALL_INIT();
5235
5236 /*
5237 * switch to memory context appropriate for multiple function calls
5238 */
5239 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5240
5241 /* allocate memory for user context */
5242 pindex = (int *) palloc(sizeof(int));
5243 *pindex = 0;
5244 funcctx->user_fctx = pindex;
5245
5246 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
5247 elog(ERROR, "return type must be a row type");
5248 funcctx->tuple_desc = tupdesc;
5249
5250 MemoryContextSwitchTo(oldcontext);
5251 }
5252
5253 /* stuff done on every call of the function */
5254 funcctx = SRF_PERCALL_SETUP();
5255 pindex = (int *) funcctx->user_fctx;
5256
5257 if (zoneabbrevtbl == NULL ||
5258 *pindex >= zoneabbrevtbl->numabbrevs)
5259 SRF_RETURN_DONE(funcctx);
5260
5261 tp = zoneabbrevtbl->abbrevs + *pindex;
5262
5263 switch (tp->type)
5264 {
5265 case TZ:
5266 gmtoffset = tp->value;
5267 is_dst = false;
5268 break;
5269 case DTZ:
5270 gmtoffset = tp->value;
5271 is_dst = true;
5272 break;
5273 case DYNTZ:
5274 {
5275 /* Determine the current meaning of the abbrev */
5276 pg_tz *tzp;
5277 DateTimeErrorExtra extra;
5279 int isdst;
5280
5281 tzp = FetchDynamicTimeZone(zoneabbrevtbl, tp, &extra);
5282 if (tzp == NULL)
5284 NULL, NULL, NULL);
5287 tp->token,
5288 tzp,
5289 &isdst);
5290 is_dst = (bool) isdst;
5291 break;
5292 }
5293 default:
5294 elog(ERROR, "unrecognized timezone type %d", (int) tp->type);
5295 gmtoffset = 0; /* keep compiler quiet */
5296 is_dst = false;
5297 break;
5298 }
5299
5300 /*
5301 * Convert name to text, using upcasing conversion that is the inverse of
5302 * what ParseDateTime() uses.
5303 */
5304 strlcpy(buffer, tp->token, sizeof(buffer));
5305 for (p = (unsigned char *) buffer; *p; p++)
5306 *p = pg_toupper(*p);
5307
5308 values[0] = CStringGetTextDatum(buffer);
5309
5310 /* Convert offset (in seconds) to an interval; can't overflow */
5311 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5312 itm_in.tm_usec = (int64) gmtoffset * USECS_PER_SEC;
5313 resInterval = (Interval *) palloc(sizeof(Interval));
5314 (void) itmin2interval(&itm_in, resInterval);
5315 values[1] = IntervalPGetDatum(resInterval);
5316
5317 values[2] = BoolGetDatum(is_dst);
5318
5319 (*pindex)++;
5320
5321 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5322 result = HeapTupleGetDatum(tuple);
5323
5324 SRF_RETURN_NEXT(funcctx, result);
5325}
int DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr, pg_tz *tzp, int *isdst)
Definition: datetime.c:1803
int itmin2interval(struct pg_itm_in *itm_in, Interval *span)
Definition: timestamp.c:2115
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1609
static Datum values[MAXATTR]
Definition: bootstrap.c:153
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define MemSet(start, val, len)
Definition: c.h:1024
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:81
void * palloc(Size size)
Definition: mcxt.c:1365
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
uint64_t Datum
Definition: postgres.h:70
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc tuple_desc
Definition: funcapi.h:112
static Datum IntervalPGetDatum(const Interval *X)
Definition: timestamp.h:58

References TimeZoneAbbrevTable::abbrevs, BoolGetDatum(), CStringGetTextDatum, DateTimeParseError(), DetermineTimeZoneAbbrevOffsetTS(), DTERR_BAD_ZONE_ABBREV, DTZ, DYNTZ, elog, ERROR, FetchDynamicTimeZone(), get_call_result_type(), GetCurrentTransactionStartTimestamp(), heap_form_tuple(), HeapTupleGetDatum(), if(), IntervalPGetDatum(), itmin2interval(), MemoryContextSwitchTo(), MemSet, FuncCallContext::multi_call_memory_ctx, now(), TimeZoneAbbrevTable::numabbrevs, palloc(), pg_toupper(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, strlcpy(), pg_itm_in::tm_usec, datetkn::token, TOKMAXLEN, FuncCallContext::tuple_desc, datetkn::type, TYPEFUNC_COMPOSITE, TZ, USECS_PER_SEC, FuncCallContext::user_fctx, datetkn::value, values, and zoneabbrevtbl.

◆ pg_timezone_abbrevs_zone()

Datum pg_timezone_abbrevs_zone ( PG_FUNCTION_ARGS  )

Definition at line 5124 of file datetime.c.

5125{
5126 FuncCallContext *funcctx;
5127 int *pindex;
5128 Datum result;
5129 HeapTuple tuple;
5130 Datum values[3];
5131 bool nulls[3] = {0};
5134 const char *abbrev;
5135 long int gmtoff;
5136 int isdst;
5137 struct pg_itm_in itm_in;
5138 Interval *resInterval;
5139
5140 /* stuff done only on the first call of the function */
5141 if (SRF_IS_FIRSTCALL())
5142 {
5143 TupleDesc tupdesc;
5144 MemoryContext oldcontext;
5145
5146 /* create a function context for cross-call persistence */
5147 funcctx = SRF_FIRSTCALL_INIT();
5148
5149 /*
5150 * switch to memory context appropriate for multiple function calls
5151 */
5152 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5153
5154 /* allocate memory for user context */
5155 pindex = (int *) palloc(sizeof(int));
5156 *pindex = 0;
5157 funcctx->user_fctx = pindex;
5158
5159 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
5160 elog(ERROR, "return type must be a row type");
5161 funcctx->tuple_desc = tupdesc;
5162
5163 MemoryContextSwitchTo(oldcontext);
5164 }
5165
5166 /* stuff done on every call of the function */
5167 funcctx = SRF_PERCALL_SETUP();
5168 pindex = (int *) funcctx->user_fctx;
5169
5170 while ((abbrev = pg_get_next_timezone_abbrev(pindex,
5171 session_timezone)) != NULL)
5172 {
5173 /* Ignore abbreviations that aren't all-alphabetic */
5174 if (strspn(abbrev, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") != strlen(abbrev))
5175 continue;
5176
5177 /* Determine the current meaning of the abbrev */
5178 if (!pg_interpret_timezone_abbrev(abbrev,
5179 &t,
5180 &gmtoff,
5181 &isdst,
5183 continue; /* hm, not actually used in this zone? */
5184
5185 values[0] = CStringGetTextDatum(abbrev);
5186
5187 /* Convert offset (in seconds) to an interval; can't overflow */
5188 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5189 itm_in.tm_usec = (int64) gmtoff * USECS_PER_SEC;
5190 resInterval = (Interval *) palloc(sizeof(Interval));
5191 (void) itmin2interval(&itm_in, resInterval);
5192 values[1] = IntervalPGetDatum(resInterval);
5193
5194 values[2] = BoolGetDatum(isdst);
5195
5196 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5197 result = HeapTupleGetDatum(tuple);
5198
5199 SRF_RETURN_NEXT(funcctx, result);
5200 }
5201
5202 SRF_RETURN_DONE(funcctx);
5203}
while(p+4<=pend)
const char * pg_get_next_timezone_abbrev(int *indx, const pg_tz *tz)
Definition: localtime.c:1937

References tzEntry::abbrev, BoolGetDatum(), CStringGetTextDatum, elog, ERROR, get_call_result_type(), GetCurrentTransactionStartTimestamp(), heap_form_tuple(), HeapTupleGetDatum(), IntervalPGetDatum(), itmin2interval(), MemoryContextSwitchTo(), MemSet, FuncCallContext::multi_call_memory_ctx, now(), palloc(), pg_get_next_timezone_abbrev(), pg_interpret_timezone_abbrev(), session_timezone, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, timestamptz_to_time_t(), pg_itm_in::tm_usec, FuncCallContext::tuple_desc, TYPEFUNC_COMPOSITE, USECS_PER_SEC, FuncCallContext::user_fctx, values, and while().

◆ pg_timezone_names()

Datum pg_timezone_names ( PG_FUNCTION_ARGS  )

Definition at line 5332 of file datetime.c.

5333{
5334 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
5335 pg_tzenum *tzenum;
5336 pg_tz *tz;
5337 Datum values[4];
5338 bool nulls[4] = {0};
5339 int tzoff;
5340 struct pg_tm tm;
5341 fsec_t fsec;
5342 const char *tzn;
5343 Interval *resInterval;
5344 struct pg_itm_in itm_in;
5345
5346 InitMaterializedSRF(fcinfo, 0);
5347
5348 /* initialize timezone scanning code */
5349 tzenum = pg_tzenumerate_start();
5350
5351 /* search for another zone to display */
5352 for (;;)
5353 {
5354 tz = pg_tzenumerate_next(tzenum);
5355 if (!tz)
5356 break;
5357
5358 /* Convert now() to local time in this zone */
5360 &tzoff, &tm, &fsec, &tzn, tz) != 0)
5361 continue; /* ignore if conversion fails */
5362
5363 /*
5364 * IANA's rather silly "Factory" time zone used to emit ridiculously
5365 * long "abbreviations" such as "Local time zone must be set--see zic
5366 * manual page" or "Local time zone must be set--use tzsetup". While
5367 * modern versions of tzdb emit the much saner "-00", it seems some
5368 * benighted packagers are hacking the IANA data so that it continues
5369 * to produce these strings. To prevent producing a weirdly wide
5370 * abbrev column, reject ridiculously long abbreviations.
5371 */
5372 if (tzn && strlen(tzn) > 31)
5373 continue;
5374
5376 values[1] = CStringGetTextDatum(tzn ? tzn : "");
5377
5378 /* Convert tzoff to an interval; can't overflow */
5379 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5380 itm_in.tm_usec = (int64) -tzoff * USECS_PER_SEC;
5381 resInterval = (Interval *) palloc(sizeof(Interval));
5382 (void) itmin2interval(&itm_in, resInterval);
5383 values[2] = IntervalPGetDatum(resInterval);
5384
5385 values[3] = BoolGetDatum(tm.tm_isdst > 0);
5386
5387 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
5388 }
5389
5390 pg_tzenumerate_end(tzenum);
5391 return (Datum) 0;
5392}
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
pg_tz * pg_tzenumerate_next(pg_tzenum *dir)
Definition: pgtz.c:426
const char * pg_get_timezone_name(pg_tz *tz)
Definition: localtime.c:1990
void pg_tzenumerate_end(pg_tzenum *dir)
Definition: pgtz.c:414
pg_tzenum * pg_tzenumerate_start(void)
Definition: pgtz.c:397
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784

References values.

◆ TemporalSimplify()

Node * TemporalSimplify ( int32  max_precis,
Node node 
)

Definition at line 4962 of file datetime.c.

4963{
4964 FuncExpr *expr = castNode(FuncExpr, node);
4965 Node *ret = NULL;
4966 Node *typmod;
4967
4968 Assert(list_length(expr->args) >= 2);
4969
4970 typmod = (Node *) lsecond(expr->args);
4971
4972 if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
4973 {
4974 Node *source = (Node *) linitial(expr->args);
4975 int32 old_precis = exprTypmod(source);
4976 int32 new_precis = DatumGetInt32(((Const *) typmod)->constvalue);
4977
4978 if (new_precis < 0 || new_precis == max_precis ||
4979 (old_precis >= 0 && new_precis >= old_precis))
4980 ret = relabel_to_typmod(source, new_precis);
4981 }
4982
4983 return ret;
4984}
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:301
Node * relabel_to_typmod(Node *expr, int32 typmod)
Definition: nodeFuncs.c:689
#define IsA(nodeptr, _type_)
Definition: nodes.h:164
#define castNode(_type_, nodeptr)
Definition: nodes.h:182
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial(l)
Definition: pg_list.h:178
#define lsecond(l)
Definition: pg_list.h:183
static rewind_source * source
Definition: pg_rewind.c:89
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:212
List * args
Definition: primnodes.h:800
Definition: nodes.h:135

References FuncExpr::args, Assert(), castNode, DatumGetInt32(), exprTypmod(), IsA, linitial, list_length(), lsecond, relabel_to_typmod(), and source.

Referenced by time_support(), and timestamp_support().

◆ TimeZoneAbbrevIsKnown()

static bool TimeZoneAbbrevIsKnown ( const char *  abbr,
pg_tz tzp,
bool *  isfixed,
int *  offset,
int *  isdst 
)
static

Definition at line 1874 of file datetime.c.

1876{
1877 char upabbr[TZ_STRLEN_MAX + 1];
1878 unsigned char *p;
1879 long int gmtoff;
1880
1881 /* We need to force the abbrev to upper case */
1882 strlcpy(upabbr, abbr, sizeof(upabbr));
1883 for (p = (unsigned char *) upabbr; *p; p++)
1884 *p = pg_toupper(*p);
1885
1886 /* Look up the abbrev's meaning in this zone */
1887 if (pg_timezone_abbrev_is_known(upabbr,
1888 isfixed,
1889 &gmtoff,
1890 isdst,
1891 tzp))
1892 {
1893 /* Change sign to agree with DetermineTimeZoneOffset() */
1894 *offset = (int) -gmtoff;
1895 return true;
1896 }
1897 return false;
1898}
bool pg_timezone_abbrev_is_known(const char *abbrev, bool *isfixed, long int *gmtoff, int *isdst, const pg_tz *tz)
Definition: localtime.c:1862

References pg_timezone_abbrev_is_known(), pg_toupper(), strlcpy(), and TZ_STRLEN_MAX.

Referenced by DecodeTimezoneAbbrev(), and DecodeTimezoneAbbrevPrefix().

◆ ValidateDate()

int ValidateDate ( int  fmask,
bool  isjulian,
bool  is2digits,
bool  bc,
struct pg_tm tm 
)

Definition at line 2561 of file datetime.c.

2563{
2564 if (fmask & DTK_M(YEAR))
2565 {
2566 if (isjulian)
2567 {
2568 /* tm_year is correct and should not be touched */
2569 }
2570 else if (bc)
2571 {
2572 /* there is no year zero in AD/BC notation */
2573 if (tm->tm_year <= 0)
2574 return DTERR_FIELD_OVERFLOW;
2575 /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2576 tm->tm_year = -(tm->tm_year - 1);
2577 }
2578 else if (is2digits)
2579 {
2580 /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2581 if (tm->tm_year < 0) /* just paranoia */
2582 return DTERR_FIELD_OVERFLOW;
2583 if (tm->tm_year < 70)
2584 tm->tm_year += 2000;
2585 else if (tm->tm_year < 100)
2586 tm->tm_year += 1900;
2587 }
2588 else
2589 {
2590 /* there is no year zero in AD/BC notation */
2591 if (tm->tm_year <= 0)
2592 return DTERR_FIELD_OVERFLOW;
2593 }
2594 }
2595
2596 /* now that we have correct year, decode DOY */
2597 if (fmask & DTK_M(DOY))
2598 {
2599 j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2600 &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2601 }
2602
2603 /* check for valid month */
2604 if (fmask & DTK_M(MONTH))
2605 {
2606 if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2608 }
2609
2610 /* minimal check for valid day */
2611 if (fmask & DTK_M(DAY))
2612 {
2613 if (tm->tm_mday < 1 || tm->tm_mday > 31)
2615 }
2616
2617 if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2618 {
2619 /*
2620 * Check for valid day of month, now that we know for sure the month
2621 * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2622 * unlikely that "Feb 29" is a YMD-order error.
2623 */
2624 if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2625 return DTERR_FIELD_OVERFLOW;
2626 }
2627
2628 return 0;
2629}
const int day_tab[2][13]
Definition: datetime.c:75
#define isleap(y)
Definition: datetime.h:271

References date2j(), DAY, day_tab, DOY, DTERR_FIELD_OVERFLOW, DTERR_MD_FIELD_OVERFLOW, DTK_DATE_M, DTK_M, isleap, j2date(), MONTH, MONTHS_PER_YEAR, tm, pg_tm::tm_mday, pg_tm::tm_mon, pg_tm::tm_yday, pg_tm::tm_year, and YEAR.

Referenced by DecodeDateTime(), DecodeTimeOnly(), do_to_timestamp(), make_date(), and make_timestamp_internal().

Variable Documentation

◆ datecache

const datetkn* datecache[MAXDATEFIELDS] = {NULL}
static

Definition at line 258 of file datetime.c.

Referenced by DecodeSpecial().

◆ datetktbl

const datetkn datetktbl[]
static

Definition at line 105 of file datetime.c.

Referenced by CheckDateTokenTables(), DecodeSpecial(), and ParseDateTime().

◆ day_tab

const int day_tab[2][13]
Initial value:
=
{
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
}

Definition at line 75 of file datetime.c.

Referenced by PGTYPEStimestamp_add_interval(), timestamp_age(), timestamp_pl_interval(), timestamptz_age(), timestamptz_pl_interval_internal(), and ValidateDate().

◆ days

const char* const days[]
Initial value:
= {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", NULL}

Definition at line 84 of file datetime.c.

Referenced by AdjustDays(), brin_minmax_multi_distance_interval(), date_mii(), date_pli(), DCH_from_char(), DCH_to_char(), dttofmtasc_replace(), EncodeDateTime(), interval_cmp_value(), make_interval(), and PrintTiming().

◆ deltacache

const datetkn* deltacache[MAXDATEFIELDS] = {NULL}
static

Definition at line 260 of file datetime.c.

Referenced by DecodeUnits().

◆ deltatktbl

const datetkn deltatktbl[]
static

Definition at line 187 of file datetime.c.

Referenced by CheckDateTokenTables(), and DecodeUnits().

◆ months

const char* const months[]
Initial value:
= {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL}

Definition at line 81 of file datetime.c.

Referenced by DCH_from_char(), DCH_to_char(), dttofmtasc_replace(), EncodeDateTime(), make_interval(), PGTYPESdate_defmt_asc(), and PGTYPESdate_fmt_asc().

◆ szdatetktbl

const int szdatetktbl = sizeof datetktbl / sizeof datetktbl[0]
static

Definition at line 181 of file datetime.c.

Referenced by CheckDateTokenTables(), DecodeSpecial(), and ParseDateTime().

◆ szdeltatktbl

const int szdeltatktbl = sizeof deltatktbl / sizeof deltatktbl[0]
static

Definition at line 252 of file datetime.c.

Referenced by CheckDateTokenTables(), and DecodeUnits().

◆ tzabbrevcache

TzAbbrevCache tzabbrevcache[MAXDATEFIELDS]
static

◆ zoneabbrevtbl