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

Go to the source code of this file.

Macros

#define APPEND_CHAR(bufptr, end, newchar)
 

Functions

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

Macro Definition Documentation

◆ APPEND_CHAR

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

Function Documentation

◆ AddISO8601IntPart()

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

Definition at line 4502 of file datetime.c.

4503 {
4504  if (value == 0)
4505  return cp;
4506  sprintf(cp, "%lld%c", (long long) value, units);
4507  return cp + strlen(cp);
4508 }
static struct @150 value
#define sprintf
Definition: port.h:240

References sprintf, and value.

Referenced by EncodeInterval().

◆ AddPostgresIntPart()

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

Definition at line 4512 of file datetime.c.

4514 {
4515  if (value == 0)
4516  return cp;
4517  sprintf(cp, "%s%s%lld %s%s",
4518  (!*is_zero) ? " " : "",
4519  (*is_before && value > 0) ? "+" : "",
4520  (long long) value,
4521  units,
4522  (value != 1) ? "s" : "");
4523 
4524  /*
4525  * Each nonzero field sets is_before for (only) the next one. This is a
4526  * tad bizarre but it's how it worked before...
4527  */
4528  *is_before = (value < 0);
4529  *is_zero = false;
4530  return cp + strlen(cp);
4531 }

References sprintf, and value.

Referenced by EncodeInterval().

◆ AddVerboseIntPart()

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

Definition at line 4535 of file datetime.c.

4537 {
4538  if (value == 0)
4539  return cp;
4540  /* first nonzero value sets is_before */
4541  if (*is_zero)
4542  {
4543  *is_before = (value < 0);
4544  value = i64abs(value);
4545  }
4546  else if (*is_before)
4547  value = -value;
4548  sprintf(cp, " %lld %s%s", (long long) value, units, (value == 1) ? "" : "s");
4549  *is_zero = false;
4550  return cp + strlen(cp);
4551 }
#define i64abs(i)
Definition: c.h:1294

References i64abs, sprintf, and value.

Referenced by EncodeInterval().

◆ AdjustDays()

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

Definition at line 633 of file datetime.c.

634 {
635  int days;
636 
637  if (val < INT_MIN || val > INT_MAX)
638  return false;
639  return !pg_mul_s32_overflow((int32) val, scale, &days) &&
640  !pg_add_s32_overflow(itm_in->tm_mday, days, &itm_in->tm_mday);
641 }
const char *const days[]
Definition: datetime.c:84
signed int int32
Definition: c.h:481
long val
Definition: informix.c:664
static bool pg_mul_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:140
static bool pg_add_s32_overflow(int32 a, int32 b, int32 *result)
Definition: int.h:104
int scale
Definition: pgbench.c:181
int tm_mday
Definition: timestamp.h:85

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustFractDays()

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

Definition at line 569 of file datetime.c.

571 {
572  int extra_days;
573 
574  /* Fast path for common case */
575  if (frac == 0)
576  return true;
577 
578  /*
579  * We assume the input frac has abs value less than 1, so overflow of frac
580  * or extra_days is not an issue.
581  */
582  frac *= scale;
583  extra_days = (int) frac;
584 
585  /* ... but this could overflow, if tm_mday is already nonzero */
586  if (pg_add_s32_overflow(itm_in->tm_mday, extra_days, &itm_in->tm_mday))
587  return false;
588 
589  /* Handle any fractional day */
590  frac -= extra_days;
591  return AdjustFractMicroseconds(frac, USECS_PER_DAY, itm_in);
592 }
static bool AdjustFractMicroseconds(double frac, int64 scale, struct pg_itm_in *itm_in)
Definition: datetime.c:537
#define USECS_PER_DAY
Definition: timestamp.h:131

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustFractMicroseconds()

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

Definition at line 537 of file datetime.c.

539 {
540  int64 usec;
541 
542  /* Fast path for common case */
543  if (frac == 0)
544  return true;
545 
546  /*
547  * We assume the input frac has abs value less than 1, so overflow of frac
548  * or usec is not an issue for interesting values of scale.
549  */
550  frac *= scale;
551  usec = (int64) frac;
552 
553  /* Round off any fractional microsecond */
554  frac -= usec;
555  if (frac > 0.5)
556  usec++;
557  else if (frac < -0.5)
558  usec--;
559 
560  return !pg_add_s64_overflow(itm_in->tm_usec, usec, &itm_in->tm_usec);
561 }
static bool pg_add_s64_overflow(int64 a, int64 b, int64 *result)
Definition: int.h:161
int64 tm_usec
Definition: timestamp.h:84

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

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

◆ AdjustFractYears()

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

Definition at line 601 of file datetime.c.

603 {
604  /*
605  * As above, we assume abs(frac) < 1, so this can't overflow for any
606  * interesting value of scale.
607  */
608  int extra_months = (int) rint(frac * scale * MONTHS_PER_YEAR);
609 
610  return !pg_add_s32_overflow(itm_in->tm_mon, extra_months, &itm_in->tm_mon);
611 }
#define MONTHS_PER_YEAR
Definition: timestamp.h:108
int tm_mon
Definition: timestamp.h:86

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustMicroseconds()

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

Definition at line 618 of file datetime.c.

620 {
621  /* Handle the integer part */
622  if (!int64_multiply_add(val, scale, &itm_in->tm_usec))
623  return false;
624  /* Handle the float part */
625  return AdjustFractMicroseconds(fval, scale, itm_in);
626 }
static bool int64_multiply_add(int64 val, int64 multiplier, int64 *sum)
Definition: datetime.c:522

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustMonths()

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

Definition at line 649 of file datetime.c.

650 {
651  if (val < INT_MIN || val > INT_MAX)
652  return false;
653  return !pg_add_s32_overflow(itm_in->tm_mon, (int32) val, &itm_in->tm_mon);
654 }

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AdjustYears()

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

Definition at line 661 of file datetime.c.

663 {
664  int years;
665 
666  if (val < INT_MIN || val > INT_MAX)
667  return false;
668  return !pg_mul_s32_overflow((int32) val, scale, &years) &&
669  !pg_add_s32_overflow(itm_in->tm_year, years, &itm_in->tm_year);
670 }
int tm_year
Definition: timestamp.h:87

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ AppendSeconds()

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

Definition at line 448 of file datetime.c.

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

References Assert(), pg_ultostr(), pg_ultostr_zeropad(), 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 511 of file datetime.c.

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

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

Referenced by EncodeDateTime().

◆ CheckDateTokenTable()

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

Definition at line 4768 of file datetime.c.

4769 {
4770  bool ok = true;
4771  int i;
4772 
4773  for (i = 0; i < nel; i++)
4774  {
4775  /* check for token strings that don't fit */
4776  if (strlen(base[i].token) > TOKMAXLEN)
4777  {
4778  /* %.*s is safe since all our tokens are ASCII */
4779  elog(LOG, "token too long in %s table: \"%.*s\"",
4780  tablename,
4781  TOKMAXLEN + 1, base[i].token);
4782  ok = false;
4783  break; /* don't risk applying strcmp */
4784  }
4785  /* check for out of order */
4786  if (i > 0 &&
4787  strcmp(base[i - 1].token, base[i].token) >= 0)
4788  {
4789  elog(LOG, "ordering error in %s table: \"%s\" >= \"%s\"",
4790  tablename,
4791  base[i - 1].token,
4792  base[i].token);
4793  ok = false;
4794  }
4795  }
4796  return ok;
4797 }
#define LOG
Definition: elog.h:31
#define elog(elevel,...)
Definition: elog.h:224
#define TOKMAXLEN
Definition: datetime.h:204
#define token
Definition: indent_globs.h:126
int i
Definition: isn.c:73

References elog, i, LOG, token, and TOKMAXLEN.

Referenced by CheckDateTokenTables(), and ConvertTimeZoneAbbrevs().

◆ CheckDateTokenTables()

bool CheckDateTokenTables ( void  )

Definition at line 4800 of file datetime.c.

4801 {
4802  bool ok = true;
4803 
4804  Assert(UNIX_EPOCH_JDATE == date2j(1970, 1, 1));
4805  Assert(POSTGRES_EPOCH_JDATE == date2j(2000, 1, 1));
4806 
4807  ok &= CheckDateTokenTable("datetktbl", datetktbl, szdatetktbl);
4808  ok &= CheckDateTokenTable("deltatktbl", deltatktbl, szdeltatktbl);
4809  return ok;
4810 }
static bool CheckDateTokenTable(const char *tablename, const datetkn *base, int nel)
Definition: datetime.c:4768
static const datetkn datetktbl[]
Definition: datetime.c:105
static const int szdeltatktbl
Definition: datetime.c:252
static const int szdatetktbl
Definition: datetime.c:181
int date2j(int year, int month, int day)
Definition: datetime.c:286
static const datetkn deltatktbl[]
Definition: datetime.c:187
#define UNIX_EPOCH_JDATE
Definition: timestamp.h:234
#define POSTGRES_EPOCH_JDATE
Definition: timestamp.h:235

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

Referenced by PostmasterMain().

◆ ClearPgItmIn()

static void ClearPgItmIn ( struct pg_itm_in itm_in)
inlinestatic

Definition at line 3329 of file datetime.c.

3330 {
3331  itm_in->tm_usec = 0;
3332  itm_in->tm_mday = 0;
3333  itm_in->tm_mon = 0;
3334  itm_in->tm_year = 0;
3335 }

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

Referenced by DecodeInterval(), and DecodeISO8601Interval().

◆ ConvertTimeZoneAbbrevs()

TimeZoneAbbrevTable* ConvertTimeZoneAbbrevs ( struct tzEntry abbrevs,
int  n 
)

Definition at line 4862 of file datetime.c.

4863 {
4864  TimeZoneAbbrevTable *tbl;
4865  Size tbl_size;
4866  int i;
4867 
4868  /* Space for fixed fields and datetkn array */
4869  tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
4870  n * sizeof(datetkn);
4871  tbl_size = MAXALIGN(tbl_size);
4872  /* Count up space for dynamic abbreviations */
4873  for (i = 0; i < n; i++)
4874  {
4875  struct tzEntry *abbr = abbrevs + i;
4876 
4877  if (abbr->zone != NULL)
4878  {
4879  Size dsize;
4880 
4881  dsize = offsetof(DynamicZoneAbbrev, zone) +
4882  strlen(abbr->zone) + 1;
4883  tbl_size += MAXALIGN(dsize);
4884  }
4885  }
4886 
4887  /* Alloc the result ... */
4888  tbl = guc_malloc(LOG, tbl_size);
4889  if (!tbl)
4890  return NULL;
4891 
4892  /* ... and fill it in */
4893  tbl->tblsize = tbl_size;
4894  tbl->numabbrevs = n;
4895  /* in this loop, tbl_size reprises the space calculation above */
4896  tbl_size = offsetof(TimeZoneAbbrevTable, abbrevs) +
4897  n * sizeof(datetkn);
4898  tbl_size = MAXALIGN(tbl_size);
4899  for (i = 0; i < n; i++)
4900  {
4901  struct tzEntry *abbr = abbrevs + i;
4902  datetkn *dtoken = tbl->abbrevs + i;
4903 
4904  /* use strlcpy to truncate name if necessary */
4905  strlcpy(dtoken->token, abbr->abbrev, TOKMAXLEN + 1);
4906  if (abbr->zone != NULL)
4907  {
4908  /* Allocate a DynamicZoneAbbrev for this abbreviation */
4909  DynamicZoneAbbrev *dtza;
4910  Size dsize;
4911 
4912  dtza = (DynamicZoneAbbrev *) ((char *) tbl + tbl_size);
4913  dtza->tz = NULL;
4914  strcpy(dtza->zone, abbr->zone);
4915 
4916  dtoken->type = DYNTZ;
4917  /* value is offset from table start to DynamicZoneAbbrev */
4918  dtoken->value = (int32) tbl_size;
4919 
4920  dsize = offsetof(DynamicZoneAbbrev, zone) +
4921  strlen(abbr->zone) + 1;
4922  tbl_size += MAXALIGN(dsize);
4923  }
4924  else
4925  {
4926  dtoken->type = abbr->is_dst ? DTZ : TZ;
4927  dtoken->value = abbr->offset;
4928  }
4929  }
4930 
4931  /* Assert the two loops above agreed on size calculations */
4932  Assert(tbl->tblsize == tbl_size);
4933 
4934  /* Check the ordering, if testing */
4935  Assert(CheckDateTokenTable("timezone abbreviations", tbl->abbrevs, n));
4936 
4937  return tbl;
4938 }
#define MAXALIGN(LEN)
Definition: c.h:798
size_t Size
Definition: c.h:592
void * guc_malloc(int elevel, size_t size)
Definition: guc.c:640
#define TZ
Definition: datetime.h:95
#define DTZ
Definition: datetime.h:96
#define DYNTZ
Definition: datetime.h:97
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
char zone[FLEXIBLE_ARRAY_MEMBER]
Definition: datetime.h:227
datetkn abbrevs[FLEXIBLE_ARRAY_MEMBER]
Definition: datetime.h:219
char token[TOKMAXLEN+1]
Definition: datetime.h:209
int32 value
Definition: datetime.h:211
char type
Definition: datetime.h:210
char * zone
Definition: tzparser.h:27
int offset
Definition: tzparser.h:29
char * abbrev
Definition: tzparser.h:26
bool is_dst
Definition: tzparser.h:30
Definition: zic.c:94

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

Referenced by load_tzoffsets().

◆ date2j()

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

Definition at line 286 of file datetime.c.

