Skip to content

fix: Read money columns as numbers instead of 0 - #659

Closed
krlmlr wants to merge 5 commits into
mainfrom
claude/fix-money
Closed

krlmlr wants to merge 5 commits into
mainfrom
claude/fix-money

Conversation

@krlmlr

@krlmlr krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member

Closes #654.

money (OID 790) maps to DT_REAL in get_column_type_from_oid(), so its text output reaches PqColumnDataSource::fetch_real(), which called atof() and returned 0 for every value such as $1,234.56. The fix stays in the parsing logic and reads nothing more from the PGresult. Plain numbers (numeric, float4, float8) still go through strtod(), which now has to consume the whole string. Anything else is parsed as money output by a new parse_money() helper that follows PostgreSQL's cash_out(). The sign (a minus anywhere around the digits, or parentheses) and the currency symbol sit outside the digits, thousands separators may be multibyte, and the decimal separator is a single byte before the last digit group. ASCII - and ( cover every glibc locale's negative sign.

The text alone does not always tell the decimal separator from a thousands separator. With a single single-byte separator followed by three or four digits, 1,235 is 1235 in ja_JP (no fractional digits) and 1.235 in sq_AL (three fractional digits). Such values become NA instead of a silently wrong number. In locales without fractional digits (ja_JP, ko_KR, is_IS, vi_VN, ...), every amount from 1,000 to 999,999 is lost this way. In locales with three (ar_KW, ...), every amount from 1 to 999.999 is. The common locales with two fractional digits are not affected, because every value carries the decimal separator. A new "Money" section on the dbGetQuery() help page (postgres-query) documents this and recommends casting to numeric.

Values that cannot be parsed are counted, and after each fetch they raise one warning per column. The warning names the column, the count and the first such value, through a new warn_parse_failures() hook that DbColumn::warn_type_conflicts() calls. The message goes through a "%s" format, so a % in a column name or a value is printed as is. Peeking at the first row, as dbFetch(n = 0) and dbColumnInfo() do, does not warn, because that row is not returned. A 200,000-row ja_JP fetch raises one warning and takes about 0.06 s. With options(warn = 2), the fetch errors cleanly and the result can still be fetched from afterwards.

The older mixed-type warning in DbColumn::warn_type_conflicts() (src/DbColumn.cpp) also passes its message to cpp11::warning() as a format string. This PR leaves it alone, and it is being handled in a separate issue and PR.

Tests in tests/testthat/test-money.R set lc_monetary to C, en_US, de_DE, de_CH, fr_FR, sv_SE, nl_NL, pt_BR, ja_JP and ar_KW with SET lc_monetary. They cover negative values, the extremes of the money range, NULL and the ambiguous cases. They also check the warning: its count per column and fetch, a column name containing %s%n, and the first-row peek. Locales the server lacks are skipped. CI on Linux generates all these locales before PostgreSQL starts (.github/workflows/custom/before-install), so the money tests run there without skips; Windows names its locales differently, so they skip there. The warning tests need ja_JP, because money in two-digit locales is never ambiguous. Locally the money tests and the full test suite passed against PostgreSQL 16 with all these locales generated.

Phase 1 of the ALTREP work (#632) will move this parser into shared functions and should carry this fix with it. How money should be returned is an open question: #659 (comment)

Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g

Accepted limitations after three review rounds: #659 (comment)

https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g


Generated by Claude Code

`fetch_real()` parsed every value with `atof()`,
which stops at the currency symbol of a money value such as "$1,234.56" and returns 0.
Plain numbers still go through `strtod()`.
Other text is now parsed as money output in any lc_monetary locale:
the sign and currency symbol around the digits are recognized,
thousands separators are dropped, and the decimal separator is detected from the digit groups.
Text that cannot be parsed unambiguously,
such as "1,235" in a locale without fractional digits (ja_JP) or "1.500" in one with three (ar_KW),
becomes NA with a warning.

Closes #654.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Question: How should money values be returned?

PostgreSQL formats money as text according to the server's lc_monetary setting, for example $1,234.56, 1.234.567,89 €, CHF- 1’234.50, ¥1,235, or د.ك. 1,234.500-. The client cannot see lc_monetary without running an extra query, and the binary format (an int64 in minor units) does not help either, since it still needs the locale's number of fractional digits. RPostgres has mapped OID 790 to DT_REAL since its first fetch implementation in 2015, and #654 is the only issue about money that a search of this repository finds. This PR parses the text in parse_money() and returns NA where the text is ambiguous, with one warning per column and fetch. The ambiguity affects only locales without two fractional digits, 32 of them in glibc. In ja_JP, ko_KR, is_IS, vi_VN and other locales without fractional digits, every amount from 1,000 to 999,999 (such as ¥1,000 or ¥-1,235) comes back as NA. In ar_KW and other locales with three fractional digits, every amount from 1 to 999.999 (such as د.ك. 12.340) does. The PostgreSQL documentation recommends casting money to numeric, which is exact and works in every locale, and the dbGetQuery() help page now says so.

  • (recommended) Keep this PR: parse into a double in every locale, and return NA with a warning only where the text is ambiguous. Cost: the ja_JP and ar_KW losses above, documented and warned about. The change stays inside the parser, plus a small hook that warns once per column.
  • Probe the server's money format once per connection (or once per result), for example with SELECT 1.5::money::text, so that the decimal separator and the number of fractional digits are known and no value is ambiguous. Cost: an extra round trip per connection, and code outside the parser (connection state passed down to the column sources), which the ALTREP session in docs: Design ALTREP-backed result columns #632 asked to keep minimal. A per-connection probe also goes stale after SET lc_monetary, so it would have to be repeated per result or invalidated on SET.
  • Return money as character, as the text PostgreSQL sends. Never wrong and locale-proof, but it changes the column type for existing users who get correct numbers today, and it needs a change to the OID map in src/PqResultImpl.cpp, which docs: Design ALTREP-backed result columns #632 also touches.
  • Parse assuming C/en_US conventions ($, , thousands, . decimal) only, and document that other locales need a cast to numeric. Simpler, but 1.234,56 € would then have to become NA or an error to avoid wrong values, so it covers less than this PR for little saving in code.

Kirill has the say. If nobody decides, the PR stays as it is, a strict improvement over returning 0 for every value.


Generated by Claude Code

krlmlr and others added 3 commits November 29, 2026 12:20
… ambiguous `money` values

A value that cannot be parsed as a number now counts towards one warning per column and fetch,
which names the column, the count, and the first such value,
instead of one warning per value.
The warning no longer assumes the column is money.

Money values whose text is ambiguous become NA:
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.
The documentation of `dbGetQuery()` now says so and recommends casting to numeric.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g
… first-row peeks

The warning passes its message as an argument to a "%s" format,
so a `%` in the column name or the value is printed as is.
Peeking at the first row, as `dbFetch(n = 0)` and `dbColumnInfo()` do,
parses a row it does not return and no longer warns about it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g

krlmlr commented Nov 29, 2026 •

Copy link
Copy Markdown
Member Author

Superseded: Accepted limitations

Superseded by #659 (comment).

These limitations remain after three rounds of clean review.

  • src/PqColumnDataSource.cpp (parse_money()): in locales with 0 or 3 fractional digits, ordinary amounts come back as NA with one warning per column. Examples are ja_JP (¥1,000 to ¥999,999), ar_KW (1.000 to 999.999), is_IS and vi_VN, about 32 glibc locales in all. The text alone cannot tell a thousands separator from a decimal separator there. This is documented in ?postgres-query, under "Money". The fix, probing the server's money format, is an option in the question above. Relevance: medium for users in those locales. Confidence: high. (recorded)
  • tests/testthat/test-money.R: the tests for the %-safe warning and for "no warning on peek" need the ja_JP locale on the server. CI doesn't set that locale up, so CI skips them. They passed locally, with no skips, on a cluster that has ja_JP. No value triggers the warning in the C, en_US or de_DE locales. Adding a localedef step to the CI job would close the gap. Relevance: low. Confidence: high. Fixed in 9e77ac0: CI now generates these locales on Linux, the money tests run there without skips, and codecov/patch passes (90.10%).
  • src/PqColumnDataSource.cpp#L195: strtod() follows the client's LC_NUMERIC. With Sys.setlocale("LC_NUMERIC", "de_DE.UTF-8"), which R itself warns against, float8 1.5 is read as 1, as it was on main with atof(). This is not a regression. Relevance: low. Confidence: high.

main already has the same printf-format problem in DbColumn::warn_type_conflicts(). That is being fixed in its own issue and PR, not here.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

codecov/patch reports 72.52% of the diff covered against a target of 83.13%, and it is the only failing check. The uncovered lines are the parse_money() branches for non-C locales and the per-column warning. The tests that exercise them need ja_JP, ar_KW and similar locales on the server. CI doesn't install those locales, so it skips the tests; locally, with the locales installed, they pass without skips. This is the second item in the accepted limitations. Adding a localedef step to the CI job would close the gap. That is a workflow change, so it would go into its own PR.


Generated by Claude Code

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Install locales in CI to fix coverage.

The money tests set lc_monetary to locales that a stock Ubuntu runner lacks,
so CI skipped all of them but C and en_US,
including every test of the warning for ambiguous values.
The Linux runners now generate these locales before PostgreSQL starts.
Windows names its locales differently, so the tests still skip there.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Hr1rd5LPjEzyaTRpXAuS6g
@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Can we instruct libpq to return money as decimal?

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Not per type, as far as I can tell. libpq chooses text or binary for a whole result (PQexecParams()'s resultFormat), never per column, and there is no setting that changes how money is formatted as text. The text output always follows the server's lc_monetary. In binary format, money arrives as an int64 count of the smallest currency unit, so the client still has to know how many fractional digits the locale uses. RPostgres reads everything as text, so switching to binary would be a much larger change.

The server does convert correctly, though. I checked on PostgreSQL 16:

  • with ja_JP, 1234.5::money prints as ¥1,235 and ::numeric gives 1235;
  • with ar_KW, 12.345::money prints as د.ك. 12.345 and ::numeric gives 12.345;
  • with C, 12.34::money prints as $12.34 and ::numeric gives 12.34.

This suggests a robust fix without the ambiguity. When a result has a money column, ask the server once for the number of fractional digits, for example with SELECT (1::money)::numeric::text and counting the decimals. Then parse the money text as "sign plus all digits, divided by 10^frac_digits". The money text always shows exactly frac_digits fraction digits, so separators and symbols no longer matter, and ja_JP and ar_KW come out right.

The cost is one extra round trip, only for results that contain a money column. The query has to run per result rather than per connection, because lc_monetary can change with SET and libpq doesn't report it. The probe also has to run before the result is fetched, and it touches the result code in PqResultImpl.cpp, which #638 and the ALTREP work also change.

Workaround today: SELECT amount::numeric.

Should I switch #659 to the probe? I'd do it after #638 merges, so the change sits on the new fetch loop.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Done: CI on Linux now generates the locales the money tests use, before PostgreSQL starts (9e77ac0, in .github/workflows/custom/before-install). On that commit, the smoke test and the coverage run report no money-test skips, and codecov/patch passes at 90.10%. Windows names its locales differently, so the money tests still skip there.


Generated by Claude Code

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Accepted limitations

These limitations remain after three rounds of clean review.

  • src/PqColumnDataSource.cpp (parse_money()): in locales with 0 or 3 fractional digits, ordinary amounts come back as NA with one warning per column. Examples are ja_JP (¥1,000 to ¥999,999), ar_KW (1.000 to 999.999), is_IS and vi_VN, about 32 glibc locales in all. The text alone cannot tell a thousands separator from a decimal separator there. This is documented in ?postgres-query, under "Money". The fix, probing the server's money format, is an option in the question above. Relevance: medium for users in those locales. Confidence: high. (recorded)
  • tests/testthat/test-money.R: the tests for the %-safe warning and for "no warning on peek" need the ja_JP locale on the server. CI doesn't set that locale up, so CI skips them. They passed locally, with no skips, on a cluster that has ja_JP. No value triggers the warning in the C, en_US or de_DE locales. Adding a localedef step to the CI job would close the gap. Relevance: low. Confidence: high. Fixed in 9e77ac0: CI now generates these locales on Linux, the money tests run there without skips, and codecov/patch passes (90.10%).
  • src/PqColumnDataSource.cpp#L195: strtod() follows the client's LC_NUMERIC. With Sys.setlocale("LC_NUMERIC", "de_DE.UTF-8"), which R itself warns against, float8 1.5 is read as 1, as it was on main with atof(). This is not a regression. Relevance: low. Confidence: high.

The same printf-format problem in DbColumn::warn_type_conflicts() on main was fixed separately in #665 (merged).


Generated by Claude Code

@krlmlr

krlmlr commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

@krlmlr krlmlr closed this Nov 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

money columns are read as 0

2 participants