PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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/tuplestore.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 charAppendSeconds (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 charAppendTimestampSeconds (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 charEncodeTimezone (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 charAddISO8601IntPart (char *cp, int64 value, char units)
 
static charAddPostgresIntPart (char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
 
static charAddVerboseIntPart (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
static int fb(int x)

Typedef Documentation

◆ TzAbbrevCache

Function Documentation

◆ AddISO8601IntPart()

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

Definition at line 4636 of file datetime.c.

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

References fb(), 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 4646 of file datetime.c.

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

References fb(), 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 4669 of file datetime.c.

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

References fb(), sprintf, and value.

Referenced by EncodeInterval().

◆ AdjustDays()

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

Definition at line 644 of file datetime.c.

645{
646 int days;
647
649 return false;
650 return !pg_mul_s32_overflow((int32) val, scale, &days) &&
651 !pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
652}
const char *const days[]
Definition datetime.c:85
int32_t int32
Definition c.h:614
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

References days, fb(), pg_add_s32_overflow(), pg_mul_s32_overflow(), scale, 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 580 of file datetime.c.

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

References AdjustFractMicroseconds(), fb(), pg_add_s32_overflow(), scale, 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 548 of file datetime.c.

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

References fb(), pg_add_s64_overflow(), and scale.

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 612 of file datetime.c.

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

References fb(), MONTHS_PER_YEAR, pg_add_s32_overflow(), and scale.

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 629 of file datetime.c.

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

References AdjustFractMicroseconds(), fb(), int64_multiply_add(), scale, and val.

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustMonths()

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

Definition at line 660 of file datetime.c.

661{
663 return false;
664 return !pg_add_s32_overflow(itm_in->tm_mon, (int32) val, &itm_in->tm_mon);
665}

References fb(), pg_add_s32_overflow(), 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 672 of file datetime.c.

674{
675 int years;
676
678 return false;
679 return !pg_mul_s32_overflow((int32) val, scale, &years) &&
680 !pg_add_s32_overflow(itm_in->tm_year, years, &itm_in->tm_year);
681}

References fb(), pg_add_s32_overflow(), pg_mul_s32_overflow(), scale, 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 459 of file datetime.c.

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

References Assert, fb(), 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 522 of file datetime.c.

523{
524 return AppendSeconds(cp, tm->tm_sec, fsec, MAX_TIMESTAMP_PRECISION, true);
525}
static char * AppendSeconds(char *cp, int sec, fsec_t fsec, int precision, bool fillzeros)
Definition datetime.c:459
#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(), fb(), 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 4902 of file datetime.c.

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

Referenced by CheckDateTokenTables(), and ConvertTimeZoneAbbrevs().

◆ CheckDateTokenTables()

bool CheckDateTokenTables ( void  )

Definition at line 4934 of file datetime.c.

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

References Assert, CheckDateTokenTable(), date2j(), datetktbl, deltatktbl, fb(), 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 3463 of file datetime.c.

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

References fb().

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ ClearTimeZoneAbbrevCache()

void ClearTimeZoneAbbrevCache ( void  )

Definition at line 3228 of file datetime.c.

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

References fb(), and tzabbrevcache.

Referenced by assign_timezone().

◆ ConvertTimeZoneAbbrevs()

TimeZoneAbbrevTable * ConvertTimeZoneAbbrevs ( struct tzEntry abbrevs,
int  n 
)

Definition at line 4996 of file datetime.c.

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

References Assert, CheckDateTokenTable(), DTZ, DYNTZ, fb(), guc_malloc(), i, LOG, MAXALIGN, strlcpy(), TOKMAXLEN, TZ, and DynamicZoneAbbrev::tz.

Referenced by load_tzoffsets().

◆ date2j()

◆ datebsearch()

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

Definition at line 4276 of file datetime.c.

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

References fb(), 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 4215 of file datetime.c.

4218{
4219 switch (dterr)
4220 {
4222 errsave(escontext,
4224 errmsg("date/time field value out of range: \"%s\"",
4225 str)));
4226 break;
4228 /* <nanny>same as above, but add hint about DateStyle</nanny> */
4229 errsave(escontext,
4231 errmsg("date/time field value out of range: \"%s\"",
4232 str),
4233 errhint("Perhaps you need a different \"DateStyle\" setting.")));
4234 break;
4236 errsave(escontext,
4238 errmsg("interval field value out of range: \"%s\"",
4239 str)));
4240 break;
4242 errsave(escontext,
4244 errmsg("time zone displacement out of range: \"%s\"",
4245 str)));
4246 break;
4247 case DTERR_BAD_TIMEZONE:
4248 errsave(escontext,
4250 errmsg("time zone \"%s\" not recognized",
4251 extra->dtee_timezone)));
4252 break;
4254 errsave(escontext,
4256 errmsg("time zone \"%s\" not recognized",
4257 extra->dtee_timezone),
4258 errdetail("This time zone name appears in the configuration file for time zone abbreviation \"%s\".",
4259 extra->dtee_abbrev)));
4260 break;
4261 case DTERR_BAD_FORMAT:
4262 default:
4263 errsave(escontext,
4265 errmsg("invalid input syntax for type %s: \"%s\"",
4266 datatype, str)));
4267 break;
4268 }
4269}
int errcode(int sqlerrcode)
Definition elog.c:874
#define errsave(context,...)
Definition elog.h:262
int errhint(const char *fmt,...) pg_attribute_printf(1
int errdetail(const char *fmt,...) pg_attribute_printf(1
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
static char * errmsg
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, fb(), 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 2452 of file datetime.c.

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

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

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

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

References AdjustDays(), AdjustFractDays(), AdjustFractMicroseconds(), AdjustFractYears(), AdjustMicroseconds(), AdjustMonths(), AdjustYears(), ClearPgItmIn(), DAYS_PER_MONTH, DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_DELTA, fb(), ISO8601IntegerWidth(), ParseISO8601Number(), pg_fallthrough, 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 2781 of file datetime.c.

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

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

References DTERR_BAD_FORMAT, DTK_DATE, DTK_DATE_M, DTK_TIME, DTK_TIME_M, fb(), 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 3247 of file datetime.c.

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

References datebsearch(), datecache, datetktbl, fb(), 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 2726 of file datetime.c.

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

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

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 2644 of file datetime.c.

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

References DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_TIME_M, fb(), INTERVAL_MASK, MINS_PER_HOUR, MINUTE, ParseFractionalSecond(), range(), SECOND, SECS_PER_MINUTE, str, strtoint(), 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 2755 of file datetime.c.

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

References DecodeTimeCommon(), DTERR_FIELD_OVERFLOW, fb(), int64_multiply_add(), range(), str, 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 1918 of file datetime.c.

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

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

References DTERR_BAD_FORMAT, DTERR_TZDISP_OVERFLOW, fb(), 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 3142 of file datetime.c.

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

References TimeZoneAbbrevTable::abbrevs, datebsearch(), DTERR_BAD_ZONE_ABBREV, DTZ, DYNTZ, fb(), FetchDynamicTimeZone(), TimeZoneAbbrevTable::numabbrevs, session_timezone, strlcpy(), TimeZoneAbbrevIsKnown(), TOKMAXLEN, datetkn::type, 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 3372 of file datetime.c.

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

References TimeZoneAbbrevTable::abbrevs, datebsearch(), DYNTZ, fb(), 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 3289 of file datetime.c.

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

References DateTimeParseError(), DecodeTimezoneAbbrev(), downcase_truncate_identifier(), DTZ, DYNTZ, ereport, errcode(), errmsg, ERROR, fb(), 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 3344 of file datetime.c.

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

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

Referenced by lookup_timezone().

◆ DecodeUnits()

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

Definition at line 4170 of file datetime.c.

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

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

Referenced by DecodeInterval(), 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 1766 of file datetime.c.

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

References DetermineTimeZoneAbbrevOffsetInternal(), DetermineTimeZoneOffsetInternal(), fb(), 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 1841 of file datetime.c.

1843{
1844 char upabbr[TZ_STRLEN_MAX + 1];
1845 unsigned char *p;
1846 long int gmtoff;
1847
1848 /* We need to force the abbrev to upper case */
1849 strlcpy(upabbr, abbr, sizeof(upabbr));
1850 for (p = (unsigned char *) upabbr; *p; p++)
1851 *p = pg_toupper(*p);
1852
1853 /* Look up the abbrev's meaning at this time in this zone */
1855 &t,
1856 &gmtoff,
1857 isdst,
1858 tzp))
1859 {
1860 /* Change sign to agree with DetermineTimeZoneOffset() */
1861 *offset = (int) -gmtoff;
1862 return true;
1863 }
1864 return false;
1865}
#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)

