forked from tidyverse/dplyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexplain.r
62 lines (56 loc) · 1.71 KB
/
explain.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
#' Explain details of a tbl.
#'
#' This is a generic function which gives more details about an object than
#' \code{\link{print}}, and is more focussed on human readable output than
#' \code{\link{str}}.
#'
#' @section Databases:
#' Explaining a \code{tbl_sql} will run the SQL \code{EXPLAIN} command which
#' will describe the query plan. This requires a little bit of knowledge about
#' how \code{EXPLAIN} works for your database, but is very useful for
#' diagnosing performance problems.
#'
#' @export
#' @param x An object to explain
#' @param ... Other parameters possibly used by generic
#' @examples
#' \donttest{
#' if (require("RSQLite") && has_lahman("sqlite")) {
#'
#' lahman_s <- lahman_sqlite()
#' batting <- tbl(lahman_s, "Batting")
#' batting %>% show_query()
#' batting %>% explain()
#'
#' # The batting database has indices on all ID variables:
#' # SQLite automatically picks the most restrictive index
#' batting %>% filter(lgID == "NL" & yearID == 2000L) %>% explain()
#'
#' # OR's will use multiple indexes
#' batting %>% filter(lgID == "NL" | yearID == 2000) %>% explain()
#'
#' # Joins will use indexes in both tables
#' teams <- tbl(lahman_s, "Teams")
#' batting %>% left_join(teams, c("yearID", "teamID")) %>% explain()
#' }
#' }
explain <- function(x, ...) {
UseMethod("explain")
}
#' @export
explain.tbl_sql <- function(x, ...) {
force(x)
show_query(x)
con <- con_acquire(x$src)
on.exit(con_release(x$src, con), add = TRUE)
message("\n")
message("<PLAN>\n", db_explain(con, sql_render(x, con = con)))
invisible(NULL)
}
#' @export
#' @rdname explain
show_query <- function(x) {
con <- con_acquire(x$src)
on.exit(con_release(x$src, con), add = TRUE)
message("<SQL>\n", sql_render(x, con = con))
}