-
Notifications
You must be signed in to change notification settings - Fork 6
/
dbQueryHistory.R
90 lines (81 loc) · 2.21 KB
/
dbQueryHistory.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
### ctrdata package
#' Show history of queries loaded into a database collection
#'
#' @inheritParams ctrDb
#'
#' @return A data frame (or tibble, if \code{tibble} is loaded)
#' with columns: `query-timestamp`, `query-register`,
#' `query-records` (note: this is the number of records loaded when last
#' executing \link{ctrLoadQueryIntoDb}, not the total record number) and
#' `query-term`, with one row for each time that
#' \link{ctrLoadQueryIntoDb} loaded trial records into this collection.
#'
#' @param verbose If \code{TRUE}, prints additional information
#' (default \code{FALSE}).
#'
#' @importFrom nodbi docdb_query
#' @importFrom tibble as_tibble
#'
#' @export
#'
#' @examples
#'
#' dbc <- nodbi::src_sqlite(
#' dbname = system.file("extdata", "demo.sqlite", package = "ctrdata"),
#' collection = "my_trials"
#' )
#'
#' dbQueryHistory(con = dbc)
#'
dbQueryHistory <- function(con, verbose = FALSE) {
## check database connection
if (is.null(con$ctrDb)) con <- ctrDb(con = con)
# debug
if (verbose) message("Running dbQueryHistory ...")
hist <- nodbi::docdb_query(
src = con,
key = con$collection,
query = '{"_id": {"$eq": "meta-info"}}',
fields = '{"queries": 1, "_id": 0}'
)
# check if meeting expectations
if (is.null(hist) ||
nrow(hist) == 0L) {
#
message("No history found in expected format.")
#
# return (class data.frame is expected)
return(invisible(data.frame(NULL)))
#
}
# access data frame of queries
hist <- hist[["queries"]]
if (!is.data.frame(hist)) hist <- hist[[1]]
# inform user
if (verbose) {
message(
"Number of queries in history of \"",
con$collection, "\": ", nrow(hist)
)
# total number of records in collection
# use fast queries for _id's only
countall <- length(nodbi::docdb_query(
src = con,
key = con$collection,
query = "{}",
fields = '{"_id": 1}'
)[["_id"]])
countall <- countall[countall != "meta-info"]
# inform user
message(
"Number of records in collection \"",
con$collection, "\": ", countall
)
}
# return
if (any("tibble" == .packages())) {
return(tibble::as_tibble(hist))
}
return(hist)
}
# end ctrQueryHistoryInDb