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:284
static int fb(int x)

Typedef Documentation

◆ TzAbbrevCache

Function Documentation

◆ AddISO8601IntPart()

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

Definition at line 4667 of file datetime.c.

4668{
4669 if (value == 0)
4670 return cp;
4671 sprintf(cp, "%" PRId64 "%c", value, units);
4672 return cp + strlen(cp);
4673}
static struct @177 value
#define sprintf
Definition port.h:263

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

4679{
4680 if (value == 0)
4681 return cp;
4682 sprintf(cp, "%s%s%" PRId64 " %s%s",
4683 (!*is_zero) ? " " : "",
4684 (*is_before && value > 0) ? "+" : "",
4685 value,
4686 units,
4687 (value != 1) ? "s" : "");
4688
4689 /*
4690 * Each nonzero field sets is_before for (only) the next one. This is a
4691 * tad bizarre but it's how it worked before...
4692 */
4693 *is_before = (value < 0);
4694 *is_zero = false;
4695 return cp + strlen(cp);
4696}

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

4702{
4703 if (value == 0)
4704 return cp;
4705 /* first nonzero value sets is_before */
4706 if (*is_zero)
4707 {
4708 *is_before = (value < 0);
4709 value = i64abs(value);
4710 }
4711 else if (*is_before)
4712 value = -value;
4713 sprintf(cp, " %" PRId64 " %s%s", value, units, (value == 1) ? "" : "s");
4714 *is_zero = false;
4715 return cp + strlen(cp);
4716}

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:620
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:621
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:943
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 4934 of file datetime.c.

4935{
4936 bool ok = true;
4937 int i;
4938
4939 for (i = 0; i < nel; i++)
4940 {
4941 /* check for token strings that don't fit */
4942 if (strlen(base[i].token) > TOKMAXLEN)
4943 {
4944 /* %.*s is safe since all our tokens are ASCII */
4945 elog(LOG, "token too long in %s table: \"%.*s\"",
4946 tablename,
4947 TOKMAXLEN + 1, base[i].token);
4948 ok = false;
4949 break; /* don't risk applying strcmp */
4950 }
4951 /* check for out of order */
4952 if (i > 0 &&
4953 strcmp(base[i - 1].token, base[i].token) >= 0)
4954 {
4955 elog(LOG, "ordering error in %s table: \"%s\" >= \"%s\"",
4956 tablename,
4957 base[i - 1].token,
4958 base[i].token);
4959 ok = false;
4960 }
4961 }
4962 return ok;
4963}
#define LOG
Definition elog.h:32
#define elog(elevel,...)
Definition elog.h:228
#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 4966 of file datetime.c.

4967{
4968 bool ok = true;
4969
4970 Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4971 Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4972
4973 ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4974 ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4975 return ok;
4976}
static bool CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
Definition datetime.c:4934
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 3486 of file datetime.c.

3487{
3488 itm_in->tm_usec = 0;
3489 itm_in->tm_mday = 0;
3490 itm_in->tm_mon = 0;
3491 itm_in->tm_year = 0;
3492}

References fb().

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ ClearTimeZoneAbbrevCache()

void ClearTimeZoneAbbrevCache ( void  )

Definition at line 3246 of file datetime.c.

3247{
3248 memset(tzabbrevcache, 0, sizeof(tzabbrevcache));
3249}
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 5028 of file datetime.c.

5029{
5031 Size tbl_size;
5032 int i;
5033
5034 /* Space for fixed fields and datetkn array */
5036 n * sizeof(datetkn);
5038 /* Count up space for dynamic abbreviations */
5039 for (i = 0; i < n; i++)
5040 {
5041 struct tzEntry *abbr = abbrevs + i;
5042
5043 if (abbr->zone != NULL)
5044 {
5045 Size dsize;
5046
5047 dsize = offsetof(DynamicZoneAbbrev, zone) +
5048 strlen(abbr->zone) + 1;
5049 tbl_size += MAXALIGN(dsize);
5050 }
5051 }
5052
5053 /* Alloc the result ... */
5055 if (!tbl)
5056 return NULL;
5057
5058 /* ... and fill it in */
5059 tbl->tblsize = tbl_size;
5060 tbl->numabbrevs = n;
5061 /* in this loop, tbl_size reprises the space calculation above */
5063 n * sizeof(datetkn);
5065 for (i = 0; i < n; i++)
5066 {
5067 struct tzEntry *abbr = abbrevs + i;
5068 datetkn *dtoken = tbl->abbrevs + i;
5069
5070 /* use strlcpy to truncate name if necessary */
5071 strlcpy(dtoken->token, abbr->abbrev, TOKMAXLEN + 1);
5072 if (abbr->zone != NULL)
5073 {
5074 /* Allocate a DynamicZoneAbbrev for this abbreviation */
5076 Size dsize;
5077
5078 dtza = (DynamicZoneAbbrev *) ((char *) tbl + tbl_size);
5079 dtza->tz = NULL;
5080 strcpy(dtza->zone, abbr->zone);
5081
5082 dtoken->type = DYNTZ;
5083 /* value is offset from table start to DynamicZoneAbbrev */
5084 dtoken->value = (int32) tbl_size;
5085
5086 dsize = offsetof(DynamicZoneAbbrev, zone) +
5087 strlen(abbr->zone) + 1;
5088 tbl_size += MAXALIGN(dsize);
5089 }
5090 else
5091 {
5092 dtoken->type = abbr->is_dst ? DTZ : TZ;
5093 dtoken->value = abbr->offset;
5094 }
5095 }
5096
5097 /* Assert the two loops above agreed on size calculations */
5098 Assert(tbl->tblsize == tbl_size);
5099
5100 /* Check the ordering, if testing */
5101 Assert(CheckDateTokenTable("timezone abbreviations", tbl->abbrevs, n));
5102
5103 return tbl;
5104}
#define MAXALIGN(LEN)
Definition c.h:896
size_t Size
Definition c.h:689
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:101

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

4304{
4305 if (nel > 0)
4306 {
4307 const datetkn *last = base + nel - 1,
4308 *position;
4309 int result;
4310
4311 while (last >= base)
4312 {
4313 position = base + ((last - base) >> 1);
4314 /* precheck the first character for a bit of extra speed */
4315 result = (int) key[0] - (int) position->token[0];
4316 if (result == 0)
4317 {
4318 /* use strncmp so that we match truncated tokens */
4319 result = strncmp(key, position->token, TOKMAXLEN);
4320 if (result == 0)
4321 return position;
4322 }
4323 if (result < 0)
4324 last = position - 1;
4325 else
4326 base = position + 1;
4327 }
4328 }
4329 return NULL;
4330}
uint32 result

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

4244{
4245 switch (dterr)
4246 {
4248 errsave(escontext,
4250 errmsg("date/time field value out of range: \"%s\"",
4251 str)));
4252 break;
4254 /* <nanny>same as above, but add hint about DateStyle</nanny> */
4255 errsave(escontext,
4257 errmsg("date/time field value out of range: \"%s\"",
4258 str),
4259 errhint("Perhaps you need a different \"DateStyle\" setting.")));
4260 break;
4262 errsave(escontext,
4264 errmsg("interval field value out of range: \"%s\"",
4265 str)));
4266 break;
4268 errsave(escontext,
4270 errmsg("time zone displacement out of range: \"%s\"",
4271 str)));
4272 break;
4273 case DTERR_BAD_TIMEZONE:
4274 errsave(escontext,
4276 errmsg("time zone \"%s\" not recognized",
4277 extra->dtee_timezone)));
4278 break;
4280 errsave(escontext,
4282 errmsg("time zone \"%s\" not recognized",
4283 extra->dtee_timezone),
4284 errdetail("This time zone name appears in the configuration file for time zone abbreviation \"%s\".",
4285 extra->dtee_abbrev)));
4286 break;
4287 case DTERR_BAD_FORMAT:
4288 default:
4289 errsave(escontext,
4291 errmsg("invalid input syntax for type %s: \"%s\"",
4292 datatype, str)));
4293 break;
4294 }
4295}
int errcode(int sqlerrcode)
Definition elog.c:875
#define errsave(context,...)
Definition elog.h:264
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:290
#define DTERR_INTERVAL_OVERFLOW
Definition datetime.h:287
#define DTERR_BAD_TIMEZONE
Definition datetime.h:289
#define DTERR_TZDISP_OVERFLOW
Definition datetime.h:288
#define DTERR_FIELD_OVERFLOW
Definition datetime.h:285
#define DTERR_MD_FIELD_OVERFLOW
Definition datetime.h:286
static char * errmsg
const char * dtee_timezone
Definition datetime.h:295
const char * dtee_abbrev
Definition datetime.h:297

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

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

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

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

3979{
3980 bool datepart = true;
3981 bool havefield = false;
3982
3983 *dtype = DTK_DELTA;
3985
3986 if (strlen(str) < 2 || str[0] != 'P')
3987 return DTERR_BAD_FORMAT;
3988
3989 str++;
3990 while (*str)
3991 {
3992 char *fieldstart;
3993 int64 val;
3994 double fval;
3995 char unit;
3996 int dterr;
3997
3998 if (*str == 'T') /* T indicates the beginning of the time part */
3999 {
4000 datepart = false;
4001 havefield = false;
4002 str++;
4003 continue;
4004 }
4005
4006 fieldstart = str;
4007 dterr = ParseISO8601Number(str, &str, &val, &fval);
4008 if (dterr)
4009 return dterr;
4010
4011 /*
4012 * Note: we could step off the end of the string here. Code below
4013 * *must* exit the loop if unit == '\0'.
4014 */
4015 unit = *str++;
4016
4017 if (datepart)
4018 {
4019 switch (unit) /* before T: Y M W D */
4020 {
4021 case 'Y':
4022 if (!AdjustYears(val, 1, itm_in) ||
4023 !AdjustFractYears(fval, 1, itm_in))
4024 return DTERR_FIELD_OVERFLOW;
4025 break;
4026 case 'M':
4027 if (!AdjustMonths(val, itm_in) ||
4029 return DTERR_FIELD_OVERFLOW;
4030 break;
4031 case 'W':
4032 if (!AdjustDays(val, 7, itm_in) ||
4033 !AdjustFractDays(fval, 7, itm_in))
4034 return DTERR_FIELD_OVERFLOW;
4035 break;
4036 case 'D':
4037 if (!AdjustDays(val, 1, itm_in) ||
4039 return DTERR_FIELD_OVERFLOW;
4040 break;
4041 case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
4042 case '\0':
4044 {
4045 if (!AdjustYears(val / 10000, 1, itm_in) ||
4046 !AdjustMonths((val / 100) % 100, itm_in) ||
4047 !AdjustDays(val % 100, 1, itm_in) ||
4049 return DTERR_FIELD_OVERFLOW;
4050 if (unit == '\0')
4051 return 0;
4052 datepart = false;
4053 havefield = false;
4054 continue;
4055 }
4056 /* Else fall through to extended alternative format */
4058 case '-': /* ISO 8601 4.4.3.3 Alternative Format,
4059 * Extended */
4060 if (havefield)
4061 return DTERR_BAD_FORMAT;
4062
4063 if (!AdjustYears(val, 1, itm_in) ||
4064 !AdjustFractYears(fval, 1, itm_in))
4065 return DTERR_FIELD_OVERFLOW;
4066 if (unit == '\0')
4067 return 0;
4068 if (unit == 'T')
4069 {
4070 datepart = false;
4071 havefield = false;
4072 continue;
4073 }
4074
4075 dterr = ParseISO8601Number(str, &str, &val, &fval);
4076 if (dterr)
4077 return dterr;
4078 if (!AdjustMonths(val, itm_in) ||
4080 return DTERR_FIELD_OVERFLOW;
4081 if (*str == '\0')
4082 return 0;
4083 if (*str == 'T')
4084 {
4085 datepart = false;
4086 havefield = false;
4087 continue;
4088 }
4089 if (*str != '-')
4090 return DTERR_BAD_FORMAT;
4091 str++;
4092
4093 dterr = ParseISO8601Number(str, &str, &val, &fval);
4094 if (dterr)
4095 return dterr;
4096 if (!AdjustDays(val, 1, itm_in) ||
4098 return DTERR_FIELD_OVERFLOW;
4099 if (*str == '\0')
4100 return 0;
4101 if (*str == 'T')
4102 {
4103 datepart = false;
4104 havefield = false;
4105 continue;
4106 }
4107 return DTERR_BAD_FORMAT;
4108 default:
4109 /* not a valid date unit suffix */
4110 return DTERR_BAD_FORMAT;
4111 }
4112 }
4113 else
4114 {
4115 switch (unit) /* after T: H M S */
4116 {
4117 case 'H':
4119 return DTERR_FIELD_OVERFLOW;
4120 break;
4121 case 'M':
4123 return DTERR_FIELD_OVERFLOW;
4124 break;
4125 case 'S':
4127 return DTERR_FIELD_OVERFLOW;
4128 break;
4129 case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
4131 {
4132 if (!AdjustMicroseconds(val / 10000, 0, USECS_PER_HOUR, itm_in) ||
4133 !AdjustMicroseconds((val / 100) % 100, 0, USECS_PER_MINUTE, itm_in) ||
4136 return DTERR_FIELD_OVERFLOW;
4137 return 0;
4138 }
4139 /* Else fall through to extended alternative format */
4141 case ':': /* ISO 8601 4.4.3.3 Alternative Format,
4142 * Extended */
4143 if (havefield)
4144 return DTERR_BAD_FORMAT;
4145
4147 return DTERR_FIELD_OVERFLOW;
4148 if (unit == '\0')
4149 return 0;
4150
4151 dterr = ParseISO8601Number(str, &str, &val, &fval);
4152 if (dterr)
4153 return dterr;
4155 return DTERR_FIELD_OVERFLOW;
4156 if (*str == '\0')
4157 return 0;
4158 if (*str != ':')
4159 return DTERR_BAD_FORMAT;
4160 str++;
4161
4162 dterr = ParseISO8601Number(str, &str, &val, &fval);
4163 if (dterr)
4164 return dterr;
4166 return DTERR_FIELD_OVERFLOW;
4167 if (*str == '\0')
4168 return 0;
4169 return DTERR_BAD_FORMAT;
4170
4171 default:
4172 /* not a valid time unit suffix */
4173 return DTERR_BAD_FORMAT;
4174 }
4175 }
4176
4177 havefield = true;
4178 }
4179
4180 return 0;
4181}
static int ISO8601IntegerWidth(char *fieldstart)
Definition datetime.c:3949
static int ParseISO8601Number(char *str, char **endptr, int64 *ipart, double *fpart)
Definition datetime.c:3907

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

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

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

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

3267{
3268 int type;
3269 const datetkn *tp;
3270
3271 tp = datecache[field];
3272 /* use strncmp so that we match truncated tokens */
3273 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3274 {
3276 }
3277 if (tp == NULL)
3278 {
3280 *val = 0;
3281 }
3282 else
3283 {
3284 datecache[field] = tp;
3285 type = tp->type;
3286 *val = tp->value;
3287 }
3288
3289 return type;
3290}
static const datetkn * datecache[MAXDATEFIELDS]
Definition datetime.c:259
static const datetkn * datebsearch(const char *key, const datetkn *base, int nel)
Definition datetime.c:4303
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 2739 of file datetime.c.

2741{
2742 struct pg_itm itm;
2743 int dterr;
2744
2746 tmask, &itm);
2747 if (dterr)
2748 return dterr;
2749
2750 if (itm.tm_hour > INT_MAX)
2751 return DTERR_FIELD_OVERFLOW;
2752 tm->tm_hour = (int) itm.tm_hour;
2753 tm->tm_min = itm.tm_min;
2754 tm->tm_sec = itm.tm_sec;
2755 *fsec = itm.tm_usec;
2756
2757 return 0;
2758}
static int DecodeTimeCommon(char *str, int fmask, int range, int *tmask, struct pg_itm *itm)
Definition datetime.c:2656

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

2658{
2659 char *cp;
2660 int dterr;
2661 fsec_t fsec = 0;
2662
2663 *tmask = DTK_TIME_M;
2664
2665 errno = 0;
2666 itm->tm_hour = strtoi64(str, &cp, 10);
2667 if (errno == ERANGE)
2668 return DTERR_FIELD_OVERFLOW;
2669 if (*cp != ':')
2670 return DTERR_BAD_FORMAT;
2671 errno = 0;
2672 itm->tm_min = strtoint(cp + 1, &cp, 10);
2673 if (errno == ERANGE)
2674 return DTERR_FIELD_OVERFLOW;
2675 if (*cp == '\0')
2676 {
2677 itm->tm_sec = 0;
2678 /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2680 {
2681 if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2682 return DTERR_FIELD_OVERFLOW;
2683 itm->tm_sec = itm->tm_min;
2684 itm->tm_min = (int) itm->tm_hour;
2685 itm->tm_hour = 0;
2686 }
2687 }
2688 else if (*cp == '.')
2689 {
2690 /* always assume mm:ss.sss is MINUTE TO SECOND */
2691 dterr = ParseFractionalSecond(cp, &fsec);
2692 if (dterr)
2693 return dterr;
2694 if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2695 return DTERR_FIELD_OVERFLOW;
2696 itm->tm_sec = itm->tm_min;
2697 itm->tm_min = (int) itm->tm_hour;
2698 itm->tm_hour = 0;
2699 }
2700 else if (*cp == ':')
2701 {
2702 errno = 0;
2703 itm->tm_sec = strtoint(cp + 1, &cp, 10);
2704 if (errno == ERANGE)
2705 return DTERR_FIELD_OVERFLOW;
2706 if (*cp == '.')
2707 {
2708 dterr = ParseFractionalSecond(cp, &fsec);
2709 if (dterr)
2710 return dterr;
2711 }
2712 else if (*cp != '\0')
2713 return DTERR_BAD_FORMAT;
2714 }
2715 else
2716 return DTERR_BAD_FORMAT;
2717
2718 /* do a sanity check; but caller must check the range of tm_hour */
2719 if (itm->tm_hour < 0 ||
2720 itm->tm_min < 0 || itm->tm_min > MINS_PER_HOUR - 1 ||
2721 itm->tm_sec < 0 || itm->tm_sec > SECS_PER_MINUTE ||
2723 return DTERR_FIELD_OVERFLOW;
2724
2725 itm->tm_usec = (int) fsec;
2726
2727 return 0;
2728}
#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 2769 of file datetime.c.

2771{
2772 struct pg_itm itm;
2773 int dterr;
2774
2776 tmask, &itm);
2777 if (dterr)
2778 return dterr;
2779
2780 itm_in->tm_usec = itm.tm_usec;
2781 if (!int64_multiply_add(itm.tm_hour, USECS_PER_HOUR, &itm_in->tm_usec) ||
2782 !int64_multiply_add(itm.tm_min, USECS_PER_MINUTE, &itm_in->tm_usec) ||
2783 !int64_multiply_add(itm.tm_sec, USECS_PER_SEC, &itm_in->tm_usec))
2784 return DTERR_FIELD_OVERFLOW;
2785
2786 return 0;
2787}

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

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

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

3076{
3077 int tz;
3078 int hr,
3079 min,
3080 sec = 0;
3081 char *cp;
3082
3083 /* leading character must be "+" or "-" */
3084 if (*str != '+' && *str != '-')
3085 return DTERR_BAD_FORMAT;
3086
3087 errno = 0;
3088 hr = strtoint(str + 1, &cp, 10);
3089 if (errno == ERANGE)
3090 return DTERR_TZDISP_OVERFLOW;
3091
3092 /* explicit delimiter? */
3093 if (*cp == ':')
3094 {
3095 errno = 0;
3096 min = strtoint(cp + 1, &cp, 10);
3097 if (errno == ERANGE)
3098 return DTERR_TZDISP_OVERFLOW;
3099 if (*cp == ':')
3100 {
3101 errno = 0;
3102 sec = strtoint(cp + 1, &cp, 10);
3103 if (errno == ERANGE)
3104 return DTERR_TZDISP_OVERFLOW;
3105 }
3106 }
3107 /* otherwise, might have run things together... */
3108 else if (*cp == '\0' && strlen(str) > 3)
3109 {
3110 min = hr % 100;
3111 hr = hr / 100;
3112 /* we could, but don't, support a run-together hhmmss format */
3113 }
3114 else
3115 min = 0;
3116
3117 /* Range-check the values; see notes in datatype/timestamp.h */
3119 return DTERR_TZDISP_OVERFLOW;
3121 return DTERR_TZDISP_OVERFLOW;
3123 return DTERR_TZDISP_OVERFLOW;
3124
3125 tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
3126 if (*str == '-')
3127 tz = -tz;
3128
3129 *tzp = -tz;
3130
3131 if (*cp != '\0')
3132 return DTERR_BAD_FORMAT;
3133
3134 return 0;
3135}
#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 3160 of file datetime.c.

3163{
3164 TzAbbrevCache *tzc = &tzabbrevcache[field];
3165 bool isfixed;
3166 int isdst;
3167 const datetkn *tp;
3168
3169 /*
3170 * Do we have a cached result? Use strncmp so that we match truncated
3171 * names, although we shouldn't really see that happen with normal
3172 * abbreviations.
3173 */
3174 if (strncmp(lowtoken, tzc->abbrev, TOKMAXLEN) == 0)
3175 {
3176 *ftype = tzc->ftype;
3177 *offset = tzc->offset;
3178 *tz = tzc->tz;
3179 return 0;
3180 }
3181
3182 /*
3183 * See if the current session_timezone recognizes it. Checking this
3184 * before zoneabbrevtbl allows us to correctly handle abbreviations whose
3185 * meaning varies across zones, such as "LMT".
3186 */
3187 if (session_timezone &&
3189 &isfixed, offset, &isdst))
3190 {
3191 *ftype = (isfixed ? (isdst ? DTZ : TZ) : DYNTZ);
3192 *tz = (isfixed ? NULL : session_timezone);
3193 /* flip sign to agree with the convention used in zoneabbrevtbl */
3194 *offset = -(*offset);
3195 /* cache result; use strlcpy to truncate name if necessary */
3196 strlcpy(tzc->abbrev, lowtoken, TOKMAXLEN + 1);
3197 tzc->ftype = *ftype;
3198 tzc->offset = *offset;
3199 tzc->tz = *tz;
3200 return 0;
3201 }
3202
3203 /* Nope, so look in zoneabbrevtbl */
3204 if (zoneabbrevtbl)
3207 else
3208 tp = NULL;
3209 if (tp == NULL)
3210 {
3211 *ftype = UNKNOWN_FIELD;
3212 *offset = 0;
3213 *tz = NULL;
3214 /* failure results are not cached */
3215 }
3216 else
3217 {
3218 *ftype = tp->type;
3219 if (tp->type == DYNTZ)
3220 {
3221 *offset = 0;
3222 *tz = FetchDynamicTimeZone(zoneabbrevtbl, tp, extra);
3223 if (*tz == NULL)
3224 return DTERR_BAD_ZONE_ABBREV;
3225 }
3226 else
3227 {
3228 *offset = tp->value;
3229 *tz = NULL;
3230 }
3231
3232 /* cache result; use strlcpy to truncate name if necessary */
3233 strlcpy(tzc->abbrev, lowtoken, TOKMAXLEN + 1);
3234 tzc->ftype = *ftype;
3235 tzc->offset = *offset;
3236 tzc->tz = *tz;
3237 }
3238
3239 return 0;
3240}
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:1883
static pg_tz * FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp, DateTimeErrorExtra *extra)
Definition datetime.c:5125
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 3394 of file datetime.c.

3395{
3396 char lowtoken[TOKMAXLEN + 1];
3397 int len;
3398
3399 *offset = 0; /* avoid uninitialized vars on failure */
3400 *tz = NULL;
3401
3402 /* Downcase as much of the string as we could need */
3403 for (len = 0; len < TOKMAXLEN; len++)
3404 {
3405 if (*str == '\0' || !isalpha((unsigned char) *str))
3406 break;
3407 lowtoken[len] = pg_tolower((unsigned char) *str++);
3408 }
3409 lowtoken[len] = '\0';
3410
3411 /*
3412 * We could avoid doing repeated binary searches if we cared to duplicate
3413 * datebsearch here, but it's not clear that such an optimization would be
3414 * worth the trouble. In common cases there's probably not anything after
3415 * the zone abbrev anyway. So just search with successively truncated
3416 * strings.
3417 */
3418 while (len > 0)
3419 {
3420 bool isfixed;
3421 int isdst;
3422 const datetkn *tp;
3423
3424 /* See if the current session_timezone recognizes it. */
3425 if (session_timezone &&
3427 &isfixed, offset, &isdst))
3428 {
3429 if (isfixed)
3430 {
3431 /* flip sign to agree with the convention in zoneabbrevtbl */
3432 *offset = -(*offset);
3433 }
3434 else
3435 {
3436 /* Caller must resolve the abbrev's current meaning */
3437 *tz = session_timezone;
3438 }
3439 return len;
3440 }
3441
3442 /* Known in zoneabbrevtbl? */
3443 if (zoneabbrevtbl)
3446 else
3447 tp = NULL;
3448 if (tp != NULL)
3449 {
3450 if (tp->type == DYNTZ)
3451 {
3452 DateTimeErrorExtra extra;
3454 &extra);
3455
3456 if (tzp != NULL)
3457 {
3458 /* Caller must resolve the abbrev's current meaning */
3459 *tz = tzp;
3460 return len;
3461 }
3462 }
3463 else
3464 {
3465 /* Fixed-offset zone abbrev, so it's easy */
3466 *offset = tp->value;
3467 return len;
3468 }
3469 }
3470
3471 /* Nope, try the next shorter string. */
3472 lowtoken[--len] = '\0';
3473 }
3474
3475 /* Did not find a match */
3476 return -1;
3477}
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 3309 of file datetime.c.

3310{
3311 char *lowzone;
3312 int dterr,
3313 type;
3314 DateTimeErrorExtra extra;
3315
3316 /*
3317 * First we look in the timezone abbreviation table (to handle cases like
3318 * "EST"), and if that fails, we look in the timezone database (to handle
3319 * cases like "America/New_York"). This matches the order in which
3320 * timestamp input checks the cases; it's important because the timezone
3321 * database unwisely uses a few zone names that are identical to offset
3322 * abbreviations.
3323 */
3324
3325 /* DecodeTimezoneAbbrev requires lowercase input */
3327 strlen(tzname),
3328 false);
3329
3330 dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
3331 if (dterr)
3333
3334 if (type == TZ || type == DTZ)
3335 {
3336 /* fixed-offset abbreviation, return the offset */
3337 return TZNAME_FIXED_OFFSET;
3338 }
3339 else if (type == DYNTZ)
3340 {
3341 /* dynamic-offset abbreviation, return its referenced timezone */
3342 return TZNAME_DYNTZ;
3343 }
3344 else
3345 {
3346 /* try it as a full zone name */
3347 *tz = pg_tzset(tzname);
3348 if (*tz == NULL)
3349 ereport(ERROR,
3351 errmsg("time zone \"%s\" not recognized", tzname)));
3352 return TZNAME_ZONE;
3353 }
3354}
void DateTimeParseError(int dterr, DateTimeErrorExtra *extra, const char *str, const char *datatype, Node *escontext)
Definition datetime.c:4241
#define ereport(elevel,...)
Definition elog.h:152
#define TZNAME_ZONE
Definition datetime.h:303
#define TZNAME_FIXED_OFFSET
Definition datetime.h:301
#define TZNAME_DYNTZ
Definition datetime.h:302
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 3365 of file datetime.c.