287 {
288  int julian;
289  int century;
290 
291  if (month > 2)
292  {
293  month += 1;
294  year += 4800;
295  }
296  else
297  {
298  month += 13;
299  year += 4799;
300  }
301 
302  century = year / 100;
303  julian = year * 365 - 32167;
304  julian += year / 4 - century + century / 4;
305  julian += 7834 * month / 256 + day;
306 
307  return julian;
308 } /* date2j() */

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

◆ datebsearch()

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

Definition at line 4142 of file datetime.c.

4143 {
4144  if (nel > 0)
4145  {
4146  const datetkn *last = base + nel - 1,
4147  *position;
4148  int result;
4149 
4150  while (last >= base)
4151  {
4152  position = base + ((last - base) >> 1);
4153  /* precheck the first character for a bit of extra speed */
4154  result = (int) key[0] - (int) position->token[0];
4155  if (result == 0)
4156  {
4157  /* use strncmp so that we match truncated tokens */
4158  result = strncmp(key, position->token, TOKMAXLEN);
4159  if (result == 0)
4160  return position;
4161  }
4162  if (result < 0)
4163  last = position - 1;
4164  else
4165  base = position + 1;
4166  }
4167  }
4168  return NULL;
4169 }

References sort-test::key, and TOKMAXLEN.

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

◆ DateTimeParseError()

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

Definition at line 4081 of file datetime.c.

4084 {
4085  switch (dterr)
4086  {
4087  case DTERR_FIELD_OVERFLOW:
4088  errsave(escontext,
4089  (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
4090  errmsg("date/time field value out of range: \"%s\"",
4091  str)));
4092  break;
4094  /* <nanny>same as above, but add hint about DateStyle</nanny> */
4095  errsave(escontext,
4096  (errcode(ERRCODE_DATETIME_FIELD_OVERFLOW),
4097  errmsg("date/time field value out of range: \"%s\"",
4098  str),
4099  errhint("Perhaps you need a different \"datestyle\" setting.")));
4100  break;
4102  errsave(escontext,
4103  (errcode(ERRCODE_INTERVAL_FIELD_OVERFLOW),
4104  errmsg("interval field value out of range: \"%s\"",
4105  str)));
4106  break;
4107  case DTERR_TZDISP_OVERFLOW:
4108  errsave(escontext,
4109  (errcode(ERRCODE_INVALID_TIME_ZONE_DISPLACEMENT_VALUE),
4110  errmsg("time zone displacement out of range: \"%s\"",
4111  str)));
4112  break;
4113  case DTERR_BAD_TIMEZONE:
4114  errsave(escontext,
4115  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4116  errmsg("time zone \"%s\" not recognized",
4117  extra->dtee_timezone)));
4118  break;
4119  case DTERR_BAD_ZONE_ABBREV:
4120  errsave(escontext,
4121  (errcode(ERRCODE_CONFIG_FILE_ERROR),
4122  errmsg("time zone \"%s\" not recognized",
4123  extra->dtee_timezone),
4124  errdetail("This time zone name appears in the configuration file for time zone abbreviation \"%s\".",
4125  extra->dtee_abbrev)));
4126  break;
4127  case DTERR_BAD_FORMAT:
4128  default:
4129  errsave(escontext,
4130  (errcode(ERRCODE_INVALID_DATETIME_FORMAT),
4131  errmsg("invalid input syntax for type %s: \"%s\"",
4132  datatype, str)));
4133  break;
4134  }
4135 }
int errdetail(const char *fmt,...)
Definition: elog.c:1205
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define errsave(context,...)
Definition: elog.h:260
#define DTERR_BAD_ZONE_ABBREV
Definition: datetime.h:288
#define DTERR_INTERVAL_OVERFLOW
Definition: datetime.h:285
#define DTERR_BAD_TIMEZONE
Definition: datetime.h:287
#define DTERR_TZDISP_OVERFLOW
Definition: datetime.h:286
#define DTERR_FIELD_OVERFLOW
Definition: datetime.h:283
#define DTERR_MD_FIELD_OVERFLOW
Definition: datetime.h:284
const char * dtee_timezone
Definition: datetime.h:293
const char * dtee_abbrev
Definition: datetime.h:295

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

Referenced by date_in(), DecodeTimezoneName(), do_to_timestamp(), interval_in(), pg_timezone_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 2387 of file datetime.c.

2389 {
2390  fsec_t fsec;
2391  int nf = 0;
2392  int i,
2393  len;
2394  int dterr;
2395  bool haveTextMonth = false;
2396  int type,
2397  val,
2398  dmask = 0;
2399  char *field[MAXDATEFIELDS];
2400 
2401  *tmask = 0;
2402 
2403  /* parse this string... */
2404  while (*str != '\0' && nf < MAXDATEFIELDS)
2405  {
2406  /* skip field separators */
2407  while (*str != '\0' && !isalnum((unsigned char) *str))
2408  str++;
2409 
2410  if (*str == '\0')
2411  return DTERR_BAD_FORMAT; /* end of string after separator */
2412 
2413  field[nf] = str;
2414  if (isdigit((unsigned char) *str))
2415  {
2416  while (isdigit((unsigned char) *str))
2417  str++;
2418  }
2419  else if (isalpha((unsigned char) *str))
2420  {
2421  while (isalpha((unsigned char) *str))
2422  str++;
2423  }
2424 
2425  /* Just get rid of any non-digit, non-alpha characters... */
2426  if (*str != '\0')
2427  *str++ = '\0';
2428  nf++;
2429  }
2430 
2431  /* look first for text fields, since that will be unambiguous month */
2432  for (i = 0; i < nf; i++)
2433  {
2434  if (isalpha((unsigned char) *field[i]))
2435  {
2436  type = DecodeSpecial(i, field[i], &val);
2437  if (type == IGNORE_DTF)
2438  continue;
2439 
2440  dmask = DTK_M(type);
2441  switch (type)
2442  {
2443  case MONTH:
2444  tm->tm_mon = val;
2445  haveTextMonth = true;
2446  break;
2447 
2448  default:
2449  return DTERR_BAD_FORMAT;
2450  }
2451  if (fmask & dmask)
2452  return DTERR_BAD_FORMAT;
2453 
2454  fmask |= dmask;
2455  *tmask |= dmask;
2456 
2457  /* mark this field as being completed */
2458  field[i] = NULL;
2459  }
2460  }
2461 
2462  /* now pick up remaining numeric fields */
2463  for (i = 0; i < nf; i++)
2464  {
2465  if (field[i] == NULL)
2466  continue;
2467 
2468  if ((len = strlen(field[i])) <= 0)
2469  return DTERR_BAD_FORMAT;
2470 
2471  dterr = DecodeNumber(len, field[i], haveTextMonth, fmask,
2472  &dmask, tm,
2473  &fsec, is2digits);
2474  if (dterr)
2475  return dterr;
2476 
2477  if (fmask & dmask)
2478  return DTERR_BAD_FORMAT;
2479 
2480  fmask |= dmask;
2481  *tmask |= dmask;
2482  }
2483 
2484  if ((fmask & ~(DTK_M(DOY) | DTK_M(TZ))) != DTK_DATE_M)
2485  return DTERR_BAD_FORMAT;
2486 
2487  /* validation of the field values must wait until ValidateDate() */
2488 
2489  return 0;
2490 }
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:2716
int DecodeSpecial(int field, const char *lowtoken, int *val)
Definition: datetime.c:3137
int32 fsec_t
Definition: timestamp.h:41
#define MAXDATEFIELDS
Definition: datetime.h:202
#define MONTH
Definition: datetime.h:91
#define IGNORE_DTF
Definition: datetime.h:98
#define DTK_M(t)
Definition: datetime.h:187
#define DTK_DATE_M
Definition: datetime.h:191
#define DOY
Definition: datetime.h:105
const void size_t len
int tm_mon
Definition: pgtime.h:40
const char * type

References DecodeNumber(), DecodeSpecial(), DOY, DTERR_BAD_FORMAT, DTK_DATE_M, DTK_M, i, IGNORE_DTF, len, MAXDATEFIELDS, MONTH, generate_unaccent_rules::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 978 of file datetime.c.

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

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

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

◆ DecodeInterval()

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

Definition at line 3353 of file datetime.c.