References fb(), 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 1804 of file datetime.c.

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

References DetermineTimeZoneAbbrevOffsetInternal(), DetermineTimeZoneOffset(), ereport, errcode(), errmsg, ERROR, fb(), 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 1627 of file datetime.c.

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

4351{
4352 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4353
4354 switch (style)
4355 {
4356 case USE_ISO_DATES:
4357 case USE_XSD_DATES:
4358 /* compatible with ISO date formats */
4360 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4361 *str++ = '-';
4363 *str++ = '-';
4365 break;
4366
4367 case USE_SQL_DATES:
4368 /* compatible with Oracle/Ingres date formats */
4369 if (DateOrder == DATEORDER_DMY)
4370 {
4372 *str++ = '/';
4374 }
4375 else
4376 {
4378 *str++ = '/';
4380 }
4381 *str++ = '/';
4383 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4384 break;
4385
4386 case USE_GERMAN_DATES:
4387 /* German-style date format */
4389 *str++ = '.';
4391 *str++ = '.';
4393 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4394 break;
4395
4396 case USE_POSTGRES_DATES:
4397 default:
4398 /* traditional date-only style for Postgres */
4399 if (DateOrder == DATEORDER_DMY)
4400 {
4402 *str++ = '-';
4404 }
4405 else
4406 {
4408 *str++ = '-';
4410 }
4411 *str++ = '-';
4413 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4414 break;
4415 }
4416
4417 if (tm->tm_year <= 0)
4418 {
4419 memcpy(str, " BC", 3); /* Don't copy NUL */
4420 str += 3;
4421 }
4422 *str = '\0';
4423}
#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, fb(), 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 4465 of file datetime.c.

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

References AppendTimestampSeconds(), Assert, date2j(), DateOrder, DATEORDER_DMY, days, EncodeTimezone(), fb(), 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 4708 of file datetime.c.

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

References AddISO8601IntPart(), AddPostgresIntPart(), AddVerboseIntPart(), AppendSeconds(), fb(), INTSTYLE_ISO_8601, INTSTYLE_POSTGRES, INTSTYLE_POSTGRES_VERBOSE, INTSTYLE_SQL_STANDARD, MAX_INTERVAL_PRECISION, sprintf, and str.

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 4435 of file datetime.c.

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

References AppendSeconds(), EncodeTimezone(), fb(), 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 4312 of file datetime.c.

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

References fb(), 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 5093 of file datetime.c.

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

References Assert, DateTimeErrorExtra::dtee_abbrev, DateTimeErrorExtra::dtee_timezone, DYNTZ, fb(), pg_tzset(), datetkn::token, datetkn::type, and datetkn::value.

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

◆ GetCurrentDateTime()

void GetCurrentDateTime ( struct pg_tm tm)

Definition at line 377 of file datetime.c.

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

References fb(), 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 398 of file datetime.c.

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

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

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

◆ InstallTimeZoneAbbrevs()

void InstallTimeZoneAbbrevs ( TimeZoneAbbrevTable tbl)

Definition at line 5080 of file datetime.c.

5081{
5083 /* reset tzabbrevcache, which may contain results from old table */
5084 memset(tzabbrevcache, 0, sizeof(tzabbrevcache));
5085}

References fb(), 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 533 of file datetime.c.

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

References fb(), 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 3925 of file datetime.c.

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

References fb().

Referenced by DecodeISO8601Interval().

◆ j2date()

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

Definition at line 322 of file datetime.c.

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

References fb(), 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(), timestamp2tm(), timestamp_pl_interval(), timestamptz_pl_interval_internal(), and ValidateDate().

◆ j2day()

int j2day ( int  date)

Definition at line 355 of file datetime.c.