3366{
3367 pg_tz *result;
3368 int offset;
3369
3371 {
3372 /* fixed-offset abbreviation, get a pg_tz descriptor for that */
3373 result = pg_tzset_offset(-offset); /* flip to POSIX sign convention */
3374 }
3375 return result;
3376}
int DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
Definition datetime.c:3309
pg_tz * pg_tzset_offset(long gmtoffset)
Definition pgtz.c:320

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

Referenced by lookup_timezone().

◆ DecodeUnits()

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

Definition at line 4196 of file datetime.c.

4197{
4198 int type;
4199 const datetkn *tp;
4200
4201 tp = deltacache[field];
4202 /* use strncmp so that we match truncated tokens */
4203 if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
4204 {
4206 }
4207 if (tp == NULL)
4208 {
4210 *val = 0;
4211 }
4212 else
4213 {
4214 deltacache[field] = tp;
4215 type = tp->type;
4216 *val = tp->value;
4217 }
4218
4219 return type;
4220} /* 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 1771 of file datetime.c.

1772{
1773 pg_time_t t;
1774 int zone_offset;
1775 int abbr_offset;
1776 int abbr_isdst;
1777
1778 /*
1779 * Compute the UTC time we want to probe at. (In event of overflow, we'll
1780 * probe at the epoch, which is a bit random but probably doesn't matter.)
1781 */
1783
1784 /*
1785 * Try to match the abbreviation to something in the zone definition.
1786 */
1789 {
1790 /* Success, so use the abbrev-specific answers. */
1792 return abbr_offset;
1793 }
1794
1795 /*
1796 * No match, so use the answers we already got from
1797 * DetermineTimeZoneOffsetInternal.
1798 */
1799 return zone_offset;
1800}
static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp, pg_time_t *tp)
Definition datetime.c:1631
static bool DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t, const char *abbr, pg_tz *tzp, int *offset, int *isdst)
Definition datetime.c:1848
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 1848 of file datetime.c.

