Last active
October 16, 2024 22:44
-
-
Save sckott/35ef6ec03cd0fe848742c0c947e88457 to your computer and use it in GitHub Desktop.
Privileges with dbplyr/dplyr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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