-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.R
81 lines (66 loc) · 1.64 KB
/
db.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
library(DBI)
library(RPostgres)
library(httr)
library(glue)
db_uri <- Sys.getenv('DATABASE_URL')
parts <- parse_url(db_uri)
conn <- function() {
dbConnect(
RPostgres::Postgres(),
host = parts$hostname,
port = parts$port,
user = parts$user,
password = parts$password,
dbname = parts$path
)
}
create_games <- function() {
db <- conn()
dbExecute(db, "
CREATE TABLE games (
date DATE
, user_id BIGINT
, history VARCHAR
, ui VARCHAR
)")
}
get_games <- function() {
db <- conn()
res <- dbGetQuery(db, "select * from games")
dbDisconnect(db)
res
}
get_user_results <- function(date, user_id) {
db <- conn()
res <- dbGetQuery(db, glue("select * from games where date = '{date}' and user_id = {user_id}"))
if(nrow(res) == 0) {
dbAppendTable(db,
"games",
tibble(
date = date,
user_id = user_id,
history = rawToChar(serialize(NA, connection = NULL, ascii = TRUE)),
ui = NA
)
)
dbDisconnect(db)
return(NA)
# return(get_user_results(date, user_id))
} else {
dbDisconnect(db)
return(res)
}
}
update_user_results <- function(date, user_id, history, ui) {
db <- conn()
clean_ui <- gsub("'", "''", ui)
clean_history <- history %>% serialize(NULL, ascii=TRUE) %>% rawToChar()
dbExecute(db,
glue("
UPDATE games
SET history = '{clean_history}', ui = '{clean_ui}'
WHERE date = '{date}' and user_id = {user_id}
")
)
dbDisconnect(db)
}