1850{
1851 char upabbr[TZ_STRLEN_MAX + 1];
1852 unsigned char *p;
1853 long int gmtoff;
1854
1855 /* We need to force the abbrev to upper case */
1856 strlcpy(upabbr, abbr, sizeof(upabbr));
1857 for (p = (unsigned char *) upabbr; *p; p++)
1858 *p = pg_toupper(*p);
1859
1860 /* Look up the abbrev's meaning at this time in this zone */
1862 &t,
1863 &gmtoff,
1864 isdst,
1865 tzp))
1866 {
1867 /* Change sign to agree with DetermineTimeZoneOffset() */
1868 *offset = (int) -gmtoff;
1869 return true;
1870 }
1871 return false;
1872}
#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:1746
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 1810 of file datetime.c.

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

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

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

4380{
4381 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4382
4383 switch (style)
4384 {
4385 case USE_ISO_DATES:
4386 case USE_XSD_DATES:
4387 /* compatible with ISO date formats */
4389 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4390 *str++ = '-';
4392 *str++ = '-';
4394 break;
4395
4396 case USE_SQL_DATES:
4397 /* compatible with Oracle/Ingres date formats */
4398 if (DateOrder == DATEORDER_DMY)
4399 {
4401 *str++ = '/';
4403 }
4404 else
4405 {
4407 *str++ = '/';
4409 }
4410 *str++ = '/';
4412 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4413 break;
4414
4415 case USE_GERMAN_DATES:
4416 /* German-style date format */
4418 *str++ = '.';
4420 *str++ = '.';
4422 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4423 break;
4424
4425 case USE_POSTGRES_DATES:
4426 default:
4427 /* traditional date-only style for Postgres */
4428 if (DateOrder == DATEORDER_DMY)
4429 {
4431 *str++ = '-';
4433 }
4434 else
4435 {
4437 *str++ = '-';
4439 }
4440 *str++ = '-';
4442 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4443 break;
4444 }
4445
4446 if (tm->tm_year <= 0)
4447 {
4448 memcpy(str, " BC", 3); /* Don't copy NUL */
4449 str += 3;
4450 }
4451 *str = '\0';
4452}
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
#define USE_SQL_DATES
Definition miscadmin.h:241
#define USE_POSTGRES_DATES
Definition miscadmin.h:239
#define USE_ISO_DATES
Definition miscadmin.h:240
#define USE_XSD_DATES
Definition miscadmin.h:243
#define USE_GERMAN_DATES
Definition miscadmin.h:242

References Assert, DateOrder, DATEORDER_DMY, fb(), memcpy(), 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 4496 of file datetime.c.

4497{
4498 int day;
4499
4500 Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4501
4502 /*
4503 * Negative tm_isdst means we have no valid time zone translation.
4504 */
4505 if (tm->tm_isdst < 0)
4506 print_tz = false;
4507
4508 switch (style)
4509 {
4510 case USE_ISO_DATES:
4511 case USE_XSD_DATES:
4512 /* Compatible with ISO-8601 date formats */
4514 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4515 *str++ = '-';
4517 *str++ = '-';
4519 *str++ = (style == USE_ISO_DATES) ? ' ' : 'T';
4521 *str++ = ':';
4523 *str++ = ':';
4524 str = AppendTimestampSeconds(str, tm, fsec);
4525 if (print_tz)
4526 str = EncodeTimezone(str, tz, style);
4527 break;
4528
4529 case USE_SQL_DATES:
4530 /* Compatible with Oracle/Ingres date formats */
4531 if (DateOrder == DATEORDER_DMY)
4532 {
4534 *str++ = '/';
4536 }
4537 else
4538 {
4540 *str++ = '/';
4542 }
4543 *str++ = '/';
4545 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4546 *str++ = ' ';
4548 *str++ = ':';
4550 *str++ = ':';
4551 str = AppendTimestampSeconds(str, tm, fsec);
4552
4553 /*
4554 * Note: the uses of %.*s in this function would be risky if the
4555 * timezone names ever contain non-ASCII characters, since we are
4556 * not being careful to do encoding-aware clipping. However, all
4557 * TZ abbreviations in the IANA database are plain ASCII.
4558 */
4559 if (print_tz)
4560 {
4561 if (tzn)
4562 {
4563 sprintf(str, " %.*s", MAXTZLEN, tzn);
4564 str += strlen(str);
4565 }
4566 else
4567 str = EncodeTimezone(str, tz, style);
4568 }
4569 break;
4570
4571 case USE_GERMAN_DATES:
4572 /* German variant on European style */
4574 *str++ = '.';
4576 *str++ = '.';
4578 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4579 *str++ = ' ';
4581 *str++ = ':';
4583 *str++ = ':';
4584 str = AppendTimestampSeconds(str, tm, fsec);
4585
4586 if (print_tz)
4587 {
4588 if (tzn)
4589 {
4590 sprintf(str, " %.*s", MAXTZLEN, tzn);
4591 str += strlen(str);
4592 }
4593 else
4594 str = EncodeTimezone(str, tz, style);
4595 }
4596 break;
4597
4598 case USE_POSTGRES_DATES:
4599 default:
4600 /* Backward-compatible with traditional Postgres abstime dates */
4601 day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4602 tm->tm_wday = j2day(day);
4603 memcpy(str, days[tm->tm_wday], 3);
4604 str += 3;
4605 *str++ = ' ';
4606 if (DateOrder == DATEORDER_DMY)
4607 {
4609 *str++ = ' ';
4610 memcpy(str, months[tm->tm_mon - 1], 3);
4611 str += 3;
4612 }
4613 else
4614 {
4615 memcpy(str, months[tm->tm_mon - 1], 3);
4616 str += 3;
4617 *str++ = ' ';
4619 }
4620 *str++ = ' ';
4622 *str++ = ':';
4624 *str++ = ':';
4625 str = AppendTimestampSeconds(str, tm, fsec);
4626 *str++ = ' ';
4628 (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4629
4630 if (print_tz)
4631 {
4632 if (tzn)
4633 {
4634 sprintf(str, " %.*s", MAXTZLEN, tzn);
4635 str += strlen(str);
4636 }
4637 else
4638 {
4639 /*
4640 * We have a time zone, but no string version. Use the
4641 * numeric form, but be sure to include a leading space to
4642 * avoid formatting something which would be rejected by
4643 * the date/time parser later. - thomas 2001-10-19
4644 */
4645 *str++ = ' ';
4646 str = EncodeTimezone(str, tz, style);
4647 }
4648 }
4649 break;
4650 }
4651
4652 if (tm->tm_year <= 0)
4653 {
4654 memcpy(str, " BC", 3); /* Don't copy NUL */
4655 str += 3;
4656 }
4657 *str = '\0';
4658}
static char * EncodeTimezone(char *str, int tz, int style)
Definition datetime.c:4340
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:267

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

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

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

4466{
4468 *str++ = ':';
4470 *str++ = ':';
4471 str = AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
4472 if (print_tz)
4473 str = EncodeTimezone(str, tz, style);
4474 *str = '\0';
4475}
#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 4340 of file datetime.c.

4341{
4342 int hour,
4343 min,
4344 sec;
4345
4346 sec = abs(tz);
4347 min = sec / SECS_PER_MINUTE;
4348 sec -= min * SECS_PER_MINUTE;
4349 hour = min / MINS_PER_HOUR;
4350 min -= hour * MINS_PER_HOUR;
4351
4352 /* TZ is negated compared to sign we wish to display ... */
4353 *str++ = (tz <= 0 ? '+' : '-');
4354
4355 if (sec != 0)
4356 {
4358 *str++ = ':';
4359 str = pg_ultostr_zeropad(str, min, 2);
4360 *str++ = ':';
4361 str = pg_ultostr_zeropad(str, sec, 2);
4362 }
4363 else if (min != 0 || style == USE_XSD_DATES)
4364 {
4366 *str++ = ':';
4367 str = pg_ultostr_zeropad(str, min, 2);
4368 }
4369 else
4371 return str;
4372}

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

5127{
5129
5130 /* Just some sanity checks to prevent indexing off into nowhere */
5131 Assert(tp->type == DYNTZ);
5132 Assert(tp->value > 0 && tp->value < tbl->tblsize);
5133
5134 dtza = (DynamicZoneAbbrev *) ((char *) tbl + tp->value);
5135
5136 /* Look up the underlying zone if we haven't already */
5137 if (dtza->tz == NULL)
5138 {
5139 dtza->tz = pg_tzset(dtza->zone);
5140 if (dtza->tz == NULL)
5141 {
5142 /* Ooops, bogus zone name in config file entry */
5143 extra->dtee_timezone = dtza->zone;
5144 extra->dtee_abbrev = tp->token;
5145 }
5146 }
5147 return dtza->tz;
5148}

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

5113{
5115 /* reset tzabbrevcache, which may contain results from old table */
5116 memset(tzabbrevcache, 0, sizeof(tzabbrevcache));
5117}

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

3950{
3951 /* We might have had a leading '-' */
3952 if (*fieldstart == '-')
3953 fieldstart++;
3954 return strspn(fieldstart, "0123456789");
3955}

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

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

3908{
3909 double val;
3910
3911 /*
3912 * Historically this has accepted anything that strtod() would take,
3913 * notably including "e" notation, so continue doing that. This is
3914 * slightly annoying because the precision of double is less than that of
3915 * int64, so we would lose accuracy for inputs larger than 2^53 or so.
3916 * However, historically we rejected inputs outside the int32 range,
3917 * making that concern moot. What we do now is reject abs(val) above
3918 * 1.0e15 (a round number a bit less than 2^50), so that any accepted
3919 * value will have an exact integer part, and thereby a fraction part with
3920 * abs(*fpart) less than 1. In the absence of field complaints it doesn't
3921 * seem worth working harder.
3922 */
3923 if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3924 return DTERR_BAD_FORMAT;
3925 errno = 0;
3926 val = strtod(str, endptr);
3927 /* did we not see anything that looks like a double? */
3928 if (*endptr == str || errno != 0)
3929 return DTERR_BAD_FORMAT;
3930 /* watch out for overflow, including infinities; reject NaN too */
3931 if (isnan(val) || val < -1.0e15 || val > 1.0e15)
3932 return DTERR_FIELD_OVERFLOW;
3933 /* be very sure we truncate towards zero (cf dtrunc()) */
3934 if (val >= 0)
3935 *ipart = (int64) floor(val);
3936 else
3937 *ipart = (int64) -floor(-val);
3938 *fpart = val - *ipart;
3939 /* Callers expect this to hold */
3940 Assert(*fpart > -1.0 && *fpart < 1.0);
3941 return 0;
3942}

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

5245{
5247 int *pindex;
5248 Datum result;
5249 HeapTuple tuple;
5250 Datum values[3];
5251 bool nulls[3] = {0};
5252 const datetkn *tp;
5253 char buffer[TOKMAXLEN + 1];
5254 int gmtoffset;
5255 bool is_dst;
5256 unsigned char *p;
5257 struct pg_itm_in itm_in;
5259
5260 /* stuff done only on the first call of the function */
5261 if (SRF_IS_FIRSTCALL())
5262 {
5263 TupleDesc tupdesc;
5264 MemoryContext oldcontext;
5265
5266 /* create a function context for cross-call persistence */
5268
5269 /*
5270 * switch to memory context appropriate for multiple function calls
5271 */
5272 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5273
5274 /* allocate memory for user context */
5275 pindex = palloc_object(int);
5276 *pindex = 0;
5277 funcctx->user_fctx = pindex;
5278
5279 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
5280 elog(ERROR, "return type must be a row type");
5281 funcctx->tuple_desc = tupdesc;
5282
5283 MemoryContextSwitchTo(oldcontext);
5284 }
5285
5286 /* stuff done on every call of the function */
5288 pindex = (int *) funcctx->user_fctx;
5289
5290 if (zoneabbrevtbl == NULL ||
5293
5294 tp = zoneabbrevtbl->abbrevs + *pindex;
5295
5296 switch (tp->type)
5297 {
5298 case TZ:
5299 gmtoffset = tp->value;
5300 is_dst = false;
5301 break;
5302 case DTZ:
5303 gmtoffset = tp->value;
5304 is_dst = true;
5305 break;
5306 case DYNTZ:
5307 {
5308 /* Determine the current meaning of the abbrev */
5309 pg_tz *tzp;
5310 DateTimeErrorExtra extra;
5312 int isdst;
5313
5314 tzp = FetchDynamicTimeZone(zoneabbrevtbl, tp, &extra);
5315 if (tzp == NULL)
5317 NULL, NULL, NULL);
5320 tp->token,
5321 tzp,
5322 &isdst);
5323 is_dst = (bool) isdst;
5324 break;
5325 }
5326 default:
5327 elog(ERROR, "unrecognized timezone type %d", (int) tp->type);
5328 gmtoffset = 0; /* keep compiler quiet */
5329 is_dst = false;
5330 break;
5331 }
5332
5333 /*
5334 * Convert name to text, using upcasing conversion that is the inverse of
5335 * what ParseDateTime() uses.
5336 */
5337 strlcpy(buffer, tp->token, sizeof(buffer));
5338 for (p = (unsigned char *) buffer; *p; p++)
5339 *p = pg_toupper(*p);
5340
5341 values[0] = CStringGetTextDatum(buffer);
5342
5343 /* Convert offset (in seconds) to an interval; can't overflow */
5344 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5345 itm_in.tm_usec = (int64) gmtoffset * USECS_PER_SEC;
5349
5350 values[2] = BoolGetDatum(is_dst);
5351
5352 (*pindex)++;
5353
5354 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5355 result = HeapTupleGetDatum(tuple);
5356
5358}
int DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr, pg_tz *tzp, int *isdst)
Definition datetime.c:1810
int itmin2interval(struct pg_itm_in *itm_in, Interval *span)
Definition timestamp.c:2127
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1613
static Datum values[MAXATTR]
Definition bootstrap.c:190
#define CStringGetTextDatum(s)
Definition builtins.h:98
#define MemSet(start, val, len)
Definition c.h:1107
#define palloc_object(type)
Definition fe_memutils.h:89
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:1025
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:138
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(), result, 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 5157 of file datetime.c.