356{
357 date += 1;
358 date %= 7;
359 /* Cope if division truncates towards zero, as it probably does */
360 if (date < 0)
361 date += 7;
362
363 return date;
364} /* 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 774 of file datetime.c.

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

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

References Assert, DTERR_BAD_FORMAT, and fb().

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

◆ ParseFractionalSecond()

static int ParseFractionalSecond ( char cp,
fsec_t fsec 
)
static

Definition at line 729 of file datetime.c.

730{
731 double frac;
732 int dterr;
733
735 if (dterr)
736 return dterr;
737 *fsec = rint(frac * 1000000);
738 return 0;
739}

References fb(), and ParseFraction().

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

◆ ParseISO8601Number()

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

Definition at line 3883 of file datetime.c.

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

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

Referenced by DecodeISO8601Interval().

◆ pg_timezone_abbrevs_abbrevs()

Datum pg_timezone_abbrevs_abbrevs ( PG_FUNCTION_ARGS  )

Definition at line 5212 of file datetime.c.

5213{
5215 int *pindex;
5216 Datum result;
5217 HeapTuple tuple;
5218 Datum values[3];
5219 bool nulls[3] = {0};
5220 const datetkn *tp;
5221 char buffer[TOKMAXLEN + 1];
5222 int gmtoffset;
5223 bool is_dst;
5224 unsigned char *p;
5225 struct pg_itm_in itm_in;
5227
5228 /* stuff done only on the first call of the function */
5229 if (SRF_IS_FIRSTCALL())
5230 {
5231 TupleDesc tupdesc;
5232 MemoryContext oldcontext;
5233
5234 /* create a function context for cross-call persistence */
5236
5237 /*
5238 * switch to memory context appropriate for multiple function calls
5239 */
5240 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5241
5242 /* allocate memory for user context */
5243 pindex = palloc_object(int);
5244 *pindex = 0;
5245 funcctx->user_fctx = pindex;
5246
5247 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
5248 elog(ERROR, "return type must be a row type");
5249 funcctx->tuple_desc = tupdesc;
5250
5251 MemoryContextSwitchTo(oldcontext);
5252 }
5253
5254 /* stuff done on every call of the function */
5256 pindex = (int *) funcctx->user_fctx;
5257
5258 if (zoneabbrevtbl == NULL ||
5261
5262 tp = zoneabbrevtbl->abbrevs + *pindex;
5263
5264 switch (tp->type)
5265 {
5266 case TZ:
5267 gmtoffset = tp->value;
5268 is_dst = false;
5269 break;
5270 case DTZ:
5271 gmtoffset = tp->value;
5272 is_dst = true;
5273 break;
5274 case DYNTZ:
5275 {
5276 /* Determine the current meaning of the abbrev */
5277 pg_tz *tzp;
5278 DateTimeErrorExtra extra;
5280 int isdst;
5281
5282 tzp = FetchDynamicTimeZone(zoneabbrevtbl, tp, &extra);
5283 if (tzp == NULL)
5285 NULL, NULL, NULL);
5288 tp->token,
5289 tzp,
5290 &isdst);
5291 is_dst = (bool) isdst;
5292 break;
5293 }
5294 default:
5295 elog(ERROR, "unrecognized timezone type %d", (int) tp->type);
5296 gmtoffset = 0; /* keep compiler quiet */
5297 is_dst = false;
5298 break;
5299 }
5300
5301 /*
5302 * Convert name to text, using upcasing conversion that is the inverse of
5303 * what ParseDateTime() uses.
5304 */
5305 strlcpy(buffer, tp->token, sizeof(buffer));
5306 for (p = (unsigned char *) buffer; *p; p++)
5307 *p = pg_toupper(*p);
5308
5309 values[0] = CStringGetTextDatum(buffer);
5310
5311 /* Convert offset (in seconds) to an interval; can't overflow */
5312 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5313 itm_in.tm_usec = (int64) gmtoffset * USECS_PER_SEC;
5317
5318 values[2] = BoolGetDatum(is_dst);
5319
5320 (*pindex)++;
5321
5322 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5323 result = HeapTupleGetDatum(tuple);
5324
5325 SRF_RETURN_NEXT(funcctx, result);
5326}
int DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr, pg_tz *tzp, int *isdst)
Definition datetime.c:1804
int itmin2interval(struct pg_itm_in *itm_in, Interval *span)
Definition timestamp.c:2109
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1603
static Datum values[MAXATTR]
Definition bootstrap.c:188
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define MemSet(start, val, len)
Definition c.h:1109
#define palloc_object(type)
Definition fe_memutils.h:74
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:1037
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
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, fb(), FetchDynamicTimeZone(), get_call_result_type(), GetCurrentTransactionStartTimestamp(), heap_form_tuple(), HeapTupleGetDatum(), IntervalPGetDatum(), itmin2interval(), MemoryContextSwitchTo(), MemSet, now(), TimeZoneAbbrevTable::numabbrevs, palloc_object, pg_toupper(), SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, strlcpy(), datetkn::token, TOKMAXLEN, datetkn::type, TYPEFUNC_COMPOSITE, TZ, USECS_PER_SEC, datetkn::value, values, and zoneabbrevtbl.

