Skip to content

Redshift round() can't return decimal places #1033

@owenjonesuob

Description

@owenjonesuob

Redshift's numeric (== decimal) type has a default scale (number of decimal places) of 0, so naively casting values to numeric can lead to surprising results.

The Redshift backend already guards against this, by instead casting to float:

as.numeric = sql_cast("FLOAT"),

However the Postgres backend, which the Redshift backend inherits from, uses a custom function for its translation of round(), which contains an explicit cast to numeric:

postgres_round <- function(x, digits = 0L) {
  digits <- as.integer(digits)
  sql_expr(round(((!!x)) %::% numeric, !!digits))
}

This means we end up with the following SQL translation:

translate_sql(round(1.234, 1), con = simulate_redshift())
#> <SQL> ROUND((1.234) :: numeric, 1)

This always:

  • Implicitly rounds to 0 decimal places, via the cast to numeric
  • Then, explicitly rounds the result to the specified number of decimal places, meaning we end up with at best 0dp

Hopefully an easy fix by overriding round in the Redshift translator with a small round_redshift() function - I'll add a pull request shortly!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions