forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.r
75 lines (62 loc) · 1.63 KB
/
query.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
#' Create a mutable query object.
#'
#' A query object is mutable wrapper around a \code{DBIResult} that caches
#' expensive operations, and insulates the rest of dplyr from the vagaries of
#' DBI and the individual database implementation.
#'
#' @keywords internal
#' @param con a \code{DBOConnection}
#' @param sql a string containing an sql query.
#' @export
query <- function(con, sql, .vars) UseMethod("query")
#' @export
query.DBIConnection <- function(con, sql, .vars) {
assert_that(is.string(sql))
Query$new(con, sql(sql), .vars)
}
Query <- R6::R6Class("Query",
private = list(
.nrow = NULL,
.vars = NULL
),
public = list(
con = NULL,
sql = NULL,
initialize = function(con, sql, vars) {
self$con <- con
self$sql <- sql
private$.vars <- vars
},
print = function(...) {
cat("<Query> ", self$sql, "\n", sep = "")
print(self$con)
},
fetch = function(n = -1L) {
res <- dbSendQuery(self$con, self$sql)
on.exit(dbClearResult(res))
out <- dbFetch(res, n)
res_warn_incomplete(res)
out
},
fetch_paged = function(chunk_size = 1e4, callback) {
qry <- dbSendQuery(self$con, self$sql)
on.exit(dbClearResult(qry))
while (!dbHasCompleted(qry)) {
chunk <- dbFetch(qry, chunk_size)
callback(chunk)
}
invisible(TRUE)
},
vars = function() {
private$.vars
},
nrow = function() {
if (!is.null(private$.nrow)) return(private$.nrow)
private$.nrow <- db_query_rows(self$con, self$sql)
private$.nrow
},
ncol = function() {
length(self$vars())
}
)
)