/
expdb_db.R
259 lines (240 loc) · 8.53 KB
/
expdb_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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# * Author: Bangyou Zheng (Bangyou.Zheng@csiro.au)
# * Created: 8:54 AM Wednesday, 22 August 2012
# * Copyright: AS IS
# *
# Connect and disconnect to expDB
#' Connect to expDB
#' @param filename The filename of SQLite
#' @return a connection object as produced by dbConnect
#' @examples
#' \dontrun{
#' con <- connect('filename')
#' }
#' @export
expdbConnect <- function(filename)
{
if (is.null(filename)) {
# host <- Sys.getenv('EXPDB_MYSQL_HOST')
# if (nchar(host) == 0) {
# stop('Set environment variable "EXPDB_MYSQL_HOST" to specify to host name in a mysql server')
# }
#
# db_name <- Sys.getenv('EXPDB_MYSQL_DB')
# if (nchar(db_name) == 0) {
# stop('Set environment variable "EXPDB_MYSQL_DB" to specify to database name in a mysql server')
# }
#
# user <- Sys.getenv('EXPDB_MYSQL_USER')
# if (nchar(user) == 0) {
# stop('Set environment variable "EXPDB_MYSQL_USER" to specify to user name in a mysql server')
# }
#
# password <- Sys.getenv('EXPDB_MYSQL_PASSWORD')
# if (nchar(db_name) == 0) {
# stop('Set environment variable "EXPDB_MYSQL_PASSWORD" to specify to password name in a mysql server')
# }
#
# con <- dbConnect(
# RMySQL::MySQL(),
# dbname = db_name, host = host,
# port = 3306,
# username = user,
# password = password)
} else {
if (!file.exists(filename))
{
stop('Cannot find the SQLite database')
}
m <- RSQLite::dbDriver("SQLite")
con <- RSQLite::dbConnect(m, dbname = filename)
}
return(con)
}
#' Didconnect to expDB
#' @param con a connection object as produced by dbConnect.
#' @examples
#' \dontrun{
#' con <- connect('filename')
#' disconnect(con)
#' }
#' @return no return values
#' @export
expdbDisconnect <- function(con)
{
invisible(RSQLite::dbDisconnect(con))
}
#' Append a table into db and check the column name
#'
#' @param con A connection object as produced by dbConnect
#' @param table The target table name
#' @param data A data frame to write into table
dbAppendTable <- function(con, table, data)
{
dbcols <- DBI::dbListFields(con, table)
data <- data[, names(data) %in% dbcols]
data <- data[, match(dbcols, names(data))]
DBI::dbWriteTable(con, table, data,
append = TRUE, row.names = FALSE)
}
#' Insert new rows or update existing rows to a specific table according to a specific column (unique) by each row
#'
#' @param con A connection object as produced by dbConnect
#' @param table The target table name
#' @param data A data frame to write into table
#' @param unique_col A character vector to indentify each row in the table
dbInsertUpdateByRow <- function(con, table, data, unique_col = 'name')
{
if (sum(unique_col %in% names(data)) != length(unique_col))
{
stop(paste('column(s) "',
paste(unique_col, collapse = ', '),
'" must be in the input data.frame', sep = ''))
}
# check columns
dbcols <- DBI::dbListFields(con, table)
e_cols <- names(data) %in% dbcols
if(sum(!e_cols) > 0)
{
warning(paste(names(data)[!e_cols], collapse = ', '),
' do not exist in the table ',
table, sep = '')
data <- data[,e_cols]
}
unique_id <- getIdByUniqueIndex(con, table, data, unique_col)
insert_pos <- is.na(unique_id)
sql <- NULL
if (sum(insert_pos) > 0)
{
col_names <- paste(paste0('`', names(data), '`'), collapse = ', ')
new_values <- apply(as.data.frame(data[insert_pos,]), 1, function(x) {
paste(paste(
ifelse(is.na(x), 'NULL',
paste('"', x, '"', sep = '')), sep = ''),
collapse = ', ')
})
sql_insert <- sprintf('INSERT INTO %s (%s) VALUES (%s)', table, col_names, new_values)
sql <- c(sql, sql_insert)
}
data_col <- !(names(data) %in% unique_col)
if (sum(!insert_pos) > 0 & sum(data_col) > 0)
{
temp <- as.data.frame(data[!insert_pos,data_col])
names(temp) <- names(data)[!(names(data) %in% unique_col)]
new_values <- apply(temp, 1, function(x) {
paste(paste('`', names(x), '`', '=',
ifelse(is.na(x), 'NULL',
paste('"', x, '"', sep = '')),
sep = ''),
collapse = ', ')
})
where <- paste('id = ', unique_id[!insert_pos], sep = '')
sql_update <- sprintf('UPDATE %s SET %s WHERE %s', table, new_values, where)
sql <- c(sql, sql_update)
}
if (!is.null(sql))
{
DBI::dbBegin(con)
for (i in seq(along = sql))
{
res <- DBI::dbSendQuery(con, sql[i])
DBI::dbClearResult(res)
}
success <- DBI::dbCommit(con)
return(success)
}
return (TRUE)
}
#' Get index id by unique_columns.
#' @param con a connection object as produced by dbConnect
#' @param table the table name
#' @param data A data frame to write into table
#' @param unique_col A character vector to identify each row in the table
#' @param data_col The column names in the data.frame
#' @param ignore_case Whether ignore_case
#' @return id of unique_col
getIdByUniqueIndex <- function(con, table, data,
unique_col = 'name', data_col = unique_col,
ignore_case = FALSE)
{
if ('character' %in% class(data) & length(unique_col) == 1)
{
temp <- as.list(NULL)
temp[[unique_col]] <- data
data <- as.data.frame(temp)
}
if (ignore_case)
{
for (i in seq(along = data_col))
{
data[[data_col[i]]] <- tolower(data[[data_col[i]]])
}
}
vls <- apply(as.data.frame(data[,data_col]), 2, function(x)
{
paste(paste('"', x, '"', sep = ''), collapse = ',')
})
if (ignore_case)
{
where <- paste(paste('LOWER(', unique_col, ') in (',
vls, ')', sep = ''), collapse = ' AND ')
case <- switch(class(con),
'MySQLConnection' = '',
'SQLiteConnection' = ' COLLATE NOCASE'
)
where <- paste0(where, case)
sql <- sprintf('SELECT id, %s from %s WHERE %s',
paste('LOWER(', unique_col, ') AS ', unique_col, collapse = ','),
table, where)
} else
{
case <- switch(class(con),
'MySQLConnection' = ' COLLATE latin1_general_cs',
'SQLiteConnection' = ''
)
where <- paste(paste(unique_col, case, ' in (',
vls, ')', sep = ''), collapse = ' AND ')
sql <- sprintf('SELECT id, %s from %s WHERE %s',
paste(unique_col, collapse = ','),
table, where)
}
res <- DBI::dbGetQuery(con, sql)
res <- merge(data, res, by.x = data_col,
by.y = unique_col, sort = FALSE, all.x = TRUE)
id <- res$id[match(apply(as.data.frame(data[,data_col]), 1, paste, collapse = ''),
apply(as.data.frame(res[,data_col]), 1, paste, collapse = ''))]
return(id)
}
#' create to expDB
#' @param filename The filename of new expDB
#' @param system_traits Whether to import system traits
#' @return a connection object as produced by dbConnect
#' @export
expdbCreateDB <- function(filename, system_traits = TRUE)
{
db <- DBI::dbConnect(RSQLite::SQLite(), dbname = ":memory:")
sql <- readLines(system.file('expdbDefault.txt', package = 'expDB'))
sql <- paste(sql, collapse = '\n')
sql <- unlist(strsplit(sql, ';'))
sql <- gsub('\t+', '', sql)
sql <- gsub('\n+', '', sql)
sql <- sql[nchar(sql) > 0]
# sql <- append(sql,
# sprintf('INSERT INTO expdb_history (date,comments) VALUES ("%s","Create the new database")',
# format(Sys.time(), format='%Y-%m-%d')))
DBI::dbBegin(db)
for (i in seq(along = sql))
{
res <- DBI::dbSendQuery(db, sql[i])
DBI::dbClearResult(res)
}
success <- DBI::dbCommit(db)
# Copy database from memory to file
RSQLite::sqliteCopyDatabase(db, filename)
DBI::dbDisconnect(db)
db <- DBI::dbConnect(RSQLite::SQLite(), filename)
if (system_traits) {
traits <- utils::read.csv(system_file('meta/dbtraits.csv', 'expDB'))
dbAddTraits(db, traits)
}
return(db)
}