◆ pg_timezone_abbrevs_zone()

Datum pg_timezone_abbrevs_zone ( PG_FUNCTION_ARGS  )

Definition at line 5125 of file datetime.c.

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

References tzEntry::abbrev, BoolGetDatum(), CStringGetTextDatum, elog, ERROR, fb(), get_call_result_type(), GetCurrentTransactionStartTimestamp(), heap_form_tuple(), HeapTupleGetDatum(), IntervalPGetDatum(), itmin2interval(), MemoryContextSwitchTo(), MemSet, now(), palloc_object, 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(), TYPEFUNC_COMPOSITE, USECS_PER_SEC, and values.

◆ pg_timezone_names()

Datum pg_timezone_names ( PG_FUNCTION_ARGS  )

Definition at line 5333 of file datetime.c.

5334{
5335 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
5337 pg_tz *tz;
5338 Datum values[4];
5339 bool nulls[4] = {0};
5340 int tzoff;
5341 struct pg_tm tm;
5342 fsec_t fsec;
5343 const char *tzn;
5345 struct pg_itm_in itm_in;
5346
5347 InitMaterializedSRF(fcinfo, 0);
5348
5349 /* initialize timezone scanning code */
5351
5352 /* search for another zone to display */
5353 for (;;)
5354 {
5356 if (!tz)
5357 break;
5358
5359 /* Convert now() to local time in this zone */
5361 &tzoff, &tm, &fsec, &tzn, tz) != 0)
5362 continue; /* ignore if conversion fails */
5363
5364 /*
5365 * IANA's rather silly "Factory" time zone used to emit ridiculously
5366 * long "abbreviations" such as "Local time zone must be set--see zic
5367 * manual page" or "Local time zone must be set--use tzsetup". While
5368 * modern versions of tzdb emit the much saner "-00", it seems some
5369 * benighted packagers are hacking the IANA data so that it continues
5370 * to produce these strings. To prevent producing a weirdly wide
5371 * abbrev column, reject ridiculously long abbreviations.
5372 */
5373 if (tzn && strlen(tzn) > 31)
5374 continue;
5375
5377 values[1] = CStringGetTextDatum(tzn ? tzn : "");
5378
5379 /* Convert tzoff to an interval; can't overflow */
5380 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5381 itm_in.tm_usec = (int64) -tzoff * USECS_PER_SEC;
5385
5386 values[3] = BoolGetDatum(tm.tm_isdst > 0);
5387
5388 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
5389 }
5390
5392 return (Datum) 0;
5393}
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:785

References BoolGetDatum(), CStringGetTextDatum, fb(), GetCurrentTransactionStartTimestamp(), InitMaterializedSRF(), IntervalPGetDatum(), itmin2interval(), MemSet, palloc_object, pg_get_timezone_name(), pg_tzenumerate_end(), pg_tzenumerate_next(), pg_tzenumerate_start(), timestamp2tm(), tm, pg_tm::tm_isdst, tuplestore_putvalues(), USECS_PER_SEC, and values.

◆ TemporalSimplify()

Node * TemporalSimplify ( int32  max_precis,
Node node 
)

Definition at line 4963 of file datetime.c.

