Skip to content

Support SQL translations #40

@mgirlich

Description

@mgirlich

Add dbplyr like translations.

  1. Make it work for tbl_lazy
lazy_frame(json = 1, con = simulate_postgres()) %>% 
  mutate(x = json_extract(x, "a", 1))
  • add json_extract_sql(..., con)
con <- simulate_postgres()
lazy_frame(json = 1, con = con) %>% 
  mutate(x = !!json_extract_sql(x, "a", 1, con = con))
  1. Some arguments are not so nice to translate or restricted, in json_flatten() for example ptype is rather restricted and allow_scalars and wrap_scalars require quite a bit of extra SQL.

  2. In PostgreSQL there is no nice and easy way to translate JSON true and false to integer.

Example for a quick and dirty Postgres translation:

library(dplyr, warn.conflicts = FALSE)
library(dbplyr)
devtools::load_all("~/GitHub/jsontools/")

lazy_frame(json = 1, con = simulate_postgres()) %>% 
  mutate(x = json_extract(x, "a", 1))
#> <SQL>
#> SELECT `json`, CAST((`x` #>> 'a') AS NUMERIC) AS `x`
#> FROM `df`
lazy_frame(json = 1, con = simulate_postgres()) %>% 
  mutate(x = json_extract(x, "a", !!new_json_array(), wrap_scalars = TRUE))
#> <SQL>
#> SELECT `json`, CASE WHEN (type_of(`x` #>> 'a') IN ('object', 'array')) THEN (`x` #>> 'a') WHEN NOT(type_of(`x` #>> 'a') IN ('object', 'array')) THEN (json_build_array(`x` #>> 'a')) END AS `x`
#> FROM `df`

lazy_frame(json = 1, con = simulate_postgres()) %>% 
  mutate(x = json_flatten(x, "a", 1))
#> <SQL>
#> SELECT `json`, json_array_elements_text(`x`) AS `x`
#> FROM `df`
lazy_frame(json = 1, con = simulate_postgres()) %>% 
  mutate(x = json_flatten(x, 1, 1))
#> <SQL>
#> SELECT `json`, CAST((json_array_elements_text(`x`)) AS NUMERIC) AS `x`
#> FROM `df`

Created on 2021-03-26 by the reprex package (v1.0.0)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions