Skip to content
Closed
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
15 changes: 15 additions & 0 deletions .github/workflows/custom/before-install/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,18 @@ runs:
sudo apt-get update
sudo apt-get install -y tzdata-legacy
shell: bash

- name: Generate the locales the money tests use (Linux)
# tests/testthat/test-money.R sets lc_monetary to these locales
# and skips each one the server lacks.
# The server reads the locales when it starts,
# so they must exist before ankane/setup-postgres starts it in after-install.
# Windows names its locales differently, so the tests skip there.
if: runner.os == 'Linux'
run: |
sudo apt-get install -y locales
for locale in en_US de_DE de_CH fr_FR sv_SE nl_NL pt_BR ja_JP ar_KW; do
sudo localedef -i $locale -f UTF-8 $locale.UTF-8
done
locale -a
shell: bash
13 changes: 13 additions & 0 deletions R/PqResult.R
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ setClass(
#' Alternatively, if you want all the results (and they'll fit in memory) use `dbGetQuery()` which sends,
#' fetches and clears for you.
#'
#' @section Money:
#' Columns of type `money` are returned as numbers.
#' PostgreSQL formats them as text according to the server's `lc_monetary` setting,
#' and RPostgres infers the thousands and decimal separators from that text alone.
#' In locales with two fractional digits, such as `C`, `en_US` or `de_DE`, every value is read correctly.
#' In locales with no or three fractional digits, a single separator followed by three digits is ambiguous:
#' `"1,235"` is 1235 in `ja_JP` but would be 1.235 in `sq_AL`.
#' Such values are returned as `NA` with a warning.
#' This affects amounts from 1,000 to 999,999 in locales without fractional digits
#' (such as `ja_JP`, `ko_KR`, `is_IS` or `vi_VN`),
#' and amounts from 1 to 999.999 in locales with three (such as `ar_KW`).
#' Cast to numeric in the query, as in `SELECT amount::numeric`, to read money exactly in any locale.
#'
#' @param conn A [PqConnection-class] created by [dbConnect()].
#' @param statement An SQL string to execute.
#' @param params A list of query parameters to be substituted into a parameterised query.
Expand Down
15 changes: 15 additions & 0 deletions man/postgres-query.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/DbColumn.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ void DbColumn::finalize(const int n_) {
}

void DbColumn::warn_type_conflicts(const cpp11::r_string& name) const {
// Peeking at the first row (dbFetch(n = 0), dbColumnInfo()) parses a row
// that it does not return, the column then has no rows.
if (n > 0) {
source->warn_parse_failures(static_cast<std::string>(name));
}

std::set<DATA_TYPE> my_data_types_seen = data_types_seen;
DATA_TYPE dt = get_last_storage()->get_data_type();

Expand Down
2 changes: 2 additions & 0 deletions src/DbColumnDataSource.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ DbColumnDataSource::~DbColumnDataSource() {}
int DbColumnDataSource::get_j() const {
return j;
}

void DbColumnDataSource::warn_parse_failures(const std::string&) const {}
6 changes: 6 additions & 0 deletions src/DbColumnDataSource.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#ifndef DB_COLUMNDATASOURCE_H
#define DB_COLUMNDATASOURCE_H

#include <string>

#include "DbColumnDataType.h"

class DbColumnDataSource {
Expand Down Expand Up @@ -29,6 +31,10 @@ class DbColumnDataSource {
virtual double fetch_datetime() const = 0;
virtual double fetch_time() const = 0;

// Called once per column after each fetch,
// to warn about values that could not be parsed.
virtual void warn_parse_failures(const std::string& name) const;

protected:
int get_j() const;
};
Expand Down
182 changes: 179 additions & 3 deletions src/PqColumnDataSource.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "pch.h"
#include <boost/lexical_cast.hpp>
#include <sstream>
#include "PqColumnDataSource.h"
#include "PqResultSource.h"
#include "PqUtils.h"
Expand All @@ -9,7 +10,10 @@ PqColumnDataSource::PqColumnDataSource(
const DATA_TYPE dt_,
const int j
)
: DbColumnDataSource(j), result_source(result_source_), dt(dt_) {}
: DbColumnDataSource(j),
result_source(result_source_),
dt(dt_),
n_parse_failures(0) {}

PqColumnDataSource::~PqColumnDataSource() {}

Expand Down Expand Up @@ -37,6 +41,144 @@ int64_t PqColumnDataSource::fetch_int64() const {
return boost::lexical_cast<int64_t>(get_result_value());
}

namespace {

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

// Parses the text output of a money value.
// Its format depends on the server's lc_monetary setting,
// as in "$1,234.56", "-1.234,56 \u20ac", "CHF- 1\u2019234.50", "($1.00)",
// or "1,234.500-" after an Arabic currency symbol that contains dots.
// Everything before the first digit and after the last one
// is the currency symbol and the sign.
// Between them, PostgreSQL's cash_out() writes digit groups
// joined by a thousands separator of any length,
// and, unless the locale has no fractional digits,
// a single-byte decimal separator before the last group.
// Returns false if the text cannot be parsed unambiguously.
// With a single single-byte separator followed by three or four digits,
// "1,234" is 1234 in ja_JP (no fractional digits)
// and 1.234 in sq_AL (three fractional digits).
bool parse_money(const char* value, double* out) {
const char* begin = value;
while (*begin != '\0' && !is_digit(*begin)) {
++begin;
}
if (*begin == '\0') {
return false;
}
const char* end = value + strlen(value);
while (!is_digit(end[-1])) {
--end;
}

// The sign sits outside the digits, possibly next to the currency symbol:
// a minus sign, or parentheses around the amount.
// An ASCII '-' and '(' cover every glibc locale:
// all their negative_sign values are "-" or empty (then cash_out() uses "-"),
// n_sign_posn 0 means parentheses,
// and no currency_symbol contains '-', '(' or ')'.
bool negative = false;
bool open_paren = false;
for (const char* p = value; p < begin; ++p) {
if (*p == '-') {
negative = true;
}
if (*p == '(') {
open_paren = true;
}
}
for (const char* p = end; *p != '\0'; ++p) {
if (*p == '-') {
negative = true;
}
if (*p == ')' && open_paren) {
negative = true;
}
}

// Split into digit groups and the separators between them.
std::vector<std::string> groups;
std::vector<std::string> seps;
for (const char* p = begin; p < end;) {
const char* q = p;
while (q < end && is_digit(*q)) {
++q;
}
groups.push_back(std::string(p, q));
if (q == end) {
break;
}
p = q;
while (p < end && !is_digit(*p)) {
++p;
}
seps.push_back(std::string(q, p));
}

// The number of leading separators that are thousands separators.
const size_t n_seps = seps.size();
size_t n_thousands;
if (n_seps == 0) {
n_thousands = 0;
} else if (n_seps >= 2 && seps[n_seps - 1] != seps[n_seps - 2]) {
// Two kinds of separators: the last one is the decimal separator.
if (seps[n_seps - 1].size() != 1) {
return false;
}
n_thousands = n_seps - 1;
} else if (n_seps >= 2) {
// The same separator repeated: thousands separators only.
n_thousands = n_seps;
} else if (seps[0].size() != 1) {
// The decimal separator is a single byte, this one is not.
n_thousands = 1;
} else if (groups[0][0] == '0') {
// A leading group of thousands never starts with a zero.
n_thousands = 0;
} else if (groups[1].size() == 3 || groups[1].size() == 4) {
// Either a group of thousands or the fractional digits.
// This loses amounts from 1,000 to 999,999 in locales
// without fractional digits (ja_JP, ko_KR, is_IS, vi_VN, ...),
// and amounts from 1 to 999.999 in locales with three (ar_KW, ...).
return false;
} else {
n_thousands = 0;
}

// Thousands separators are all the same, between groups of the same size.
// The leading group is no larger and has no leading zero.
if (n_thousands > 0) {
const size_t group_size = groups[1].size();
if (groups[0].size() > group_size || groups[0][0] == '0') {
return false;
}
for (size_t i = 1; i <= n_thousands; ++i) {
if (seps[i - 1] != seps[0]) {
return false;
}
if (groups[i].size() != group_size) {
return false;
}
}
}

std::string number = negative ? "-" : "";
for (size_t i = 0; i < groups.size(); ++i) {
if (i > n_thousands) {
number += '.';
}
number += groups[i];
}

*out = strtod(number.c_str(), NULL);
return true;
}

} // namespace

double PqColumnDataSource::fetch_real() const {
const char* value = get_result_value();

Expand All @@ -46,9 +188,43 @@ double PqColumnDataSource::fetch_real() const {
return INFINITY;
} else if (strcmp(value, "NaN") == 0) {
return NAN;
} else {
return atof(value);
}

// numeric, float4 and float8 values are plain numbers.
char* end;
double ret = strtod(value, &end);
if (end != value && *end == '\0') {
return ret;
}

// money values carry a currency symbol and separators.
if (parse_money(value, &ret)) {
return ret;
}

// Warn once per column and fetch, in warn_parse_failures().
// Each fetch builds fresh column sources, so the count starts at zero.
if (n_parse_failures == 0) {
first_parse_failure = value;
}
++n_parse_failures;
return NA_REAL;
}

void PqColumnDataSource::warn_parse_failures(const std::string& name) const {
if (n_parse_failures == 0) {
return;
}

std::stringstream ss;
ss << "Column `" << name << "`: can't parse " << n_parse_failures
<< " value(s) unambiguously as numbers, returning NA, such as \""
<< first_parse_failure << "\". "
<< "For money columns, the format depends on lc_monetary, "
<< "cast them to numeric in the query.";

// Not a format string: the name and the value may contain '%'.
cpp11::warning("%s", ss.str().c_str());
}

SEXP PqColumnDataSource::fetch_string() const {
Expand Down
6 changes: 6 additions & 0 deletions src/PqColumnDataSource.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#ifndef RPOSTGRES_PQCOLUMNDATASOURCE_H
#define RPOSTGRES_PQCOLUMNDATASOURCE_H

#include <string>

#include "DbColumnDataSource.h"

class PqResultSource;
Expand All @@ -9,6 +11,8 @@ class PqColumnDataSourceFactory;
class PqColumnDataSource : public DbColumnDataSource {
PqResultSource* result_source;
const DATA_TYPE dt;
mutable int n_parse_failures;
mutable std::string first_parse_failure;

public:
PqColumnDataSource(
Expand All @@ -35,6 +39,8 @@ class PqColumnDataSource : public DbColumnDataSource {
virtual double fetch_datetime() const;
virtual double fetch_time() const;

virtual void warn_parse_failures(const std::string& name) const;

private:
static double convert_datetime(const char* val);
PGresult* get_result() const;
Expand Down
27 changes: 27 additions & 0 deletions tests/testthat/helper-money.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Connects with lc_monetary set to `locale`,
# skipping the test if the server does not have that locale.
postgres_with_lc_monetary <- function(locale) {
con <- postgresDefault()
ok <- tryCatch(
{
dbExecute(con, paste0("SET lc_monetary = ", dbQuoteString(con, locale)))
TRUE
},
error = function(e) FALSE
)
if (!ok) {
dbDisconnect(con)
skip(paste0("lc_monetary = '", locale, "' not available on the server"))
}
con
}

# Reads each of `values` as money, one row each.
read_money <- function(con, values) {
sql <- paste0(
"SELECT v::money AS m FROM unnest(ARRAY[",
paste0("'", values, "'::numeric", collapse = ", "),
"]) WITH ORDINALITY AS t(v, i) ORDER BY i"
)
dbGetQuery(con, sql)$m
}
Loading