4964{
4965 FuncExpr *expr = castNode(FuncExpr, node);
4966 Node *ret = NULL;
4967 Node *typmod;
4968
4969 Assert(list_length(expr->args) >= 2);
4970
4971 typmod = (Node *) lsecond(expr->args);
4972
4973 if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
4974 {
4975 Node *source = (Node *) linitial(expr->args);
4978
4979 if (new_precis < 0 || new_precis == max_precis ||
4980 (old_precis >= 0 && new_precis >= old_precis))
4982 }
4983
4984 return ret;
4985}
int32 exprTypmod(const Node *expr)
Definition nodeFuncs.c:304
Node * relabel_to_typmod(Node *expr, int32 typmod)
Definition nodeFuncs.c:694
#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:202
List * args
Definition primnodes.h:801
Definition nodes.h:135

References FuncExpr::args, Assert, castNode, DatumGetInt32(), exprTypmod(), fb(), 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 1875 of file datetime.c.

1877{
1878 char upabbr[TZ_STRLEN_MAX + 1];
1879 unsigned char *p;
1880 long int gmtoff;
1881
1882 /* We need to force the abbrev to upper case */
1883 strlcpy(upabbr, abbr, sizeof(upabbr));
1884 for (p = (unsigned char *) upabbr; *p; p++)
1885 *p = pg_toupper(*p);
1886
1887 /* Look up the abbrev's meaning in this zone */
1889 isfixed,
1890 &gmtoff,
1891 isdst,
1892 tzp))
1893 {
1894 /* Change sign to agree with DetermineTimeZoneOffset() */
1895 *offset = (int) -gmtoff;
1896 return true;
1897 }
1898 return false;
1899}
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 fb(), 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 2562 of file datetime.c.

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

259{NULL};

Referenced by DecodeSpecial().

◆ datetktbl

const datetkn datetktbl[]
static

Definition at line 106 of file datetime.c.

106 {
107 /* token, type, value */
108 {"+infinity", RESERV, DTK_LATE}, /* same as "infinity" */
109 {EARLY, RESERV, DTK_EARLY}, /* "-infinity" reserved for "early time" */
110 {DA_D, ADBC, AD}, /* "ad" for years > 0 */
111 {"allballs", RESERV, DTK_ZULU}, /* 00:00:00 */
112 {"am", AMPM, AM},
113 {"apr", MONTH, 4},
114 {"april", MONTH, 4},
115 {"at", IGNORE_DTF, 0}, /* "at" (throwaway) */
116 {"aug", MONTH, 8},
117 {"august", MONTH, 8},
118 {DB_C, ADBC, BC}, /* "bc" for years <= 0 */
119 {"d", UNITS, DTK_DAY}, /* "day of month" for ISO input */
120 {"dec", MONTH, 12},
121 {"december", MONTH, 12},
122 {"dow", UNITS, DTK_DOW}, /* day of week */
123 {"doy", UNITS, DTK_DOY}, /* day of year */
124 {"dst", DTZMOD, SECS_PER_HOUR},
125 {EPOCH, RESERV, DTK_EPOCH}, /* "epoch" reserved for system epoch time */
126 {"feb", MONTH, 2},
127 {"february", MONTH, 2},
128 {"fri", DOW, 5},
129 {"friday", DOW, 5},
130 {"h", UNITS, DTK_HOUR}, /* "hour" */
131 {LATE, RESERV, DTK_LATE}, /* "infinity" reserved for "late time" */
132 {"isodow", UNITS, DTK_ISODOW}, /* ISO day of week, Sunday == 7 */
133 {"isoyear", UNITS, DTK_ISOYEAR}, /* year in terms of the ISO week date */
134 {"j", UNITS, DTK_JULIAN},
135 {"jan", MONTH, 1},
136 {"january", MONTH, 1},
137 {"jd", UNITS, DTK_JULIAN},
138 {"jul", MONTH, 7},
139 {"julian", UNITS, DTK_JULIAN},
140 {"july", MONTH, 7},
141 {"jun", MONTH, 6},
142 {"june", MONTH, 6},
143 {"m", UNITS, DTK_MONTH}, /* "month" for ISO input */
144 {"mar", MONTH, 3},
145 {"march", MONTH, 3},
146 {"may", MONTH, 5},
147 {"mm", UNITS, DTK_MINUTE}, /* "minute" for ISO input */
148 {"mon", DOW, 1},
149 {"monday", DOW, 1},
150 {"nov", MONTH, 11},
151 {"november", MONTH, 11},
152 {NOW, RESERV, DTK_NOW}, /* current transaction time */
153 {"oct", MONTH, 10},
154 {"october", MONTH, 10},
155 {"on", IGNORE_DTF, 0}, /* "on" (throwaway) */
156 {"pm", AMPM, PM},
157 {"s", UNITS, DTK_SECOND}, /* "seconds" for ISO input */
158 {"sat", DOW, 6},
159 {"saturday", DOW, 6},
160 {"sep", MONTH, 9},
161 {"sept", MONTH, 9},
162 {"september", MONTH, 9},
163 {"sun", DOW, 0},
164 {"sunday", DOW, 0},
165 {"t", ISOTIME, DTK_TIME}, /* Filler for ISO time fields */
166 {"thu", DOW, 4},
167 {"thur", DOW, 4},
168 {"thurs", DOW, 4},
169 {"thursday", DOW, 4},
170 {TODAY, RESERV, DTK_TODAY}, /* midnight */
171 {TOMORROW, RESERV, DTK_TOMORROW}, /* tomorrow midnight */
172 {"tue", DOW, 2},
173 {"tues", DOW, 2},
174 {"tuesday", DOW, 2},
175 {"wed", DOW, 3},
176 {"wednesday", DOW, 3},
177 {"weds", DOW, 3},
178 {"y", UNITS, DTK_YEAR}, /* "year" for ISO input */
179 {YESTERDAY, RESERV, DTK_YESTERDAY} /* yesterday midnight */
180};
#define SECS_PER_HOUR
Definition timestamp.h:127
#define EPOCH
Definition datetime.h:37
#define DTK_ISODOW
Definition datetime.h:180
#define DB_C
Definition datetime.h:61
#define DTK_ISOYEAR
Definition datetime.h:179
#define DTK_DOY
Definition datetime.h:176
#define AD
Definition datetime.h:75
#define TOMORROW
Definition datetime.h:43
#define EARLY
Definition datetime.h:39
#define DA_D
Definition datetime.h:60
#define LATE
Definition datetime.h:40
#define NOW
Definition datetime.h:41
#define DTK_DOW
Definition datetime.h:175
#define TODAY
Definition datetime.h:42
#define YESTERDAY
Definition datetime.h:44

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 76 of file datetime.c.

