Skip to content

Instantly share code, notes, and snippets.

@sckott
Last active October 16, 2024 22:44
Show Gist options
  • Save sckott/35ef6ec03cd0fe848742c0c947e88457 to your computer and use it in GitHub Desktop.
Save sckott/35ef6ec03cd0fe848742c0c947e88457 to your computer and use it in GitHub Desktop.
Privileges with dbplyr/dplyr
library(DBI)
library(RPostgres)
library(dplyr)
library(dbplyr)
con <- dbConnect(Postgres())
dbExecute(con, "CREATE ROLE admin")
dbExecute(con, "CREATE ROLE alice")
orange <- setNames(Orange, tolower(names(Orange)))
copy_to(con, orange, "orange", temporary = FALSE)
dbExecute(con, "GRANT SELECT ON orange TO admin")
dbExecute(con, "GRANT SELECT (tree, circumference) ON orange TO public")
## User: admin
dbExecute(con, "SET SESSION AUTHORIZATION admin")
# fine
head(tbl(con, "orange"))
#> # Source: SQL [6 x 3]
#> # Database: postgres [user@/tmp:5432/user]
#> tree age circumference
#> <chr> <dbl> <dbl>
#> 1 1 118 30
#> 2 1 484 58
#> 3 1 664 87
#> 4 1 1004 115
#> 5 1 1231 120
#> 6 1 1372 142
## User: alice
dbExecute(con, "SET SESSION AUTHORIZATION alice")
# this works fine
head(dbGetQuery(con, "SELECT tree, circumference FROM orange"))
#> tree circumference
#> 1 1 30
#> 2 1 58
#> 3 1 87
#> 4 1 115
#> 5 1 120
#> 6 1 142
# this does not work
tbl(con, "orange")
#> Error in `db_query_fields.DBIConnection()`:
#> ! Can't query fields.
#> ℹ Using SQL: SELECT * FROM "orange" AS "q01" WHERE (0 = 1)
#> Caused by error:
#> ! Failed to fetch row : ERROR: permission denied for table orange
# nor this
tbl(con, "orange") %>% select(tree, circumference)
#> Error in `db_query_fields.DBIConnection()`:
#> ! Can't query fields.
#> ℹ Using SQL: SELECT * FROM "orange" AS "q02" WHERE (0 = 1)
#> Caused by error:
#> ! Failed to fetch row : ERROR: permission denied for table orange
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment