Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
202 changes: 144 additions & 58 deletions src/PqColumnDataSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,79 @@
#include "PqResultSource.h"
#include "PqUtils.h"

// Parsers for the text output of PostgreSQL's date and time types
// with DateStyle ISO.
// Each takes the current position and the end of the value,
// never reads at or past the end,
// and advances the position only on success.
namespace {

bool is_digit(char c) {
return c >= '0' && c <= '9';
}

bool parse_char(const char*& val, const char* end, char c) {
if (val == end || *val != c) {
return false;
}
++val;
return true;
}

// One to max_digits decimal digits
bool parse_uint(const char*& val, const char* end, int max_digits, int& out) {
const char* p = val;
int ret = 0;
for (; p != end && p - val < max_digits && is_digit(*p); ++p) {
ret = ret * 10 + (*p - '0');
}
if (p == val) {
return false;
}
out = ret;
val = p;
return true;
}

// YYYY-MM-DD, PostgreSQL emits four or more digits for the year
bool parse_ymd(const char*& val, const char* end, int& y, int& m, int& d) {
const char* p = val;
// Up to 5874897, the largest year of the date type;
// days_from_civil() overflows int for larger years
if (!parse_uint(p, end, 7, y) || y > 5874897 || !parse_char(p, end, '-') ||
!parse_uint(p, end, 2, m) || !parse_char(p, end, '-') ||
!parse_uint(p, end, 2, d)) {
return false;
}
val = p;
return true;
}

// The " BC" suffix of years before 1 AD, after any offset from UTC
bool parse_bc(const char*& val, const char* end) {
if (end - val < 3 || strncmp(val, " BC", 3) != 0) {
return false;
}
val += 3;
return true;
}

// The whole value is "infinity" or "-infinity"
bool parse_infinity(const char* val, const char* end, double& out) {
const size_t len = static_cast<size_t>(end - val);
if (len == 8 && strncmp(val, "infinity", 8) == 0) {
out = R_PosInf;
return true;
}
if (len == 9 && strncmp(val, "-infinity", 9) == 0) {
out = R_NegInf;
return true;
}
return false;
}

} // namespace

PqColumnDataSource::PqColumnDataSource(
PqResultSource* result_source_,
const DATA_TYPE dt_,
Expand Down Expand Up @@ -72,19 +145,24 @@ SEXP PqColumnDataSource::fetch_blob() const {

double PqColumnDataSource::fetch_date() const {
const char* val = get_result_value();
int year = *val - 0x30;
year *= 10;
year += (*(++val) - 0x30);
year *= 10;
year += (*(++val) - 0x30);
year *= 10;
year += (*(++val) - 0x30);
val++;
int mon = 10 * (*(++val) - 0x30);
mon += (*(++val) - 0x30);
val++;
int mday = (*(++val) - 0x30) * 10;
mday += (*(++val) - 0x30);
const char* end = val + strlen(val);

double special;
if (parse_infinity(val, end, special)) {
return special;
}

int year, mon, mday;
if (!parse_ymd(val, end, year, mon, mday)) {
return NA_REAL;
}
bool bc = parse_bc(val, end);
if (val != end) {
return NA_REAL;
}
if (bc) {
year = 1 - year;
}
return days_from_civil(year, mon, mday);
}

Expand All @@ -109,61 +187,69 @@ double PqColumnDataSource::fetch_time() const {
}

double PqColumnDataSource::convert_datetime(const char* val) {
struct tm date;
date.tm_isdst = -1;
date.tm_year = *val++ - 0x30;
date.tm_year *= 10;
date.tm_year += (*val++ - 0x30);
date.tm_year *= 10;
date.tm_year += (*val++ - 0x30);
date.tm_year *= 10;
date.tm_year += (*val++ - 0x30) - 1900;

val++;
date.tm_mon = (*val++ - 0x30) * 10;
date.tm_mon += (*val++ - 0x30) - 1;
const char* end = val + strlen(val);

val++;
date.tm_mday = (*val++ - 0x30) * 10;
date.tm_mday += (*val++ - 0x30);

val++;
date.tm_hour = (*val++ - 0x30) * 10;
date.tm_hour += (*val++ - 0x30);

val++;
date.tm_min = (*val++ - 0x30) * 10;
date.tm_min += (*val++ - 0x30);
double special;
if (parse_infinity(val, end, special)) {
return special;
}

val++;
char* end;
double sec = strtod(val, &end);
val = end;
int year, mon, mday, hour, min, sec;
if (!parse_ymd(val, end, year, mon, mday) || !parse_char(val, end, ' ') ||
!parse_uint(val, end, 2, hour) || !parse_char(val, end, ':') ||
!parse_uint(val, end, 2, min) || !parse_char(val, end, ':') ||
!parse_uint(val, end, 2, sec)) {
return NA_REAL;
}

date.tm_sec = static_cast<int>(sec);
// Fractional seconds, PostgreSQL emits at most six digits
double frac = 0;
if (parse_char(val, end, '.')) {
long long num = 0, den = 1;
if (val == end || !is_digit(*val)) {
return NA_REAL;
}
for (; val != end && is_digit(*val); ++val) {
if (den < 1000000000000000LL) {
num = num * 10 + (*val - '0');
den *= 10;
}
}
frac = static_cast<double>(num) / static_cast<double>(den);
}

// Offset from UTC: +HH, +HH:MM, or +HH:MM:SS (local mean time)
int utcoffset = 0;
if (*val == '+' || *val == '-') {
int tz_hours = 0, tz_minutes = 0, sign = 0;
sign = (*val++ == '+' ? +1 : -1);

tz_hours = (*val++ - 0x30) * 10;
tz_hours += (*val++ - 0x30);

if (*val == ':') {
++val;
tz_minutes = (*val++ - 0x30) * 10;
tz_minutes += (*val++ - 0x30);
if (val != end && (*val == '+' || *val == '-')) {
int sign = (*val++ == '+' ? +1 : -1);
int tz_hours = 0, tz_minutes = 0, tz_seconds = 0;
if (!parse_uint(val, end, 2, tz_hours)) {
return NA_REAL;
}

utcoffset = sign * (tz_hours * 3600 + tz_minutes * 60);
if (parse_char(val, end, ':')) {
if (!parse_uint(val, end, 2, tz_minutes)) {
return NA_REAL;
}
if (parse_char(val, end, ':') && !parse_uint(val, end, 2, tz_seconds)) {
return NA_REAL;
}
}
utcoffset = sign * (tz_hours * 3600 + tz_minutes * 60 + tz_seconds);
}

time_t time = tm_to_time_t(date);
bool bc = parse_bc(val, end);
if (val != end) {
return NA_REAL;
}
if (bc) {
year = 1 - year;
}

double ret = static_cast<double>(time) + (sec - date.tm_sec) - utcoffset;
// Exact in double: the largest value is far below 2^53
double days = days_from_civil(year, mon, mday);
double secs = days * 86400 + hour * 3600 + min * 60 + sec;

return ret;
return secs + frac - utcoffset;
}

PGresult* PqColumnDataSource::get_result() const {
Expand Down
100 changes: 100 additions & 0 deletions tests/testthat/test-datetime-parsing.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
test_that("infinite dates and timestamps with time zone are returned as Inf (#655)", {
con <- postgresDefault()
on.exit(dbDisconnect(con))

res <- dbGetQuery(
con,
"SELECT 'infinity'::date AS a, '-infinity'::date AS b,
'infinity'::timestamptz AS c, '-infinity'::timestamptz AS d"
)
expect_identical(unclass(res$a), Inf)
expect_identical(unclass(res$b), -Inf)
expect_identical(as.numeric(res$c), Inf)
expect_identical(as.numeric(res$d), -Inf)
})

test_that("infinite timestamps do not depend on the rest of the query (#655)", {
con <- postgresDefault()
on.exit(dbDisconnect(con))

alone <- dbGetQuery(con, "SELECT 'infinity'::timestamp AS c")$c
with_others <- dbGetQuery(
con,
"SELECT 1 AS x, 'infinity'::timestamp AS c, 'abc' AS y"
)$c
padded <- dbGetQuery(
con,
"SELECT repeat('x', 1000) AS a, 'infinity'::timestamp AS c"
)$c
expect_false(is.finite(alone))
expect_identical(with_others, alone)
expect_identical(padded, alone)
})

test_that("dates outside years 1 to 9999 are parsed (#655)", {
con <- postgresDefault()
on.exit(dbDisconnect(con))

dates <- c(
"10000-01-01",
"5874897-12-31",
"0044-03-15 BC",
"0001-01-01 BC",
"4713-11-24 BC",
"0001-01-01",
"2020-02-29"
)
sql <- paste0(
"SELECT d, d - '1970-01-01'::date AS days FROM (VALUES ",
paste0("('", dates, "'::date)", collapse = ", "),
") AS t(d)"
)
res <- dbGetQuery(con, sql)
expect_s3_class(res$d, "Date")
expect_equal(unclass(res$d), as.numeric(res$days))
# 1 BC is year 0
expect_equal(res$d[[4]], as.Date(ISOdate(0, 1, 1)))
})

test_that("timestamps outside years 1 to 9999 are parsed (#655)", {
con <- postgresDefault()
on.exit(dbDisconnect(con))

timestamps <- c(
"10000-01-01 12:00:00",
"294276-12-31 23:59:59",
"0044-03-15 12:00:00.25 BC",
"4713-11-24 00:00:00 BC",
"2020-01-01 12:00:00.123456"
)
values <- paste0("('", timestamps, "')", collapse = ", ")
sql <- paste0(
"SELECT s::timestamp AS ts, s::timestamptz AS tstz,
extract(epoch FROM s::timestamp)::float8 AS epoch
FROM (VALUES ",
values,
") AS t(s)"
)
res <- dbGetQuery(con, sql)
expect_equal(as.numeric(res$ts), res$epoch)
expect_equal(as.numeric(res$tstz), res$epoch)
expect_equal(as.numeric(res$tstz[[3]]) %% 1, 0.25)
})

test_that("offsets from UTC with seconds are honored (#655)", {
con <- postgresDefault(timezone = "Asia/Kolkata")
on.exit(dbDisconnect(con))

# Local mean time before 1854: PostgreSQL returns an offset of +05:53:28
res <- dbGetQuery(
con,
"SELECT s::timestamptz AS tstz, s::timestamptz::text AS text,
extract(epoch FROM s::timestamptz)::float8 AS epoch
FROM (VALUES ('1850-01-01 00:00:00'), ('0044-03-15 00:00:00 BC'),
('2020-06-01 12:00:00.5')) AS t(s)"
)
expect_match(res$text[[1]], "[+]05:53:28$")
expect_match(res$text[[2]], "[+]05:53:28 BC$")
expect_match(res$text[[3]], "[+]05:30$")
expect_equal(as.numeric(res$tstz), res$epoch)
})