77{
78 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0},
79 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0}
80};

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 85 of file datetime.c.

85 {"Sunday", "Monday", "Tuesday", "Wednesday",
86"Thursday", "Friday", "Saturday", NULL};

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

◆ deltacache

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

Definition at line 261 of file datetime.c.

261{NULL};

Referenced by DecodeUnits().

◆ deltatktbl

const datetkn deltatktbl[]
static

Definition at line 188 of file datetime.c.

188 {
189 /* token, type, value */
190 {"@", IGNORE_DTF, 0}, /* postgres relative prefix */
191 {DAGO, AGO, 0}, /* "ago" indicates negative time offset */
192 {"c", UNITS, DTK_CENTURY}, /* "century" relative */
193 {"cent", UNITS, DTK_CENTURY}, /* "century" relative */
194 {"centuries", UNITS, DTK_CENTURY}, /* "centuries" relative */
195 {DCENTURY, UNITS, DTK_CENTURY}, /* "century" relative */
196 {"d", UNITS, DTK_DAY}, /* "day" relative */
197 {DDAY, UNITS, DTK_DAY}, /* "day" relative */
198 {"days", UNITS, DTK_DAY}, /* "days" relative */
199 {"dec", UNITS, DTK_DECADE}, /* "decade" relative */
200 {DDECADE, UNITS, DTK_DECADE}, /* "decade" relative */
201 {"decades", UNITS, DTK_DECADE}, /* "decades" relative */
202 {"decs", UNITS, DTK_DECADE}, /* "decades" relative */
203 {"h", UNITS, DTK_HOUR}, /* "hour" relative */
204 {DHOUR, UNITS, DTK_HOUR}, /* "hour" relative */
205 {"hours", UNITS, DTK_HOUR}, /* "hours" relative */
206 {"hr", UNITS, DTK_HOUR}, /* "hour" relative */
207 {"hrs", UNITS, DTK_HOUR}, /* "hours" relative */
208 {"m", UNITS, DTK_MINUTE}, /* "minute" relative */
209 {"microsecon", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
210 {"mil", UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
211 {"millennia", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
212 {DMILLENNIUM, UNITS, DTK_MILLENNIUM}, /* "millennium" relative */
213 {"millisecon", UNITS, DTK_MILLISEC}, /* relative */
214 {"mils", UNITS, DTK_MILLENNIUM}, /* "millennia" relative */
215 {"min", UNITS, DTK_MINUTE}, /* "minute" relative */
216 {"mins", UNITS, DTK_MINUTE}, /* "minutes" relative */
217 {DMINUTE, UNITS, DTK_MINUTE}, /* "minute" relative */
218 {"minutes", UNITS, DTK_MINUTE}, /* "minutes" relative */
219 {"mon", UNITS, DTK_MONTH}, /* "months" relative */
220 {"mons", UNITS, DTK_MONTH}, /* "months" relative */
221 {DMONTH, UNITS, DTK_MONTH}, /* "month" relative */
222 {"months", UNITS, DTK_MONTH},
223 {"ms", UNITS, DTK_MILLISEC},
224 {"msec", UNITS, DTK_MILLISEC},
226 {"mseconds", UNITS, DTK_MILLISEC},
227 {"msecs", UNITS, DTK_MILLISEC},
228 {"qtr", UNITS, DTK_QUARTER}, /* "quarter" relative */
229 {DQUARTER, UNITS, DTK_QUARTER}, /* "quarter" relative */
230 {"s", UNITS, DTK_SECOND},
231 {"sec", UNITS, DTK_SECOND},
233 {"seconds", UNITS, DTK_SECOND},
234 {"secs", UNITS, DTK_SECOND},
235 {DTIMEZONE, UNITS, DTK_TZ}, /* "timezone" time offset */
236 {"timezone_h", UNITS, DTK_TZ_HOUR}, /* timezone hour units */
237 {"timezone_m", UNITS, DTK_TZ_MINUTE}, /* timezone minutes units */
238 {"us", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
239 {"usec", UNITS, DTK_MICROSEC}, /* "microsecond" relative */
240 {DMICROSEC, UNITS, DTK_MICROSEC}, /* "microsecond" relative */
241 {"useconds", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
242 {"usecs", UNITS, DTK_MICROSEC}, /* "microseconds" relative */
243 {"w", UNITS, DTK_WEEK}, /* "week" relative */
244 {DWEEK, UNITS, DTK_WEEK}, /* "week" relative */
245 {"weeks", UNITS, DTK_WEEK}, /* "weeks" relative */
246 {"y", UNITS, DTK_YEAR}, /* "year" relative */
247 {DYEAR, UNITS, DTK_YEAR}, /* "year" relative */
248 {"years", UNITS, DTK_YEAR}, /* "years" relative */
249 {"yr", UNITS, DTK_YEAR}, /* "year" relative */
250 {"yrs", UNITS, DTK_YEAR} /* "years" relative */
251};
#define DAGO
Definition datetime.h:35
#define DYEAR
Definition datetime.h:56
#define DTK_QUARTER
Definition datetime.h:166
#define DHOUR
Definition datetime.h:51
#define DWEEK
Definition datetime.h:53
#define DTK_TZ_HOUR
Definition datetime.h:177
#define DTIMEZONE
Definition datetime.h:62
#define DTK_TZ_MINUTE
Definition datetime.h:178
#define DMONTH
Definition datetime.h:54
#define DDECADE
Definition datetime.h:57
#define DDAY
Definition datetime.h:52
#define DMICROSEC
Definition datetime.h:47
#define DMILLENNIUM
Definition datetime.h:59
#define DCENTURY
Definition datetime.h:58
#define DQUARTER
Definition datetime.h:55
#define DSECOND
Definition datetime.h:49
#define DMILLISEC
Definition datetime.h:48
#define DMINUTE
Definition datetime.h:50

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 82 of file datetime.c.

82 {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
83"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", NULL};

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 182 of file datetime.c.

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

◆ szdeltatktbl

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

Definition at line 253 of file datetime.c.

Referenced by CheckDateTokenTables(), and DecodeUnits().

◆ tzabbrevcache

TzAbbrevCache tzabbrevcache[MAXDATEFIELDS]
static

◆ zoneabbrevtbl