3355 {
3356  bool force_negative = false;
3357  bool is_before = false;
3358  bool parsing_unit_val = false;
3359  char *cp;
3360  int fmask = 0,
3361  tmask,
3362  type,
3363  uval;
3364  int i;
3365  int dterr;
3366  int64 val;
3367  double fval;
3368 
3369  *dtype = DTK_DELTA;
3370  type = IGNORE_DTF;
3371  ClearPgItmIn(itm_in);
3372 
3373  /*----------
3374  * The SQL standard defines the interval literal
3375  * '-1 1:00:00'
3376  * to mean "negative 1 days and negative 1 hours", while Postgres
3377  * traditionally treats this as meaning "negative 1 days and positive
3378  * 1 hours". In SQL_STANDARD intervalstyle, we apply the leading sign
3379  * to all fields if there are no other explicit signs.
3380  *
3381  * We leave the signs alone if there are additional explicit signs.
3382  * This protects us against misinterpreting postgres-style dump output,
3383  * since the postgres-style output code has always put an explicit sign on
3384  * all fields following a negative field. But note that SQL-spec output
3385  * is ambiguous and can be misinterpreted on load! (So it's best practice
3386  * to dump in postgres style, not SQL style.)
3387  *----------
3388  */
3389  if (IntervalStyle == INTSTYLE_SQL_STANDARD && nf > 0 && *field[0] == '-')
3390  {
3391  force_negative = true;
3392  /* Check for additional explicit signs */
3393  for (i = 1; i < nf; i++)
3394  {
3395  if (*field[i] == '-' || *field[i] == '+')
3396  {
3397  force_negative = false;
3398  break;
3399  }
3400  }
3401  }
3402 
3403  /* read through list backwards to pick up units before values */
3404  for (i = nf - 1; i >= 0; i--)
3405  {
3406  switch (ftype[i])
3407  {
3408  case DTK_TIME:
3409  dterr = DecodeTimeForInterval(field[i], fmask, range,
3410  &tmask, itm_in);
3411  if (dterr)
3412  return dterr;
3413  if (force_negative &&
3414  itm_in->tm_usec > 0)
3415  itm_in->tm_usec = -itm_in->tm_usec;
3416  type = DTK_DAY;
3417  parsing_unit_val = false;
3418  break;
3419 
3420  case DTK_TZ:
3421 
3422  /*
3423  * Timezone means a token with a leading sign character and at
3424  * least one digit; there could be ':', '.', '-' embedded in
3425  * it as well.
3426  */
3427  Assert(*field[i] == '-' || *field[i] == '+');
3428 
3429  /*
3430  * Check for signed hh:mm or hh:mm:ss. If so, process exactly
3431  * like DTK_TIME case above, plus handling the sign.
3432  */
3433  if (strchr(field[i] + 1, ':') != NULL &&
3434  DecodeTimeForInterval(field[i] + 1, fmask, range,
3435  &tmask, itm_in) == 0)
3436  {
3437  if (*field[i] == '-')
3438  {
3439  /* flip the sign on time field */
3440  if (itm_in->tm_usec == PG_INT64_MIN)
3441  return DTERR_FIELD_OVERFLOW;
3442  itm_in->tm_usec = -itm_in->tm_usec;
3443  }
3444 
3445  if (force_negative &&
3446  itm_in->tm_usec > 0)
3447  itm_in->tm_usec = -itm_in->tm_usec;
3448 
3449  /*
3450  * Set the next type to be a day, if units are not
3451  * specified. This handles the case of '1 +02:03' since we
3452  * are reading right to left.
3453  */
3454  type = DTK_DAY;
3455  parsing_unit_val = false;
3456  break;
3457  }
3458 
3459  /*
3460  * Otherwise, fall through to DTK_NUMBER case, which can
3461  * handle signed float numbers and signed year-month values.
3462  */
3463 
3464  /* FALLTHROUGH */
3465 
3466  case DTK_DATE:
3467  case DTK_NUMBER:
3468  if (type == IGNORE_DTF)
3469  {
3470  /* use typmod to decide what rightmost field is */
3471  switch (range)
3472  {
3473  case INTERVAL_MASK(YEAR):
3474  type = DTK_YEAR;
3475  break;
3476  case INTERVAL_MASK(MONTH):
3478  type = DTK_MONTH;
3479  break;
3480  case INTERVAL_MASK(DAY):
3481  type = DTK_DAY;
3482  break;
3483  case INTERVAL_MASK(HOUR):
3485  type = DTK_HOUR;
3486  break;
3487  case INTERVAL_MASK(MINUTE):
3490  type = DTK_MINUTE;
3491  break;
3492  case INTERVAL_MASK(SECOND):
3496  type = DTK_SECOND;
3497  break;
3498  default:
3499  type = DTK_SECOND;
3500  break;
3501  }
3502  }
3503 
3504  errno = 0;
3505  val = strtoi64(field[i], &cp, 10);
3506  if (errno == ERANGE)
3507  return DTERR_FIELD_OVERFLOW;
3508 
3509  if (*cp == '-')
3510  {
3511  /* SQL "years-months" syntax */
3512  int val2;
3513 
3514  val2 = strtoint(cp + 1, &cp, 10);
3515  if (errno == ERANGE || val2 < 0 || val2 >= MONTHS_PER_YEAR)
3516  return DTERR_FIELD_OVERFLOW;
3517  if (*cp != '\0')
3518  return DTERR_BAD_FORMAT;
3519  type = DTK_MONTH;
3520  if (*field[i] == '-')
3521  val2 = -val2;
3523  return DTERR_FIELD_OVERFLOW;
3524  if (pg_add_s64_overflow(val, val2, &val))
3525  return DTERR_FIELD_OVERFLOW;
3526  fval = 0;
3527  }
3528  else if (*cp == '.')
3529  {
3530  dterr = ParseFraction(cp, &fval);
3531  if (dterr)
3532  return dterr;
3533  if (*field[i] == '-')
3534  fval = -fval;
3535  }
3536  else if (*cp == '\0')
3537  fval = 0;
3538  else
3539  return DTERR_BAD_FORMAT;
3540 
3541  tmask = 0; /* DTK_M(type); */
3542 
3543  if (force_negative)
3544  {
3545  /* val and fval should be of same sign, but test anyway */
3546  if (val > 0)
3547  val = -val;
3548  if (fval > 0)
3549  fval = -fval;
3550  }
3551 
3552  switch (type)
3553  {
3554  case DTK_MICROSEC:
3555  if (!AdjustMicroseconds(val, fval, 1, itm_in))
3556  return DTERR_FIELD_OVERFLOW;
3557  tmask = DTK_M(MICROSECOND);
3558  break;
3559 
3560  case DTK_MILLISEC:
3561  if (!AdjustMicroseconds(val, fval, 1000, itm_in))
3562  return DTERR_FIELD_OVERFLOW;
3563  tmask = DTK_M(MILLISECOND);
3564  break;
3565 
3566  case DTK_SECOND:
3567  if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
3568  return DTERR_FIELD_OVERFLOW;
3569 
3570  /*
3571  * If any subseconds were specified, consider this
3572  * microsecond and millisecond input as well.
3573  */
3574  if (fval == 0)
3575  tmask = DTK_M(SECOND);
3576  else
3577  tmask = DTK_ALL_SECS_M;
3578  break;
3579 
3580  case DTK_MINUTE:
3581  if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3582  return DTERR_FIELD_OVERFLOW;
3583  tmask = DTK_M(MINUTE);
3584  break;
3585 
3586  case DTK_HOUR:
3587  if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3588  return DTERR_FIELD_OVERFLOW;
3589  tmask = DTK_M(HOUR);
3590  type = DTK_DAY; /* set for next field */
3591  break;
3592 
3593  case DTK_DAY:
3594  if (!AdjustDays(val, 1, itm_in) ||
3595  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3596  return DTERR_FIELD_OVERFLOW;
3597  tmask = DTK_M(DAY);
3598  break;
3599 
3600  case DTK_WEEK:
3601  if (!AdjustDays(val, 7, itm_in) ||
3602  !AdjustFractDays(fval, 7, itm_in))
3603  return DTERR_FIELD_OVERFLOW;
3604  tmask = DTK_M(WEEK);
3605  break;
3606 
3607  case DTK_MONTH:
3608  if (!AdjustMonths(val, itm_in) ||
3609  !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3610  return DTERR_FIELD_OVERFLOW;
3611  tmask = DTK_M(MONTH);
3612  break;
3613 
3614  case DTK_YEAR:
3615  if (!AdjustYears(val, 1, itm_in) ||
3616  !AdjustFractYears(fval, 1, itm_in))
3617  return DTERR_FIELD_OVERFLOW;
3618  tmask = DTK_M(YEAR);
3619  break;
3620 
3621  case DTK_DECADE:
3622  if (!AdjustYears(val, 10, itm_in) ||
3623  !AdjustFractYears(fval, 10, itm_in))
3624  return DTERR_FIELD_OVERFLOW;
3625  tmask = DTK_M(DECADE);
3626  break;
3627 
3628  case DTK_CENTURY:
3629  if (!AdjustYears(val, 100, itm_in) ||
3630  !AdjustFractYears(fval, 100, itm_in))
3631  return DTERR_FIELD_OVERFLOW;
3632  tmask = DTK_M(CENTURY);
3633  break;
3634 
3635  case DTK_MILLENNIUM:
3636  if (!AdjustYears(val, 1000, itm_in) ||
3637  !AdjustFractYears(fval, 1000, itm_in))
3638  return DTERR_FIELD_OVERFLOW;
3639  tmask = DTK_M(MILLENNIUM);
3640  break;
3641 
3642  default:
3643  return DTERR_BAD_FORMAT;
3644  }
3645  parsing_unit_val = false;
3646  break;
3647 
3648  case DTK_STRING:
3649  case DTK_SPECIAL:
3650  /* reject consecutive unhandled units */
3651  if (parsing_unit_val)
3652  return DTERR_BAD_FORMAT;
3653  type = DecodeUnits(i, field[i], &uval);
3654  if (type == UNKNOWN_FIELD)
3655  type = DecodeSpecial(i, field[i], &uval);
3656  if (type == IGNORE_DTF)
3657  continue;
3658 
3659  tmask = 0; /* DTK_M(type); */
3660  switch (type)
3661  {
3662  case UNITS:
3663  type = uval;
3664  parsing_unit_val = true;
3665  break;
3666 
3667  case AGO:
3668 
3669  /*
3670  * "ago" is only allowed to appear at the end of the
3671  * interval.
3672  */
3673  if (i != nf - 1)
3674  return DTERR_BAD_FORMAT;
3675  is_before = true;
3676  type = uval;
3677  break;
3678 
3679  case RESERV:
3680  tmask = (DTK_DATE_M | DTK_TIME_M);
3681 
3682  /*
3683  * Only reserved words corresponding to infinite
3684  * intervals are accepted.
3685  */
3686  if (uval != DTK_LATE && uval != DTK_EARLY)
3687  return DTERR_BAD_FORMAT;
3688 
3689  /*
3690  * Infinity cannot be followed by anything else. We
3691  * could allow "ago" to reverse the sign of infinity
3692  * but using signed infinity is more intuitive.
3693  */
3694  if (i != nf - 1)
3695  return DTERR_BAD_FORMAT;
3696 
3697  *dtype = uval;
3698  break;
3699 
3700  default:
3701  return DTERR_BAD_FORMAT;
3702  }
3703  break;
3704 
3705  default:
3706  return DTERR_BAD_FORMAT;
3707  }
3708 
3709  if (tmask & fmask)
3710  return DTERR_BAD_FORMAT;
3711  fmask |= tmask;
3712  }
3713 
3714  /* ensure that at least one time field has been found */
3715  if (fmask == 0)
3716  return DTERR_BAD_FORMAT;
3717 
3718  /* reject if unit appeared and was never handled */
3719  if (parsing_unit_val)
3720  return DTERR_BAD_FORMAT;
3721 
3722  /* finally, AGO negates everything */
3723  if (is_before)
3724  {
3725  if (itm_in->tm_usec == PG_INT64_MIN ||
3726  itm_in->tm_mday == INT_MIN ||
3727  itm_in->tm_mon == INT_MIN ||
3728  itm_in->tm_year == INT_MIN)
3729  return DTERR_FIELD_OVERFLOW;
3730 
3731  itm_in->tm_usec = -itm_in->tm_usec;
3732  itm_in->tm_mday = -itm_in->tm_mday;
3733  itm_in->tm_mon = -itm_in->tm_mon;
3734  itm_in->tm_year = -itm_in->tm_year;
3735  }
3736 
3737  return 0;
3738 }
int DecodeUnits(int field, const char *lowtoken, int *val)
Definition: datetime.c:4036
static bool AdjustDays(int64 val, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:633
static bool AdjustFractYears(double frac, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:601
static bool AdjustMicroseconds(int64 val, double fval, int64 scale, struct pg_itm_in *itm_in)
Definition: datetime.c:618
static int DecodeTimeForInterval(char *str, int fmask, int range, int *tmask, struct pg_itm_in *itm_in)
Definition: datetime.c:2690
static bool AdjustYears(int64 val, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:661
static bool AdjustMonths(int64 val, struct pg_itm_in *itm_in)
Definition: datetime.c:649
static bool AdjustFractDays(double frac, int scale, struct pg_itm_in *itm_in)
Definition: datetime.c:569
static void ClearPgItmIn(struct pg_itm_in *itm_in)
Definition: datetime.c:3329
#define strtoi64(str, endptr, base)
Definition: c.h:1284
#define PG_INT64_MIN
Definition: c.h:578
#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:124
#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:219
#define INTSTYLE_SQL_STANDARD
Definition: miscadmin.h:257
static struct cvec * range(struct vars *v, chr a, chr b, int cases)
Definition: regc_locale.c:412
#define INTERVAL_MASK(b)
Definition: timestamp.h:73

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

Referenced by interval_in().

◆ DecodeISO8601Interval()

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

Definition at line 3818 of file datetime.c.

3820 {
3821  bool datepart = true;
3822  bool havefield = false;
3823 
3824  *dtype = DTK_DELTA;
3825  ClearPgItmIn(itm_in);
3826 
3827  if (strlen(str) < 2 || str[0] != 'P')
3828  return DTERR_BAD_FORMAT;
3829 
3830  str++;
3831  while (*str)
3832  {
3833  char *fieldstart;
3834  int64 val;
3835  double fval;
3836  char unit;
3837  int dterr;
3838 
3839  if (*str == 'T') /* T indicates the beginning of the time part */
3840  {
3841  datepart = false;
3842  havefield = false;
3843  str++;
3844  continue;
3845  }
3846 
3847  fieldstart = str;
3848  dterr = ParseISO8601Number(str, &str, &val, &fval);
3849  if (dterr)
3850  return dterr;
3851 
3852  /*
3853  * Note: we could step off the end of the string here. Code below
3854  * *must* exit the loop if unit == '\0'.
3855  */
3856  unit = *str++;
3857 
3858  if (datepart)
3859  {
3860  switch (unit) /* before T: Y M W D */
3861  {
3862  case 'Y':
3863  if (!AdjustYears(val, 1, itm_in) ||
3864  !AdjustFractYears(fval, 1, itm_in))
3865  return DTERR_FIELD_OVERFLOW;
3866  break;
3867  case 'M':
3868  if (!AdjustMonths(val, itm_in) ||
3869  !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3870  return DTERR_FIELD_OVERFLOW;
3871  break;
3872  case 'W':
3873  if (!AdjustDays(val, 7, itm_in) ||
3874  !AdjustFractDays(fval, 7, itm_in))
3875  return DTERR_FIELD_OVERFLOW;
3876  break;
3877  case 'D':
3878  if (!AdjustDays(val, 1, itm_in) ||
3879  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3880  return DTERR_FIELD_OVERFLOW;
3881  break;
3882  case 'T': /* ISO 8601 4.4.3.3 Alternative Format / Basic */
3883  case '\0':
3884  if (ISO8601IntegerWidth(fieldstart) == 8 && !havefield)
3885  {
3886  if (!AdjustYears(val / 10000, 1, itm_in) ||
3887  !AdjustMonths((val / 100) % 100, itm_in) ||
3888  !AdjustDays(val % 100, 1, itm_in) ||
3889  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3890  return DTERR_FIELD_OVERFLOW;
3891  if (unit == '\0')
3892  return 0;
3893  datepart = false;
3894  havefield = false;
3895  continue;
3896  }
3897  /* Else fall through to extended alternative format */
3898  /* FALLTHROUGH */
3899  case '-': /* ISO 8601 4.4.3.3 Alternative Format,
3900  * Extended */
3901  if (havefield)
3902  return DTERR_BAD_FORMAT;
3903 
3904  if (!AdjustYears(val, 1, itm_in) ||
3905  !AdjustFractYears(fval, 1, itm_in))
3906  return DTERR_FIELD_OVERFLOW;
3907  if (unit == '\0')
3908  return 0;
3909  if (unit == 'T')
3910  {
3911  datepart = false;
3912  havefield = false;
3913  continue;
3914  }
3915 
3916  dterr = ParseISO8601Number(str, &str, &val, &fval);
3917  if (dterr)
3918  return dterr;
3919  if (!AdjustMonths(val, itm_in) ||
3920  !AdjustFractDays(fval, DAYS_PER_MONTH, itm_in))
3921  return DTERR_FIELD_OVERFLOW;
3922  if (*str == '\0')
3923  return 0;
3924  if (*str == 'T')
3925  {
3926  datepart = false;
3927  havefield = false;
3928  continue;
3929  }
3930  if (*str != '-')
3931  return DTERR_BAD_FORMAT;
3932  str++;
3933 
3934  dterr = ParseISO8601Number(str, &str, &val, &fval);
3935  if (dterr)
3936  return dterr;
3937  if (!AdjustDays(val, 1, itm_in) ||
3938  !AdjustFractMicroseconds(fval, USECS_PER_DAY, itm_in))
3939  return DTERR_FIELD_OVERFLOW;
3940  if (*str == '\0')
3941  return 0;
3942  if (*str == 'T')
3943  {
3944  datepart = false;
3945  havefield = false;
3946  continue;
3947  }
3948  return DTERR_BAD_FORMAT;
3949  default:
3950  /* not a valid date unit suffix */
3951  return DTERR_BAD_FORMAT;
3952  }
3953  }
3954  else
3955  {
3956  switch (unit) /* after T: H M S */
3957  {
3958  case 'H':
3959  if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3960  return DTERR_FIELD_OVERFLOW;
3961  break;
3962  case 'M':
3963  if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3964  return DTERR_FIELD_OVERFLOW;
3965  break;
3966  case 'S':
3967  if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
3968  return DTERR_FIELD_OVERFLOW;
3969  break;
3970  case '\0': /* ISO 8601 4.4.3.3 Alternative Format */
3971  if (ISO8601IntegerWidth(fieldstart) == 6 && !havefield)
3972  {
3973  if (!AdjustMicroseconds(val / 10000, 0, USECS_PER_HOUR, itm_in) ||
3974  !AdjustMicroseconds((val / 100) % 100, 0, USECS_PER_MINUTE, itm_in) ||
3975  !AdjustMicroseconds(val % 100, 0, USECS_PER_SEC, itm_in) ||
3976  !AdjustFractMicroseconds(fval, 1, itm_in))
3977  return DTERR_FIELD_OVERFLOW;
3978  return 0;
3979  }
3980  /* Else fall through to extended alternative format */
3981  /* FALLTHROUGH */
3982  case ':': /* ISO 8601 4.4.3.3 Alternative Format,
3983  * Extended */
3984  if (havefield)
3985  return DTERR_BAD_FORMAT;
3986 
3987  if (!AdjustMicroseconds(val, fval, USECS_PER_HOUR, itm_in))
3988  return DTERR_FIELD_OVERFLOW;
3989  if (unit == '\0')
3990  return 0;
3991 
3992  dterr = ParseISO8601Number(str, &str, &val, &fval);
3993  if (dterr)
3994  return dterr;
3995  if (!AdjustMicroseconds(val, fval, USECS_PER_MINUTE, itm_in))
3996  return DTERR_FIELD_OVERFLOW;
3997  if (*str == '\0')
3998  return 0;
3999  if (*str != ':')
4000  return DTERR_BAD_FORMAT;
4001  str++;
4002 
4003  dterr = ParseISO8601Number(str, &str, &val, &fval);
4004  if (dterr)
4005  return dterr;
4006  if (!AdjustMicroseconds(val, fval, USECS_PER_SEC, itm_in))
4007  return DTERR_FIELD_OVERFLOW;
4008  if (*str == '\0')
4009  return 0;
4010  return DTERR_BAD_FORMAT;
4011 
4012  default:
4013  /* not a valid time unit suffix */
4014  return DTERR_BAD_FORMAT;
4015  }
4016  }
4017 
4018  havefield = true;
4019  }
4020 
4021  return 0;
4022 }
static int ISO8601IntegerWidth(char *fieldstart)
Definition: datetime.c:3791
static int ParseISO8601Number(char *str, char **endptr, int64 *ipart, double *fpart)
Definition: datetime.c:3749

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

2718 {
2719  int val;
2720  char *cp;
2721  int dterr;
2722 
2723  *tmask = 0;
2724 
2725  errno = 0;
2726  val = strtoint(str, &cp, 10);
2727  if (errno == ERANGE)
2728  return DTERR_FIELD_OVERFLOW;
2729  if (cp == str)
2730  return DTERR_BAD_FORMAT;
2731 
2732  if (*cp == '.')
2733  {
2734  /*
2735  * More than two digits before decimal point? Then could be a date or
2736  * a run-together time: 2001.360 20011225 040506.789
2737  */
2738  if (cp - str > 2)
2739  {
2740  dterr = DecodeNumberField(flen, str,
2741  (fmask | DTK_DATE_M),
2742  tmask, tm,
2743  fsec, is2digits);
2744  if (dterr < 0)
2745  return dterr;
2746  return 0;
2747  }
2748 
2749  dterr = ParseFractionalSecond(cp, fsec);
2750  if (dterr)
2751  return dterr;
2752  }
2753  else if (*cp != '\0')
2754  return DTERR_BAD_FORMAT;
2755 
2756  /* Special case for day of year */
2757  if (flen == 3 && (fmask & DTK_DATE_M) == DTK_M(YEAR) && val >= 1 &&
2758  val <= 366)
2759  {
2760  *tmask = (DTK_M(DOY) | DTK_M(MONTH) | DTK_M(DAY));
2761  tm->tm_yday = val;
2762  /* tm_mon and tm_mday can't actually be set yet ... */
2763  return 0;
2764  }
2765 
2766  /* Switch based on what we have so far */
2767  switch (fmask & DTK_DATE_M)
2768  {
2769  case 0:
2770 
2771  /*
2772  * Nothing so far; make a decision about what we think the input
2773  * is. There used to be lots of heuristics here, but the
2774  * consensus now is to be paranoid. It *must* be either
2775  * YYYY-MM-DD (with a more-than-two-digit year field), or the
2776  * field order defined by DateOrder.
2777  */
2778  if (flen >= 3 || DateOrder == DATEORDER_YMD)
2779  {
2780  *tmask = DTK_M(YEAR);
2781  tm->tm_year = val;
2782  }
2783  else if (DateOrder == DATEORDER_DMY)
2784  {
2785  *tmask = DTK_M(DAY);
2786  tm->tm_mday = val;
2787  }
2788  else
2789  {
2790  *tmask = DTK_M(MONTH);
2791  tm->tm_mon = val;
2792  }
2793  break;
2794 
2795  case (DTK_M(YEAR)):
2796  /* Must be at second field of YY-MM-DD */
2797  *tmask = DTK_M(MONTH);
2798  tm->tm_mon = val;
2799  break;
2800 
2801  case (DTK_M(MONTH)):
2802  if (haveTextMonth)
2803  {
2804  /*
2805  * We are at the first numeric field of a date that included a
2806  * textual month name. We want to support the variants
2807  * MON-DD-YYYY, DD-MON-YYYY, and YYYY-MON-DD as unambiguous
2808  * inputs. We will also accept MON-DD-YY or DD-MON-YY in
2809  * either DMY or MDY modes, as well as YY-MON-DD in YMD mode.
2810  */
2811  if (flen >= 3 || DateOrder == DATEORDER_YMD)
2812  {
2813  *tmask = DTK_M(YEAR);
2814  tm->tm_year = val;
2815  }
2816  else
2817  {
2818  *tmask = DTK_M(DAY);
2819  tm->tm_mday = val;
2820  }
2821  }
2822  else
2823  {
2824  /* Must be at second field of MM-DD-YY */
2825  *tmask = DTK_M(DAY);
2826  tm->tm_mday = val;
2827  }
2828  break;
2829 
2830  case (DTK_M(YEAR) | DTK_M(MONTH)):
2831  if (haveTextMonth)
2832  {
2833  /* Need to accept DD-MON-YYYY even in YMD mode */
2834  if (flen >= 3 && *is2digits)
2835  {
2836  /* Guess that first numeric field is day was wrong */
2837  *tmask = DTK_M(DAY); /* YEAR is already set */
2838  tm->tm_mday = tm->tm_year;
2839  tm->tm_year = val;
2840  *is2digits = false;
2841  }
2842  else
2843  {
2844  *tmask = DTK_M(DAY);
2845  tm->tm_mday = val;
2846  }
2847  }
2848  else
2849  {
2850  /* Must be at third field of YY-MM-DD */
2851  *tmask = DTK_M(DAY);
2852  tm->tm_mday = val;
2853  }
2854  break;
2855 
2856  case (DTK_M(DAY)):
2857  /* Must be at second field of DD-MM-YY */
2858  *tmask = DTK_M(MONTH);
2859  tm->tm_mon = val;
2860  break;
2861 
2862  case (DTK_M(MONTH) | DTK_M(DAY)):
2863  /* Must be at third field of DD-MM-YY or MM-DD-YY */
2864  *tmask = DTK_M(YEAR);
2865  tm->tm_year = val;
2866  break;
2867 
2868  case (DTK_M(YEAR) | DTK_M(MONTH) | DTK_M(DAY)):
2869  /* we have all the date, so it must be a time field */
2870  dterr = DecodeNumberField(flen, str, fmask,
2871  tmask, tm,
2872  fsec, is2digits);
2873  if (dterr < 0)
2874  return dterr;
2875  return 0;
2876 
2877  default:
2878  /* Anything else is bogus input */
2879  return DTERR_BAD_FORMAT;
2880  }
2881 
2882  /*
2883  * When processing a year field, mark it for adjustment if it's only one
2884  * or two digits.
2885  */
2886  if (*tmask == DTK_M(YEAR))
2887  *is2digits = (flen <= 2);
2888 
2889  return 0;
2890 }
static int ParseFractionalSecond(char *cp, fsec_t *fsec)
Definition: datetime.c:709
int DateOrder
Definition: globals.c:123
#define DATEORDER_DMY
Definition: miscadmin.h:242
#define DATEORDER_YMD
Definition: miscadmin.h:241
int tm_yday
Definition: pgtime.h:43

References DateOrder, DATEORDER_DMY, DATEORDER_YMD, DAY, DecodeNumberField(), DOY, DTERR_BAD_FORMAT, DTERR_FIELD_OVERFLOW, DTK_DATE_M, DTK_M, MONTH, ParseFractionalSecond(), generate_unaccent_rules::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 2901 of file datetime.c.

2903 {
2904  char *cp;
2905 
2906  /*
2907  * Have a decimal point? Then this is a date or something with a seconds
2908  * field...
2909  */
2910  if ((cp = strchr(str, '.')) != NULL)
2911  {
2912  /*
2913  * Can we use ParseFractionalSecond here? Not clear whether trailing
2914  * junk should be rejected ...
2915  */
2916  if (cp[1] == '\0')
2917  {
2918  /* avoid assuming that strtod will accept "." */
2919  *fsec = 0;
2920  }
2921  else
2922  {
2923  double frac;
2924 
2925  errno = 0;
2926  frac = strtod(cp, NULL);
2927  if (errno != 0)
2928  return DTERR_BAD_FORMAT;
2929  *fsec = rint(frac * 1000000);
2930  }
2931  /* Now truncate off the fraction for further processing */
2932  *cp = '\0';
2933  len = strlen(str);
2934  }
2935  /* No decimal point and no complete date yet? */
2936  else if ((fmask & DTK_DATE_M) != DTK_DATE_M)
2937  {
2938  if (len >= 6)
2939  {
2940  *tmask = DTK_DATE_M;
2941 
2942  /*
2943  * Start from end and consider first 2 as Day, next 2 as Month,
2944  * and the rest as Year.
2945  */
2946  tm->tm_mday = atoi(str + (len - 2));
2947  *(str + (len - 2)) = '\0';
2948  tm->tm_mon = atoi(str + (len - 4));
2949  *(str + (len - 4)) = '\0';
2950  tm->tm_year = atoi(str);
2951  if ((len - 4) == 2)
2952  *is2digits = true;
2953 
2954  return DTK_DATE;
2955  }
2956  }
2957 
2958  /* not all time fields are specified? */
2959  if ((fmask & DTK_TIME_M) != DTK_TIME_M)
2960  {
2961  /* hhmmss */
2962  if (len == 6)
2963  {
2964  *tmask = DTK_TIME_M;
2965  tm->tm_sec = atoi(str + 4);
2966  *(str + 4) = '\0';
2967  tm->tm_min = atoi(str + 2);
2968  *(str + 2) = '\0';
2969  tm->tm_hour = atoi(str);
2970 
2971  return DTK_TIME;
2972  }
2973  /* hhmm? */
2974  else if (len == 4)
2975  {
2976  *tmask = DTK_TIME_M;
2977  tm->tm_sec = 0;
2978  tm->tm_min = atoi(str + 2);
2979  *(str + 2) = '\0';
2980  tm->tm_hour = atoi(str);
2981 
2982  return DTK_TIME;
2983  }
2984  }
2985 
2986  return DTERR_BAD_FORMAT;
2987 }

References DTERR_BAD_FORMAT, DTK_DATE, DTK_DATE_M, DTK_TIME, DTK_TIME_M, len, generate_unaccent_rules::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 3137 of file datetime.c.

3138 {
3139  int type;
3140  const datetkn *tp;
3141 
3142  tp = datecache[field];
3143  /* use strncmp so that we match truncated tokens */
3144  if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3145  {
3146  tp = datebsearch(lowtoken, datetktbl, szdatetktbl);
3147  }
3148  if (tp == NULL)
3149  {
3150  type = UNKNOWN_FIELD;
3151  *val = 0;
3152  }
3153  else
3154  {
3155  datecache[field] = tp;
3156  type = tp->type;
3157  *val = tp->value;
3158  }
3159 
3160  return type;
3161 }
static const datetkn * datecache[MAXDATEFIELDS]
Definition: datetime.c:258
static const datetkn * datebsearch(const char *key, const datetkn *base, int nel)
Definition: datetime.c:4142

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

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

◆ DecodeTime()

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

Definition at line 2661 of file datetime.c.

2663 {
2664  struct pg_itm itm;
2665  int dterr;
2666 
2667  dterr = DecodeTimeCommon(str, fmask, range,
2668  tmask, &itm);
2669  if (dterr)
2670  return dterr;
2671 
2672  if (itm.tm_hour > INT_MAX)
2673  return DTERR_FIELD_OVERFLOW;
2674  tm->tm_hour = (int) itm.tm_hour;
2675  tm->tm_min = itm.tm_min;
2676  tm->tm_sec = itm.tm_sec;
2677  *fsec = itm.tm_usec;
2678 
2679  return 0;
2680 }
static int DecodeTimeCommon(char *str, int fmask, int range, int *tmask, struct pg_itm *itm)
Definition: datetime.c:2579

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

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

◆ DecodeTimeCommon()

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

Definition at line 2579 of file datetime.c.

2581 {
2582  char *cp;
2583  int dterr;
2584  fsec_t fsec = 0;
2585 
2586  *tmask = DTK_TIME_M;
2587 
2588  errno = 0;
2589  itm->tm_hour = strtoi64(str, &cp, 10);
2590  if (errno == ERANGE)
2591  return DTERR_FIELD_OVERFLOW;
2592  if (*cp != ':')
2593  return DTERR_BAD_FORMAT;
2594  errno = 0;
2595  itm->tm_min = strtoint(cp + 1, &cp, 10);
2596  if (errno == ERANGE)
2597  return DTERR_FIELD_OVERFLOW;
2598  if (*cp == '\0')
2599  {
2600  itm->tm_sec = 0;
2601  /* If it's a MINUTE TO SECOND interval, take 2 fields as being mm:ss */
2603  {
2604  if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2605  return DTERR_FIELD_OVERFLOW;
2606  itm->tm_sec = itm->tm_min;
2607  itm->tm_min = (int) itm->tm_hour;
2608  itm->tm_hour = 0;
2609  }
2610  }
2611  else if (*cp == '.')
2612  {
2613  /* always assume mm:ss.sss is MINUTE TO SECOND */
2614  dterr = ParseFractionalSecond(cp, &fsec);
2615  if (dterr)
2616  return dterr;
2617  if (itm->tm_hour > INT_MAX || itm->tm_hour < INT_MIN)
2618  return DTERR_FIELD_OVERFLOW;
2619  itm->tm_sec = itm->tm_min;
2620  itm->tm_min = (int) itm->tm_hour;
2621  itm->tm_hour = 0;
2622  }
2623  else if (*cp == ':')
2624  {
2625  errno = 0;
2626  itm->tm_sec = strtoint(cp + 1, &cp, 10);
2627  if (errno == ERANGE)
2628  return DTERR_FIELD_OVERFLOW;
2629  if (*cp == '.')
2630  {
2631  dterr = ParseFractionalSecond(cp, &fsec);
2632  if (dterr)
2633  return dterr;
2634  }
2635  else if (*cp != '\0')
2636  return DTERR_BAD_FORMAT;
2637  }
2638  else
2639  return DTERR_BAD_FORMAT;
2640 
2641  /* do a sanity check; but caller must check the range of tm_hour */
2642  if (itm->tm_hour < 0 ||
2643  itm->tm_min < 0 || itm->tm_min > MINS_PER_HOUR - 1 ||
2644  itm->tm_sec < 0 || itm->tm_sec > SECS_PER_MINUTE ||
2645  fsec < 0 || fsec > USECS_PER_SEC)
2646  return DTERR_FIELD_OVERFLOW;
2647 
2648  itm->tm_usec = (int) fsec;
2649 
2650  return 0;
2651 }
#define MINS_PER_HOUR
Definition: timestamp.h:129
#define SECS_PER_MINUTE
Definition: timestamp.h:128
int64 tm_hour
Definition: timestamp.h:70
int tm_sec
Definition: timestamp.h:68
int tm_min
Definition: timestamp.h:69
int tm_usec
Definition: timestamp.h:67

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

Referenced by DecodeTime(), and DecodeTimeForInterval().

◆ DecodeTimeForInterval()

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

Definition at line 2690 of file datetime.c.

2692 {
2693  struct pg_itm itm;
2694  int dterr;
2695 
2696  dterr = DecodeTimeCommon(str, fmask, range,
2697  tmask, &itm);
2698  if (dterr)
2699  return dterr;
2700 
2701  itm_in->tm_usec = itm.tm_usec;
2702  if (!int64_multiply_add(itm.tm_hour, USECS_PER_HOUR, &itm_in->tm_usec) ||
2703  !int64_multiply_add(itm.tm_min, USECS_PER_MINUTE, &itm_in->tm_usec) ||
2704  !int64_multiply_add(itm.tm_sec, USECS_PER_SEC, &itm_in->tm_usec))
2705  return DTERR_FIELD_OVERFLOW;
2706 
2707  return 0;
2708 }

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

Referenced by DecodeInterval().

◆ DecodeTimeOnly()

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

Definition at line 1864 of file datetime.c.

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

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

Referenced by time_in(), and timetz_in().

◆ DecodeTimezone()

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

Definition at line 2996 of file datetime.c.

2997 {
2998  int tz;
2999  int hr,
3000  min,
3001  sec = 0;
3002  char *cp;
3003 
3004  /* leading character must be "+" or "-" */
3005  if (*str != '+' && *str != '-')
3006  return DTERR_BAD_FORMAT;
3007 
3008  errno = 0;
3009  hr = strtoint(str + 1, &cp, 10);
3010  if (errno == ERANGE)
3011  return DTERR_TZDISP_OVERFLOW;
3012 
3013  /* explicit delimiter? */
3014  if (*cp == ':')
3015  {
3016  errno = 0;
3017  min = strtoint(cp + 1, &cp, 10);
3018  if (errno == ERANGE)
3019  return DTERR_TZDISP_OVERFLOW;
3020  if (*cp == ':')
3021  {
3022  errno = 0;
3023  sec = strtoint(cp + 1, &cp, 10);
3024  if (errno == ERANGE)
3025  return DTERR_TZDISP_OVERFLOW;
3026  }
3027  }
3028  /* otherwise, might have run things together... */
3029  else if (*cp == '\0' && strlen(str) > 3)
3030  {
3031  min = hr % 100;
3032  hr = hr / 100;
3033  /* we could, but don't, support a run-together hhmmss format */
3034  }
3035  else
3036  min = 0;
3037 
3038  /* Range-check the values; see notes in datatype/timestamp.h */
3039  if (hr < 0 || hr > MAX_TZDISP_HOUR)
3040  return DTERR_TZDISP_OVERFLOW;
3041  if (min < 0 || min >= MINS_PER_HOUR)
3042  return DTERR_TZDISP_OVERFLOW;
3043  if (sec < 0 || sec >= SECS_PER_MINUTE)
3044  return DTERR_TZDISP_OVERFLOW;
3045 
3046  tz = (hr * MINS_PER_HOUR + min) * SECS_PER_MINUTE + sec;
3047  if (*str == '-')
3048  tz = -tz;
3049 
3050  *tzp = -tz;
3051 
3052  if (*cp != '\0')
3053  return DTERR_BAD_FORMAT;
3054 
3055  return 0;
3056 }
#define MAX_TZDISP_HOUR
Definition: timestamp.h:143

References DTERR_BAD_FORMAT, DTERR_TZDISP_OVERFLOW, MAX_TZDISP_HOUR, MINS_PER_HOUR, SECS_PER_MINUTE, generate_unaccent_rules::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 3080 of file datetime.c.

3083 {
3084  const datetkn *tp;
3085 
3086  tp = abbrevcache[field];
3087  /* use strncmp so that we match truncated tokens */
3088  if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
3089  {
3090  if (zoneabbrevtbl)
3091  tp = datebsearch(lowtoken, zoneabbrevtbl->abbrevs,
3093  else
3094  tp = NULL;
3095  }
3096  if (tp == NULL)
3097  {
3098  *ftype = UNKNOWN_FIELD;
3099  *offset = 0;
3100  *tz = NULL;
3101  }
3102  else
3103  {
3104  abbrevcache[field] = tp;
3105  *ftype = tp->type;
3106  if (tp->type == DYNTZ)
3107  {
3108  *offset = 0;
3109  *tz = FetchDynamicTimeZone(zoneabbrevtbl, tp, extra);
3110  if (*tz == NULL)
3111  return DTERR_BAD_ZONE_ABBREV;
3112  }
3113  else
3114  {
3115  *offset = tp->value;
3116  *tz = NULL;
3117  }
3118  }
3119 
3120  return 0;
3121 }
static const datetkn * abbrevcache[MAXDATEFIELDS]
Definition: datetime.c:262
static TimeZoneAbbrevTable * zoneabbrevtbl
Definition: datetime.c:254
static pg_tz * FetchDynamicTimeZone(TimeZoneAbbrevTable *tbl, const datetkn *tp, DateTimeErrorExtra *extra)
Definition: datetime.c:4959

References abbrevcache, TimeZoneAbbrevTable::abbrevs, datebsearch(), DTERR_BAD_ZONE_ABBREV, DYNTZ, FetchDynamicTimeZone(), TimeZoneAbbrevTable::numabbrevs, datetkn::token, TOKMAXLEN, datetkn::type, 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 3262 of file datetime.c.

3263 {
3264  char lowtoken[TOKMAXLEN + 1];
3265  int len;
3266 
3267  *offset = 0; /* avoid uninitialized vars on failure */
3268  *tz = NULL;
3269 
3270  if (!zoneabbrevtbl)
3271  return -1; /* no abbrevs known, so fail immediately */
3272 
3273  /* Downcase as much of the string as we could need */
3274  for (len = 0; len < TOKMAXLEN; len++)
3275  {
3276  if (*str == '\0' || !isalpha((unsigned char) *str))
3277  break;
3278  lowtoken[len] = pg_tolower((unsigned char) *str++);
3279  }
3280  lowtoken[len] = '\0';
3281 
3282  /*
3283  * We could avoid doing repeated binary searches if we cared to duplicate
3284  * datebsearch here, but it's not clear that such an optimization would be
3285  * worth the trouble. In common cases there's probably not anything after
3286  * the zone abbrev anyway. So just search with successively truncated
3287  * strings.
3288  */
3289  while (len > 0)
3290  {
3291  const datetkn *tp = datebsearch(lowtoken, zoneabbrevtbl->abbrevs,
3293 
3294  if (tp != NULL)
3295  {
3296  if (tp->type == DYNTZ)
3297  {
3298  DateTimeErrorExtra extra;
3300  &extra);
3301 
3302  if (tzp != NULL)
3303  {
3304  /* Caller must resolve the abbrev's current meaning */
3305  *tz = tzp;
3306  return len;
3307  }
3308  }
3309  else
3310  {
3311  /* Fixed-offset zone abbrev, so it's easy */
3312  *offset = tp->value;
3313  return len;
3314  }
3315  }
3316  lowtoken[--len] = '\0';
3317  }
3318 
3319  /* Did not find a match */
3320  return -1;
3321 }
unsigned char pg_tolower(unsigned char ch)
Definition: pgstrcasecmp.c:122

References TimeZoneAbbrevTable::abbrevs, datebsearch(), DYNTZ, FetchDynamicTimeZone(), len, TimeZoneAbbrevTable::numabbrevs, pg_tolower(), generate_unaccent_rules::str, 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 3179 of file datetime.c.

3180 {
3181  char *lowzone;
3182  int dterr,
3183  type;
3184  DateTimeErrorExtra extra;
3185 
3186  /*
3187  * First we look in the timezone abbreviation table (to handle cases like
3188  * "EST"), and if that fails, we look in the timezone database (to handle
3189  * cases like "America/New_York"). This matches the order in which
3190  * timestamp input checks the cases; it's important because the timezone
3191  * database unwisely uses a few zone names that are identical to offset
3192  * abbreviations.
3193  */
3194 
3195  /* DecodeTimezoneAbbrev requires lowercase input */
3196  lowzone = downcase_truncate_identifier(tzname,
3197  strlen(tzname),
3198  false);
3199 
3200  dterr = DecodeTimezoneAbbrev(0, lowzone, &type, offset, tz, &extra);
3201  if (dterr)
3202  DateTimeParseError(dterr, &extra, NULL, NULL, NULL);
3203 
3204  if (type == TZ || type == DTZ)
3205  {
3206  /* fixed-offset abbreviation, return the offset */
3207  return TZNAME_FIXED_OFFSET;
3208  }
3209  else if (type == DYNTZ)
3210  {
3211  /* dynamic-offset abbreviation, return its referenced timezone */
3212  return TZNAME_DYNTZ;
3213  }
3214  else
3215  {
3216  /* try it as a full zone name */
3217  *tz = pg_tzset(tzname);
3218  if (*tz == NULL)
3219  ereport(ERROR,
3220  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3221  errmsg("time zone \"%s\" not recognized", tzname)));
3222  return TZNAME_ZONE;
3223  }
3224 }
void DateTimeParseError(int dterr, DateTimeErrorExtra *extra, const char *str, const char *datatype, Node *escontext)
Definition: datetime.c:4081
#define ereport(elevel,...)
Definition: elog.h:149
#define TZNAME_ZONE
Definition: datetime.h:301
#define TZNAME_FIXED_OFFSET
Definition: datetime.h:299
#define TZNAME_DYNTZ
Definition: datetime.h:300
char * downcase_truncate_identifier(const char *ident, int len, bool warn)
Definition: scansup.c:37

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

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

◆ DecodeTimezoneNameToTz()

pg_tz* DecodeTimezoneNameToTz ( const char *  tzname)

Definition at line 3234 of file datetime.c.

3235 {
3236  pg_tz *result;
3237  int offset;
3238 
3239  if (DecodeTimezoneName(tzname, &offset, &result) == TZNAME_FIXED_OFFSET)
3240  {
3241  /* fixed-offset abbreviation, get a pg_tz descriptor for that */
3242  result = pg_tzset_offset(-offset); /* flip to POSIX sign convention */
3243  }
3244  return result;
3245 }
int DecodeTimezoneName(const char *tzname, int *offset, pg_tz **tz)
Definition: datetime.c:3179
pg_tz * pg_tzset_offset(long gmtoffset)
Definition: pgtz.c:320

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

Referenced by lookup_timezone().

◆ DecodeUnits()

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

Definition at line 4036 of file datetime.c.

4037 {
4038  int type;
4039  const datetkn *tp;
4040 
4041  tp = deltacache[field];
4042  /* use strncmp so that we match truncated tokens */
4043  if (tp == NULL || strncmp(lowtoken, tp->token, TOKMAXLEN) != 0)
4044  {
4045  tp = datebsearch(lowtoken, deltatktbl, szdeltatktbl);
4046  }
4047  if (tp == NULL)
4048  {
4049  type = UNKNOWN_FIELD;
4050  *val = 0;
4051  }
4052  else
4053  {
4054  deltacache[field] = tp;
4055  type = tp->type;
4056  *val = tp->value;
4057  }
4058 
4059  return type;
4060 } /* DecodeUnits() */
static const datetkn * deltacache[MAXDATEFIELDS]
Definition: datetime.c:260

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

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

◆ DetermineTimeZoneAbbrevOffset()

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

Definition at line 1746 of file datetime.c.

1747 {
1748  pg_time_t t;
1749  int zone_offset;
1750  int abbr_offset;
1751  int abbr_isdst;
1752 
1753  /*
1754  * Compute the UTC time we want to probe at. (In event of overflow, we'll
1755  * probe at the epoch, which is a bit random but probably doesn't matter.)
1756  */
1757  zone_offset = DetermineTimeZoneOffsetInternal(tm, tzp, &t);
1758 
1759  /*
1760  * Try to match the abbreviation to something in the zone definition.
1761  */
1762  if (DetermineTimeZoneAbbrevOffsetInternal(t, abbr, tzp,
1763  &abbr_offset, &abbr_isdst))
1764  {
1765  /* Success, so use the abbrev-specific answers. */
1766  tm->tm_isdst = abbr_isdst;
1767  return abbr_offset;
1768  }
1769 
1770  /*
1771  * No match, so use the answers we already got from
1772  * DetermineTimeZoneOffsetInternal.
1773  */
1774  return zone_offset;
1775 }
static int DetermineTimeZoneOffsetInternal(struct pg_tm *tm, pg_tz *tzp, pg_time_t *tp)
Definition: datetime.c:1607
static bool DetermineTimeZoneAbbrevOffsetInternal(pg_time_t t, const char *abbr, pg_tz *tzp, int *offset, int *isdst)
Definition: datetime.c:1821
int64 pg_time_t
Definition: pgtime.h:23

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

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

◆ DetermineTimeZoneAbbrevOffsetInternal()

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

Definition at line 1821 of file datetime.c.

1823 {
1824  char upabbr[TZ_STRLEN_MAX + 1];
1825  unsigned char *p;
1826  long int gmtoff;
1827 
1828  /* We need to force the abbrev to upper case */
1829  strlcpy(upabbr, abbr, sizeof(upabbr));
1830  for (p = (unsigned char *) upabbr; *p; p++)
1831  *p = pg_toupper(*p);
1832 
1833  /* Look up the abbrev's meaning at this time in this zone */
1834  if (pg_interpret_timezone_abbrev(upabbr,
1835  &t,
1836  &gmtoff,
1837  isdst,
1838  tzp))
1839  {
1840  /* Change sign to agree with DetermineTimeZoneOffset() */
1841  *offset = (int) -gmtoff;
1842  return true;
1843  }
1844  return false;
1845 }
#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:1757
unsigned char pg_toupper(unsigned char ch)
Definition: pgstrcasecmp.c:105

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

Referenced by DetermineTimeZoneAbbrevOffset(), and DetermineTimeZoneAbbrevOffsetTS().

◆ DetermineTimeZoneAbbrevOffsetTS()

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

Definition at line 1784 of file datetime.c.

1786 {
1788  int zone_offset;
1789  int abbr_offset;
1790  int tz;
1791  struct pg_tm tm;
1792  fsec_t fsec;
1793 
1794  /*
1795  * If the abbrev matches anything in the zone data, this is pretty easy.
1796  */
1797  if (DetermineTimeZoneAbbrevOffsetInternal(t, abbr, tzp,
1798  &abbr_offset, isdst))
1799  return abbr_offset;
1800 
1801  /*
1802  * Else, break down the timestamp so we can use DetermineTimeZoneOffset.
1803  */
1804  if (timestamp2tm(ts, &tz, &tm, &fsec, NULL, tzp) != 0)
1805  ereport(ERROR,
1806  (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1807  errmsg("timestamp out of range")));
1808 
1809  zone_offset = DetermineTimeZoneOffset(&tm, tzp);
1810  *isdst = tm.tm_isdst;
1811  return zone_offset;
1812 }
int timestamp2tm(Timestamp dt, int *tzp, struct pg_tm *tm, fsec_t *fsec, const char **tzn, pg_tz *attimezone)
Definition: timestamp.c:1901
pg_time_t timestamptz_to_time_t(TimestampTz t)
Definition: timestamp.c:1833

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

Referenced by pg_timezone_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 1607 of file datetime.c.

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

References date2j(), IS_VALID_JULIAN, MINS_PER_HOUR, pg_next_dst_boundary(), res, 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 4216 of file datetime.c.

4217 {
4218  Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4219 
4220  switch (style)
4221  {
4222  case USE_ISO_DATES:
4223  case USE_XSD_DATES:
4224  /* compatible with ISO date formats */
4226  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4227  *str++ = '-';
4229  *str++ = '-';
4231  break;
4232 
4233  case USE_SQL_DATES:
4234  /* compatible with Oracle/Ingres date formats */
4235  if (DateOrder == DATEORDER_DMY)
4236  {
4238  *str++ = '/';
4240  }
4241  else
4242  {
4244  *str++ = '/';
4246  }
4247  *str++ = '/';
4249  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4250  break;
4251 
4252  case USE_GERMAN_DATES:
4253  /* German-style date format */
4255  *str++ = '.';
4257  *str++ = '.';
4259  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4260  break;
4261 
4262  case USE_POSTGRES_DATES:
4263  default:
4264  /* traditional date-only style for Postgres */
4265  if (DateOrder == DATEORDER_DMY)
4266  {
4268  *str++ = '-';
4270  }
4271  else
4272  {
4274  *str++ = '-';
4276  }
4277  *str++ = '-';
4279  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4280  break;
4281  }
4282 
4283  if (tm->tm_year <= 0)
4284  {
4285  memcpy(str, " BC", 3); /* Don't copy NUL */
4286  str += 3;
4287  }
4288  *str = '\0';
4289 }
#define USE_SQL_DATES
Definition: miscadmin.h:236
#define USE_POSTGRES_DATES
Definition: miscadmin.h:234
#define USE_ISO_DATES
Definition: miscadmin.h:235
#define USE_XSD_DATES
Definition: miscadmin.h:238
#define USE_GERMAN_DATES
Definition: miscadmin.h:237

References Assert(), DateOrder, DATEORDER_DMY, MONTHS_PER_YEAR, pg_ultostr_zeropad(), generate_unaccent_rules::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 4331 of file datetime.c.

4332 {
4333  int day;
4334 
4335  Assert(tm->tm_mon >= 1 && tm->tm_mon <= MONTHS_PER_YEAR);
4336 
4337  /*
4338  * Negative tm_isdst means we have no valid time zone translation.
4339  */
4340  if (tm->tm_isdst < 0)
4341  print_tz = false;
4342 
4343  switch (style)
4344  {
4345  case USE_ISO_DATES:
4346  case USE_XSD_DATES:
4347  /* Compatible with ISO-8601 date formats */
4349  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4350  *str++ = '-';
4352  *str++ = '-';
4354  *str++ = (style == USE_ISO_DATES) ? ' ' : 'T';
4356  *str++ = ':';
4358  *str++ = ':';
4359  str = AppendTimestampSeconds(str, tm, fsec);
4360  if (print_tz)
4361  str = EncodeTimezone(str, tz, style);
4362  break;
4363 
4364  case USE_SQL_DATES:
4365  /* Compatible with Oracle/Ingres date formats */
4366  if (DateOrder == DATEORDER_DMY)
4367  {
4369  *str++ = '/';
4371  }
4372  else
4373  {
4375  *str++ = '/';
4377  }
4378  *str++ = '/';
4380  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4381  *str++ = ' ';
4383  *str++ = ':';
4385  *str++ = ':';
4386  str = AppendTimestampSeconds(str, tm, fsec);
4387 
4388  /*
4389  * Note: the uses of %.*s in this function would be risky if the
4390  * timezone names ever contain non-ASCII characters, since we are
4391  * not being careful to do encoding-aware clipping. However, all
4392  * TZ abbreviations in the IANA database are plain ASCII.
4393  */
4394  if (print_tz)
4395  {
4396  if (tzn)
4397  {
4398  sprintf(str, " %.*s", MAXTZLEN, tzn);
4399  str += strlen(str);
4400  }
4401  else
4402  str = EncodeTimezone(str, tz, style);
4403  }
4404  break;
4405 
4406  case USE_GERMAN_DATES:
4407  /* German variant on European style */
4409  *str++ = '.';
4411  *str++ = '.';
4413  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4414  *str++ = ' ';
4416  *str++ = ':';
4418  *str++ = ':';
4419  str = AppendTimestampSeconds(str, tm, fsec);
4420 
4421  if (print_tz)
4422  {
4423  if (tzn)
4424  {
4425  sprintf(str, " %.*s", MAXTZLEN, tzn);
4426  str += strlen(str);
4427  }
4428  else
4429  str = EncodeTimezone(str, tz, style);
4430  }
4431  break;
4432 
4433  case USE_POSTGRES_DATES:
4434  default:
4435  /* Backward-compatible with traditional Postgres abstime dates */
4436  day = date2j(tm->tm_year, tm->tm_mon, tm->tm_mday);
4437  tm->tm_wday = j2day(day);
4438  memcpy(str, days[tm->tm_wday], 3);
4439  str += 3;
4440  *str++ = ' ';
4441  if (DateOrder == DATEORDER_DMY)
4442  {
4444  *str++ = ' ';
4445  memcpy(str, months[tm->tm_mon - 1], 3);
4446  str += 3;
4447  }
4448  else
4449  {
4450  memcpy(str, months[tm->tm_mon - 1], 3);
4451  str += 3;
4452  *str++ = ' ';
4454  }
4455  *str++ = ' ';
4457  *str++ = ':';
4459  *str++ = ':';
4460  str = AppendTimestampSeconds(str, tm, fsec);
4461  *str++ = ' ';
4463  (tm->tm_year > 0) ? tm->tm_year : -(tm->tm_year - 1), 4);
4464 
4465  if (print_tz)
4466  {
4467  if (tzn)
4468  {
4469  sprintf(str, " %.*s", MAXTZLEN, tzn);
4470  str += strlen(str);
4471  }
4472  else
4473  {
4474  /*
4475  * We have a time zone, but no string version. Use the
4476  * numeric form, but be sure to include a leading space to
4477  * avoid formatting something which would be rejected by
4478  * the date/time parser later. - thomas 2001-10-19
4479  */
4480  *str++ = ' ';
4481  str = EncodeTimezone(str, tz, style);
4482  }
4483  }
4484  break;
4485  }
4486 
4487  if (tm->tm_year <= 0)
4488  {
4489  memcpy(str, " BC", 3); /* Don't copy NUL */
4490  str += 3;
4491  }
4492  *str = '\0';
4493 }
static char * EncodeTimezone(char *str, int tz, int style)
Definition: datetime.c:4178
int j2day(int date)
Definition: datetime.c:344
const char *const months[]
Definition: datetime.c:81
static char * AppendTimestampSeconds(char *cp, struct pg_tm *tm, fsec_t fsec)
Definition: datetime.c:511
#define MAXTZLEN
Definition: miscadmin.h:262

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

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

◆ EncodeInterval()

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

Definition at line 4574 of file datetime.c.

4575 {
4576  char *cp = str;
4577  int year = itm->tm_year;
4578  int mon = itm->tm_mon;
4579  int64 mday = itm->tm_mday; /* tm_mday could be INT_MIN */
4580  int64 hour = itm->tm_hour;
4581  int min = itm->tm_min;
4582  int sec = itm->tm_sec;
4583  int fsec = itm->tm_usec;
4584  bool is_before = false;
4585  bool is_zero = true;
4586 
4587  /*
4588  * The sign of year and month are guaranteed to match, since they are
4589  * stored internally as "month". But we'll need to check for is_before and
4590  * is_zero when determining the signs of day and hour/minute/seconds
4591  * fields.
4592  */
4593  switch (style)
4594  {
4595  /* SQL Standard interval format */
4596  case INTSTYLE_SQL_STANDARD:
4597  {
4598  bool has_negative = year < 0 || mon < 0 ||
4599  mday < 0 || hour < 0 ||
4600  min < 0 || sec < 0 || fsec < 0;
4601  bool has_positive = year > 0 || mon > 0 ||
4602  mday > 0 || hour > 0 ||
4603  min > 0 || sec > 0 || fsec > 0;
4604  bool has_year_month = year != 0 || mon != 0;
4605  bool has_day_time = mday != 0 || hour != 0 ||
4606  min != 0 || sec != 0 || fsec != 0;
4607  bool has_day = mday != 0;
4608  bool sql_standard_value = !(has_negative && has_positive) &&
4609  !(has_year_month && has_day_time);
4610 
4611  /*
4612  * SQL Standard wants only 1 "<sign>" preceding the whole
4613  * interval ... but can't do that if mixed signs.
4614  */
4615  if (has_negative && sql_standard_value)
4616  {
4617  *cp++ = '-';
4618  year = -year;
4619  mon = -mon;
4620  mday = -mday;
4621  hour = -hour;
4622  min = -min;
4623  sec = -sec;
4624  fsec = -fsec;
4625  }
4626 
4627  if (!has_negative && !has_positive)
4628  {
4629  sprintf(cp, "0");
4630  }
4631  else if (!sql_standard_value)
4632  {
4633  /*
4634  * For non sql-standard interval values, force outputting
4635  * the signs to avoid ambiguities with intervals with
4636  * mixed sign components.
4637  */
4638  char year_sign = (year < 0 || mon < 0) ? '-' : '+';
4639  char day_sign = (mday < 0) ? '-' : '+';
4640  char sec_sign = (hour < 0 || min < 0 ||
4641  sec < 0 || fsec < 0) ? '-' : '+';
4642 
4643  sprintf(cp, "%c%d-%d %c%lld %c%lld:%02d:",
4644  year_sign, abs(year), abs(mon),
4645  day_sign, (long long) i64abs(mday),
4646  sec_sign, (long long) i64abs(hour), abs(min));
4647  cp += strlen(cp);
4648  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4649  *cp = '\0';
4650  }
4651  else if (has_year_month)
4652  {
4653  sprintf(cp, "%d-%d", year, mon);
4654  }
4655  else if (has_day)
4656  {
4657  sprintf(cp, "%lld %lld:%02d:",
4658  (long long) mday, (long long) hour, min);
4659  cp += strlen(cp);
4660  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4661  *cp = '\0';
4662  }
4663  else
4664  {
4665  sprintf(cp, "%lld:%02d:", (long long) hour, min);
4666  cp += strlen(cp);
4667  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4668  *cp = '\0';
4669  }
4670  }
4671  break;
4672 
4673  /* ISO 8601 "time-intervals by duration only" */
4674  case INTSTYLE_ISO_8601:
4675  /* special-case zero to avoid printing nothing */
4676  if (year == 0 && mon == 0 && mday == 0 &&
4677  hour == 0 && min == 0 && sec == 0 && fsec == 0)
4678  {
4679  sprintf(cp, "PT0S");
4680  break;
4681  }
4682  *cp++ = 'P';
4683  cp = AddISO8601IntPart(cp, year, 'Y');
4684  cp = AddISO8601IntPart(cp, mon, 'M');
4685  cp = AddISO8601IntPart(cp, mday, 'D');
4686  if (hour != 0 || min != 0 || sec != 0 || fsec != 0)
4687  *cp++ = 'T';
4688  cp = AddISO8601IntPart(cp, hour, 'H');
4689  cp = AddISO8601IntPart(cp, min, 'M');
4690  if (sec != 0 || fsec != 0)
4691  {
4692  if (sec < 0 || fsec < 0)
4693  *cp++ = '-';
4694  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4695  *cp++ = 'S';
4696  *cp++ = '\0';
4697  }
4698  break;
4699 
4700  /* Compatible with postgresql < 8.4 when DateStyle = 'iso' */
4701  case INTSTYLE_POSTGRES:
4702  cp = AddPostgresIntPart(cp, year, "year", &is_zero, &is_before);
4703 
4704  /*
4705  * Ideally we should spell out "month" like we do for "year" and
4706  * "day". However, for backward compatibility, we can't easily
4707  * fix this. bjm 2011-05-24
4708  */
4709  cp = AddPostgresIntPart(cp, mon, "mon", &is_zero, &is_before);
4710  cp = AddPostgresIntPart(cp, mday, "day", &is_zero, &is_before);
4711  if (is_zero || hour != 0 || min != 0 || sec != 0 || fsec != 0)
4712  {
4713  bool minus = (hour < 0 || min < 0 || sec < 0 || fsec < 0);
4714 
4715  sprintf(cp, "%s%s%02lld:%02d:",
4716  is_zero ? "" : " ",
4717  (minus ? "-" : (is_before ? "+" : "")),
4718  (long long) i64abs(hour), abs(min));
4719  cp += strlen(cp);
4720  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, true);
4721  *cp = '\0';
4722  }
4723  break;
4724 
4725  /* Compatible with postgresql < 8.4 when DateStyle != 'iso' */
4727  default:
4728  strcpy(cp, "@");
4729  cp++;
4730  cp = AddVerboseIntPart(cp, year, "year", &is_zero, &is_before);
4731  cp = AddVerboseIntPart(cp, mon, "mon", &is_zero, &is_before);
4732  cp = AddVerboseIntPart(cp, mday, "day", &is_zero, &is_before);
4733  cp = AddVerboseIntPart(cp, hour, "hour", &is_zero, &is_before);
4734  cp = AddVerboseIntPart(cp, min, "min", &is_zero, &is_before);
4735  if (sec != 0 || fsec != 0)
4736  {
4737  *cp++ = ' ';
4738  if (sec < 0 || (sec == 0 && fsec < 0))
4739  {
4740  if (is_zero)
4741  is_before = true;
4742  else if (!is_before)
4743  *cp++ = '-';
4744  }
4745  else if (is_before)
4746  *cp++ = '-';
4747  cp = AppendSeconds(cp, sec, fsec, MAX_INTERVAL_PRECISION, false);
4748  /* We output "ago", not negatives, so use abs(). */
4749  sprintf(cp, " sec%s",
4750  (abs(sec) != 1 || fsec != 0) ? "s" : "");
4751  is_zero = false;
4752  }
4753  /* identically zero? then put in a unitless zero... */
4754  if (is_zero)
4755  strcat(cp, " 0");
4756  if (is_before)
4757  strcat(cp, " ago");
4758  break;
4759  }
4760 }
static char * AddVerboseIntPart(char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
Definition: datetime.c:4535
static char * AddPostgresIntPart(char *cp, int64 value, const char *units, bool *is_zero, bool *is_before)
Definition: datetime.c:4512
static char * AddISO8601IntPart(char *cp, int64 value, char units)
Definition: datetime.c:4502
#define MAX_INTERVAL_PRECISION
Definition: timestamp.h:93
#define INTSTYLE_POSTGRES_VERBOSE
Definition: miscadmin.h:256
#define INTSTYLE_ISO_8601
Definition: miscadmin.h:258
#define INTSTYLE_POSTGRES
Definition: miscadmin.h:255
int tm_year
Definition: timestamp.h:73
int tm_mon
Definition: timestamp.h:72
int tm_mday
Definition: timestamp.h:71

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

Referenced by interval_out().

◆ EncodeTimeOnly()

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

Definition at line 4301 of file datetime.c.

4302 {
4304  *str++ = ':';
4306  *str++ = ':';
4307  str = AppendSeconds(str, tm->tm_sec, fsec, MAX_TIME_PRECISION, true);
4308  if (print_tz)
4309  str = EncodeTimezone(str, tz, style);
4310  *str = '\0';
4311 }
#define MAX_TIME_PRECISION
Definition: date.h:45

References AppendSeconds(), EncodeTimezone(), MAX_TIME_PRECISION, pg_ultostr_zeropad(), generate_unaccent_rules::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 4178 of file datetime.c.

4179 {
4180  int hour,
4181  min,
4182  sec;
4183 
4184  sec = abs(tz);
4185  min = sec / SECS_PER_MINUTE;
4186  sec -= min * SECS_PER_MINUTE;
4187  hour = min / MINS_PER_HOUR;
4188  min -= hour * MINS_PER_HOUR;
4189 
4190  /* TZ is negated compared to sign we wish to display ... */
4191  *str++ = (tz <= 0 ? '+' : '-');
4192 
4193  if (sec != 0)
4194  {
4195  str = pg_ultostr_zeropad(str, hour, 2);
4196  *str++ = ':';
4197  str = pg_ultostr_zeropad(str, min, 2);
4198  *str++ = ':';
4199  str = pg_ultostr_zeropad(str, sec, 2);
4200  }
4201  else if (min != 0 || style == USE_XSD_DATES)
4202  {
4203  str = pg_ultostr_zeropad(str, hour, 2);
4204  *str++ = ':';
4205  str = pg_ultostr_zeropad(str, min, 2);
4206  }
4207  else
4208  str = pg_ultostr_zeropad(str, hour, 2);
4209  return str;
4210 }

References MINS_PER_HOUR, pg_ultostr_zeropad(), SECS_PER_MINUTE, generate_unaccent_rules::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 4959 of file datetime.c.

4961 {
4962  DynamicZoneAbbrev *dtza;
4963 
4964  /* Just some sanity checks to prevent indexing off into nowhere */
4965  Assert(tp->type == DYNTZ);
4966  Assert(tp->value > 0 && tp->value < tbl->tblsize);
4967 
4968  dtza = (DynamicZoneAbbrev *) ((char *) tbl + tp->value);
4969 
4970  /* Look up the underlying zone if we haven't already */
4971  if (dtza->tz == NULL)
4972  {
4973  dtza->tz = pg_tzset(dtza->zone);
4974  if (dtza->tz == NULL)
4975  {
4976  /* Ooops, bogus zone name in config file entry */
4977  extra->dtee_timezone = dtza->zone;
4978  extra->dtee_abbrev = tp->token;
4979  }
4980  }
4981  return dtza->tz;
4982 }

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

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

◆ GetCurrentDateTime()

void GetCurrentDateTime ( struct pg_tm tm)

Definition at line 366 of file datetime.c.

367 {
368  fsec_t fsec;
369 
370  GetCurrentTimeUsec(tm, &fsec, NULL);
371 }

References GetCurrentTimeUsec(), and tm.

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

◆ GetCurrentTimeUsec()

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

Definition at line 387 of file datetime.c.

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

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

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

◆ InstallTimeZoneAbbrevs()

void InstallTimeZoneAbbrevs ( TimeZoneAbbrevTable tbl)

Definition at line 4946 of file datetime.c.

4947 {
4948  zoneabbrevtbl = tbl;
4949  /* reset abbrevcache, which may contain pointers into old table */
4950  memset(abbrevcache, 0, sizeof(abbrevcache));
4951 }

References abbrevcache, 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 522 of file datetime.c.

523 {
524  int64 product;
525 
526  if (pg_mul_s64_overflow(val, multiplier, &product) ||
527  pg_add_s64_overflow(*sum, product, sum))
528  return false;
529  return true;
530 }

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

Referenced by AdjustMicroseconds(), and DecodeTimeForInterval().

◆ ISO8601IntegerWidth()

static int ISO8601IntegerWidth ( char *  fieldstart)
static

Definition at line 3791 of file datetime.c.

3792 {
3793  /* We might have had a leading '-' */
3794  if (*fieldstart == '-')
3795  fieldstart++;
3796  return strspn(fieldstart, "0123456789");
3797 }

Referenced by DecodeISO8601Interval().

◆ j2date()

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

Definition at line 311 of file datetime.c.

312 {
313  unsigned int julian;
314  unsigned int quad;
315  unsigned int extra;
316  int y;
317 
318  julian = jd;
319  julian += 32044;
320  quad = julian / 146097;
321  extra = (julian - quad * 146097) * 4 + 3;
322  julian += 60 + quad * 3 + extra / 146097;
323  quad = julian / 1461;
324  julian -= quad * 1461;
325  y = julian * 4 / 1461;
326  julian = ((y != 0) ? ((julian + 305) % 365) : ((julian + 306) % 366))
327  + 123;
328  y += quad * 4;
329  *year = y - 4800;
330  quad = julian * 2141 / 65536;
331  *day = julian - 7834 * quad / 256;
332  *month = (quad + 10) % MONTHS_PER_YEAR + 1;
333 } /* j2date() */
int y
Definition: isn.c:72

References MONTHS_PER_YEAR, and y.

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

◆ j2day()

int j2day ( int  date)

Definition at line 344 of file datetime.c.

345 {
346  date += 1;
347  date %= 7;
348  /* Cope if division truncates towards zero, as it probably does */
349  if (date < 0)
350  date += 7;
351 
352  return date;
353 } /* 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 754 of file datetime.c.

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

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

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

◆ ParseFraction()

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

Definition at line 680 of file datetime.c.

681 {
682  /* Caller should always pass the start of the fraction part */
683  Assert(*cp == '.');
684 
685  /*
686  * We want to allow just "." with no digits, but some versions of strtod
687  * will report EINVAL for that, so special-case it.
688  */
689  if (cp[1] == '\0')
690  {
691  *frac = 0;
692  }
693  else
694  {
695  errno = 0;
696  *frac = strtod(cp, &cp);
697  /* check for parse failure */
698  if (*cp != '\0' || errno != 0)
699  return DTERR_BAD_FORMAT;
700  }
701  return 0;
702 }

References Assert(), and DTERR_BAD_FORMAT.

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

◆ ParseFractionalSecond()

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

Definition at line 709 of file datetime.c.

710 {
711  double frac;
712  int dterr;
713 
714  dterr = ParseFraction(cp, &frac);
715  if (dterr)
716  return dterr;
717  *fsec = rint(frac * 1000000);
718  return 0;
719 }

References ParseFraction().

Referenced by DecodeNumber(), and DecodeTimeCommon().

◆ ParseISO8601Number()

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

Definition at line 3749 of file datetime.c.

3750 {
3751  double val;
3752 
3753  /*
3754  * Historically this has accepted anything that strtod() would take,
3755  * notably including "e" notation, so continue doing that. This is
3756  * slightly annoying because the precision of double is less than that of
3757  * int64, so we would lose accuracy for inputs larger than 2^53 or so.
3758  * However, historically we rejected inputs outside the int32 range,
3759  * making that concern moot. What we do now is reject abs(val) above
3760  * 1.0e15 (a round number a bit less than 2^50), so that any accepted
3761  * value will have an exact integer part, and thereby a fraction part with
3762  * abs(*fpart) less than 1. In the absence of field complaints it doesn't
3763  * seem worth working harder.
3764  */
3765  if (!(isdigit((unsigned char) *str) || *str == '-' || *str == '.'))
3766  return DTERR_BAD_FORMAT;
3767  errno = 0;
3768  val = strtod(str, endptr);
3769  /* did we not see anything that looks like a double? */
3770  if (*endptr == str || errno != 0)
3771  return DTERR_BAD_FORMAT;
3772  /* watch out for overflow, including infinities; reject NaN too */
3773  if (isnan(val) || val < -1.0e15 || val > 1.0e15)
3774  return DTERR_FIELD_OVERFLOW;
3775  /* be very sure we truncate towards zero (cf dtrunc()) */
3776  if (val >= 0)
3777  *ipart = (int64) floor(val);
3778  else
3779  *ipart = (int64) -floor(-val);
3780  *fpart = val - *ipart;
3781  /* Callers expect this to hold */
3782  Assert(*fpart > -1.0 && *fpart < 1.0);
3783  return 0;
3784 }

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

Referenced by DecodeISO8601Interval().

◆ pg_timezone_abbrevs()

Datum pg_timezone_abbrevs ( PG_FUNCTION_ARGS  )

Definition at line 4990 of file datetime.c.

4991 {
4992  FuncCallContext *funcctx;
4993  int *pindex;
4994  Datum result;
4995  HeapTuple tuple;
4996  Datum values[3];
4997  bool nulls[3] = {0};
4998  const datetkn *tp;
4999  char buffer[TOKMAXLEN + 1];
5000  int gmtoffset;
5001  bool is_dst;
5002  unsigned char *p;
5003  struct pg_itm_in itm_in;
5004  Interval *resInterval;
5005 
5006  /* stuff done only on the first call of the function */
5007  if (SRF_IS_FIRSTCALL())
5008  {
5009  TupleDesc tupdesc;
5010  MemoryContext oldcontext;
5011 
5012  /* create a function context for cross-call persistence */
5013  funcctx = SRF_FIRSTCALL_INIT();
5014 
5015  /*
5016  * switch to memory context appropriate for multiple function calls
5017  */
5018  oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
5019 
5020  /* allocate memory for user context */
5021  pindex = (int *) palloc(sizeof(int));
5022  *pindex = 0;
5023  funcctx->user_fctx = (void *) pindex;
5024 
5025  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
5026  elog(ERROR, "return type must be a row type");
5027  funcctx->tuple_desc = tupdesc;
5028 
5029  MemoryContextSwitchTo(oldcontext);
5030  }
5031 
5032  /* stuff done on every call of the function */
5033  funcctx = SRF_PERCALL_SETUP();
5034  pindex = (int *) funcctx->user_fctx;
5035 
5036  if (zoneabbrevtbl == NULL ||
5037  *pindex >= zoneabbrevtbl->numabbrevs)
5038  SRF_RETURN_DONE(funcctx);
5039 
5040  tp = zoneabbrevtbl->abbrevs + *pindex;
5041 
5042  switch (tp->type)
5043  {
5044  case TZ:
5045  gmtoffset = tp->value;
5046  is_dst = false;
5047  break;
5048  case DTZ:
5049  gmtoffset = tp->value;
5050  is_dst = true;
5051  break;
5052  case DYNTZ:
5053  {
5054  /* Determine the current meaning of the abbrev */
5055  pg_tz *tzp;
5056  DateTimeErrorExtra extra;
5057  TimestampTz now;
5058  int isdst;
5059 
5060  tzp = FetchDynamicTimeZone(zoneabbrevtbl, tp, &extra);
5061  if (tzp == NULL)
5063  NULL, NULL, NULL);
5065  gmtoffset = -DetermineTimeZoneAbbrevOffsetTS(now,
5066  tp->token,
5067  tzp,
5068  &isdst);
5069  is_dst = (bool) isdst;
5070  break;
5071  }
5072  default:
5073  elog(ERROR, "unrecognized timezone type %d", (int) tp->type);
5074  gmtoffset = 0; /* keep compiler quiet */
5075  is_dst = false;
5076  break;
5077  }
5078 
5079  /*
5080  * Convert name to text, using upcasing conversion that is the inverse of
5081  * what ParseDateTime() uses.
5082  */
5083  strlcpy(buffer, tp->token, sizeof(buffer));
5084  for (p = (unsigned char *) buffer; *p; p++)
5085  *p = pg_toupper(*p);
5086 
5087  values[0] = CStringGetTextDatum(buffer);
5088 
5089  /* Convert offset (in seconds) to an interval; can't overflow */
5090  MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5091  itm_in.tm_usec = (int64) gmtoffset * USECS_PER_SEC;
5092  resInterval = (Interval *) palloc(sizeof(Interval));
5093  (void) itmin2interval(&itm_in, resInterval);
5094  values[1] = IntervalPGetDatum(resInterval);
5095 
5096  values[2] = BoolGetDatum(is_dst);
5097 
5098  (*pindex)++;
5099 
5100  tuple = heap_form_tuple(funcctx->tuple_desc, values, nulls);
5101  result = HeapTupleGetDatum(tuple);
5102 
5103  SRF_RETURN_NEXT(funcctx, result);
5104 }
int DetermineTimeZoneAbbrevOffsetTS(TimestampTz ts, const char *abbr, pg_tz *tzp, int *isdst)
Definition: datetime.c:1784
int itmin2interval(struct pg_itm_in *itm_in, Interval *span)
Definition: timestamp.c:2115
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
static Datum values[MAXATTR]
Definition: bootstrap.c:152
#define CStringGetTextDatum(s)
Definition: builtins.h:97
unsigned char bool
Definition: c.h:443
#define MemSet(start, val, len)
Definition: c.h:1007
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:1116
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void * palloc(Size size)
Definition: mcxt.c:1304
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
TupleDesc tuple_desc
Definition: funcapi.h:112
static Datum IntervalPGetDatum(const Interval *X)
Definition: timestamp.h:58

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

◆ pg_timezone_names()

Datum pg_timezone_names ( PG_FUNCTION_ARGS  )

Definition at line 5111 of file datetime.c.

5112 {
5113  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
5114  pg_tzenum *tzenum;
5115  pg_tz *tz;
5116  Datum values[4];
5117  bool nulls[4] = {0};
5118  int tzoff;
5119  struct pg_tm tm;
5120  fsec_t fsec;
5121  const char *tzn;
5122  Interval *resInterval;
5123  struct pg_itm_in itm_in;
5124 
5125  InitMaterializedSRF(fcinfo, 0);
5126 
5127  /* initialize timezone scanning code */
5128  tzenum = pg_tzenumerate_start();
5129 
5130  /* search for another zone to display */
5131  for (;;)
5132  {
5133  tz = pg_tzenumerate_next(tzenum);
5134  if (!tz)
5135  break;
5136 
5137  /* Convert now() to local time in this zone */
5139  &tzoff, &tm, &fsec, &tzn, tz) != 0)
5140  continue; /* ignore if conversion fails */
5141 
5142  /*
5143  * IANA's rather silly "Factory" time zone used to emit ridiculously
5144  * long "abbreviations" such as "Local time zone must be set--see zic
5145  * manual page" or "Local time zone must be set--use tzsetup". While
5146  * modern versions of tzdb emit the much saner "-00", it seems some
5147  * benighted packagers are hacking the IANA data so that it continues
5148  * to produce these strings. To prevent producing a weirdly wide
5149  * abbrev column, reject ridiculously long abbreviations.
5150  */
5151  if (tzn && strlen(tzn) > 31)
5152  continue;
5153 
5155  values[1] = CStringGetTextDatum(tzn ? tzn : "");
5156 
5157  /* Convert tzoff to an interval; can't overflow */
5158  MemSet(&itm_in, 0, sizeof(struct pg_itm_in));
5159  itm_in.tm_usec = (int64) -tzoff * USECS_PER_SEC;
5160  resInterval = (Interval *) palloc(sizeof(Interval));
5161  (void) itmin2interval(&itm_in, resInterval);
5162  values[2] = IntervalPGetDatum(resInterval);
5163 
5164  values[3] = BoolGetDatum(tm.tm_isdst > 0);
5165 
5166  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc, values, nulls);
5167  }
5168 
5169  pg_tzenumerate_end(tzenum);
5170  return (Datum) 0;
5171 }
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
const char * pg_get_timezone_name(pg_tz *tz)
Definition: localtime.c:1875
pg_tz * pg_tzenumerate_next(pg_tzenum *dir)
Definition: pgtz.c:426
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:750

References values.

◆ TemporalSimplify()

Node* TemporalSimplify ( int32  max_precis,
Node node 
)

Definition at line 4829 of file datetime.c.

4830 {
4831  FuncExpr *expr = castNode(FuncExpr, node);
4832  Node *ret = NULL;
4833  Node *typmod;
4834 
4835  Assert(list_length(expr->args) >= 2);
4836 
4837  typmod = (Node *) lsecond(expr->args);
4838 
4839  if (IsA(typmod, Const) && !((Const *) typmod)->constisnull)
4840  {
4841  Node *source = (Node *) linitial(expr->args);
4842  int32 old_precis = exprTypmod(source);
4843  int32 new_precis = DatumGetInt32(((Const *) typmod)->constvalue);
4844 
4845  if (new_precis < 0 || new_precis == max_precis ||
4846  (old_precis >= 0 && new_precis >= old_precis))
4847  ret = relabel_to_typmod(source, new_precis);
4848  }
4849 
4850  return ret;
4851 }
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:284
Node * relabel_to_typmod(Node *expr, int32 typmod)
Definition: nodeFuncs.c:656
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
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:724
Definition: nodes.h:129

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

Referenced by time_support(), and timestamp_support().

◆ ValidateDate()

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

Definition at line 2497 of file datetime.c.

2499 {
2500  if (fmask & DTK_M(YEAR))
2501  {
2502  if (isjulian)
2503  {
2504  /* tm_year is correct and should not be touched */
2505  }
2506  else if (bc)
2507  {
2508  /* there is no year zero in AD/BC notation */
2509  if (tm->tm_year <= 0)
2510  return DTERR_FIELD_OVERFLOW;
2511  /* internally, we represent 1 BC as year zero, 2 BC as -1, etc */
2512  tm->tm_year = -(tm->tm_year - 1);
2513  }
2514  else if (is2digits)
2515  {
2516  /* process 1 or 2-digit input as 1970-2069 AD, allow '0' and '00' */
2517  if (tm->tm_year < 0) /* just paranoia */
2518  return DTERR_FIELD_OVERFLOW;
2519  if (tm->tm_year < 70)
2520  tm->tm_year += 2000;
2521  else if (tm->tm_year < 100)
2522  tm->tm_year += 1900;
2523  }
2524  else
2525  {
2526  /* there is no year zero in AD/BC notation */
2527  if (tm->tm_year <= 0)
2528  return DTERR_FIELD_OVERFLOW;
2529  }
2530  }
2531 
2532  /* now that we have correct year, decode DOY */
2533  if (fmask & DTK_M(DOY))
2534  {
2535  j2date(date2j(tm->tm_year, 1, 1) + tm->tm_yday - 1,
2536  &tm->tm_year, &tm->tm_mon, &tm->tm_mday);
2537  }
2538 
2539  /* check for valid month */
2540  if (fmask & DTK_M(MONTH))
2541  {
2542  if (tm->tm_mon < 1 || tm->tm_mon > MONTHS_PER_YEAR)
2543  return DTERR_MD_FIELD_OVERFLOW;
2544  }
2545 
2546  /* minimal check for valid day */
2547  if (fmask & DTK_M(DAY))
2548  {
2549  if (tm->tm_mday < 1 || tm->tm_mday > 31)
2550  return DTERR_MD_FIELD_OVERFLOW;
2551  }
2552 
2553  if ((fmask & DTK_DATE_M) == DTK_DATE_M)
2554  {
2555  /*
2556  * Check for valid day of month, now that we know for sure the month
2557  * and year. Note we don't use MD_FIELD_OVERFLOW here, since it seems
2558  * unlikely that "Feb 29" is a YMD-order error.
2559  */
2560  if (tm->tm_mday > day_tab[isleap(tm->tm_year)][tm->tm_mon - 1])
2561  return DTERR_FIELD_OVERFLOW;
2562  }
2563 
2564  return 0;
2565 }
const int day_tab[2][13]
Definition: datetime.c:75
#define isleap(y)
Definition: datetime.h:271

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

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

Variable Documentation

◆ abbrevcache

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

Definition at line 262 of file datetime.c.

Referenced by DecodeTimezoneAbbrev(), and InstallTimeZoneAbbrevs().

◆ datecache

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

Definition at line 258 of file datetime.c.

Referenced by DecodeSpecial().

◆ datetktbl

const datetkn datetktbl[]
static

Definition at line 105 of file datetime.c.

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

◆ day_tab

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

Definition at line 75 of file datetime.c.

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

◆ days

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

Definition at line 84 of file datetime.c.

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

◆ deltacache

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

Definition at line 260 of file datetime.c.

Referenced by DecodeUnits().

◆ deltatktbl

const datetkn deltatktbl[]
static

Definition at line 187 of file datetime.c.

Referenced by CheckDateTokenTables(), and DecodeUnits().

◆ months

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

Definition at line 81 of file datetime.c.

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

◆ szdatetktbl

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

Definition at line 181 of file datetime.c.

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

◆ szdeltatktbl

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

Definition at line 252 of file datetime.c.

Referenced by CheckDateTokenTables(), and DecodeUnits().

◆ zoneabbrevtbl

TimeZoneAbbrevTable* zoneabbrevtbl = NULL
static