5158{
5160 int *pindex;
5161 Datum result;
5162 HeapTuple tuple;
5163 Datum values[3];
5164 bool nulls[3] = {0};
5167 const char *abbrev;
5168 long int gmtoff;
5169 int isdst;
5170 struct pg_itm_in itm_in;
5172
5173 /* stuff done only on the first call of the function */
5174 if (SRF_IS_FIRSTCALL())
5175 {
5176 TupleDesc tupdesc;
5177 MemoryContext oldcontext;
5178
5179 /* create a function context for cross-call persistence */
5181
5182 /*
5183 * switch to memory context appropriate for multiple function calls
5184 */
5185 oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5186
5187 /* allocate memory for user context */
5188 pindex = palloc_object(int);
5189 *pindex = 0;
5190 funcctx->user_fctx = pindex;
5191
5192 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
5193 elog(ERROR, "return type must be a row type");
5194 funcctx->tuple_desc = tupdesc;
5195
5196 MemoryContextSwitchTo(oldcontext);
5197 }
5198
5199 /* stuff done on every call of the function */
5201 pindex = (int *) funcctx->user_fctx;
5202
5203 while ((abbrev = pg_get_next_timezone_abbrev(pindex,
5205 {
5206 /* Ignore abbreviations that aren't all-alphabetic */
5207 if (strspn(abbrev, "ABCDEFGHIJKLMNOPQRSTUVWXYZ") != strlen(abbrev))
5208 continue;
5209
5210 /* Determine the current meaning of the abbrev */
5211 if (!pg_interpret_timezone_abbrev(abbrev,
5212 &t,
5213 &gmtoff,
5214 &isdst,
5216 continue; /* hm, not actually used in this zone? */
5217
5218 values[0] = CStringGetTextDatum(abbrev);
5219
5220 /* Convert offset (in seconds) to an interval; can't overflow */
5221 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5222 itm_in.tm_usec = (int64) gmtoff * USECS_PER_SEC;
5226
5228
5229 tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5230 result = HeapTupleGetDatum(tuple);
5231
5233 }
5234
5236}
const char * pg_get_next_timezone_abbrev(int *indx, const pg_tz *tz)
Definition localtime.c:1939

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(), result, 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 5365 of file datetime.c.

5366{
5367 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
5369 pg_tz *tz;
5370 Datum values[4];
5371 bool nulls[4] = {0};
5372 int tzoff;
5373 struct pg_tm tm;
5374 fsec_t fsec;
5375 const char *tzn;
5377 struct pg_itm_in itm_in;
5378
5379 InitMaterializedSRF(fcinfo, 0);
5380
5381 /* initialize timezone scanning code */
5383
5384 /* search for another zone to display */
5385 for (;;)
5386 {
5388 if (!tz)
5389 break;
5390
5391 /* Convert now() to local time in this zone */
5393 &tzoff, &tm, &fsec, &tzn, tz) != 0)
5394 continue; /* ignore if conversion fails */
5395
5396 /*
5397 * IANA's rather silly "Factory" time zone used to emit ridiculously
5398 * long "abbreviations" such as "Local time zone must be set--see zic
5399 * manual page" or "Local time zone must be set--use tzsetup". While
5400 * modern versions of tzdb emit the much saner "-00", it seems some
5401 * benighted packagers are hacking the IANA data so that it continues
5402 * to produce these strings. To prevent producing a weirdly wide
5403 * abbrev column, reject ridiculously long abbreviations.
5404 */
5405 if (tzn && strlen(tzn) > 31)
5406 continue;
5407
5409 values[1] = CStringGetTextDatum(tzn ? tzn : "");
5410
5411 /* Convert tzoff to an interval; can't overflow */
5412 MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5413 itm_in.tm_usec = (int64) -tzoff * USECS_PER_SEC;
5417
5418 values[3] = BoolGetDatum(tm.tm_isdst > 0);
5419
5420 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
5421 }
5422
5424 return (Datum) 0;
5425}
void InitMaterializedSRF(FunctionCallInfo fcinfo, uint32 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:1992
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 4995 of file datetime.c.

4996{
4997 FuncExpr *expr = castNode(FuncExpr, node);
4998 Node *ret = NULL;
4999 Node *typmod;
5000
5001 Assert(list_length(expr->args) >= 2);
5002
5003 typmod = (Node *) lsecond(expr->args);
5004
5005 if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
5006 {
5007 Node *source = (Node *) linitial(expr->args);
5010
5011 if (new_precis < 0 || new_precis == max_precis ||
5012 (old_precis >= 0 && new_precis >= old_precis))
5014 }
5015
5016 return ret;
5017}
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 1883 of file datetime.c.

1885{
1886 char upabbr[TZ_STRLEN_MAX + 1];
1887 unsigned char *p;
1888 long int gmtoff;
1889
1890 /* We need to force the abbrev to upper case */
1891 strlcpy(upabbr, abbr, sizeof(upabbr));
1892 for (p = (unsigned char *) upabbr; *p; p++)
1893 *p = pg_toupper(*p);
1894
1895 /* Look up the abbrev's meaning in this zone */
1897 isfixed,
1898 &gmtoff,
1899 isdst,
1900 tzp))
1901 {
1902 /* Change sign to agree with DetermineTimeZoneOffset() */
1903 *offset = (int) -gmtoff;
1904 return true;
1905 }
1906 return false;
1907}
bool pg_timezone_abbrev_is_known(const char *abbrev, bool *isfixed, long int *gmtoff, int *isdst, const pg_tz *tz)
Definition localtime.c:1864

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

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

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