-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtable_source.R
More file actions
402 lines (366 loc) · 12.5 KB
/
table_source.R
File metadata and controls
402 lines (366 loc) · 12.5 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#' Make a table description directly.
#'
#' Build minimal structures (table name and column names) needed to represent data from a remote table.
#'
#' Generate a query that returns contents of a table, we
#' could try to eliminate this (replace the query with the table name),
#' but there are features one can work with with the query in place and
#' SQL optimizers likely make this zero-cost anyway.
#'
#' @param table_name character, name of table
#' @param columns character, column names of table (non-empty and unique values).
#' @param ... not used, force later argument to bind by name
#' @param qualifiers optional named ordered vector of strings carrying additional db hierarchy terms, such as schema.
#' @param q_table_name optional character, qualified table name, note: has to be re-generated for different DB connections.
#' @param head_sample optional, head_sample of table as an example
#' @param limit_was optional, row limit used to produce head_sample.
#' @return a relop representation of the data
#'
#' @seealso \code{\link{db_td}}, \code{\link{local_td}}
#'
#' @examples
#'
#' if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) {
#' my_db <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
#' rq_copy_to(my_db,
#' 'd',
#' data.frame(AUC = 0.6, R2 = 0.2),
#' overwrite = TRUE,
#' temporary = TRUE)
#' d <- mk_td('d',
#' columns = c("AUC", "R2"))
#' print(d)
#' sql <- to_sql(d, my_db)
#' cat(sql)
#' print(DBI::dbGetQuery(my_db, sql))
#' DBI::dbDisconnect(my_db)
#' }
#'
#' @seealso \code{\link{db_td}}, \code{\link{local_td}}, \code{\link{rq_copy_to}}, \code{\link{materialize}}, \code{\link{execute}}, \code{\link{to_sql}}
#'
#' @export
#'
mk_td <- function(table_name, columns,
...,
qualifiers = NULL,
q_table_name = NULL,
head_sample = NULL,
limit_was = NULL) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::mk_td")
if(is.null(table_name)) {
stop("rquery::mk_td called with NULL table_name")
}
if(is.null(q_table_name)) {
q_table_name <- table_name
}
if((length(columns)<=0) || (!is.character(columns))) {
stop("rquery::mk_td columns must be a non-empty character vector")
}
if(length(columns)!=length(unique(columns))) {
stop("rquery::mk_td columns must be unique")
}
if(!is.null(head_sample)) {
diff = setdiff(union(columns, colnames(head_sample)), intersect(columns, colnames(head_sample)))
if(length(diff) > 0) {
stop(paste("wrapr::mk_td columns and colnames(head_sample) disagree", paste(diff, collapse = ', ')))
}
}
r <- list(source = list(),
table_name = table_name,
q_table_name = q_table_name,
parsed = NULL,
columns = columns,
qualifiers = qualifiers,
head_sample = head_sample,
limit_was = limit_was)
r <- relop_decorate("relop_table_source", r)
r
}
#' @describeIn mk_td old name for mk_td
#' @export
table_source <- mk_td
#' Construct a table description from a database source.
#'
#' Build structures (table name, column names, and quoting
#' strategy) needed to represent data from a remote table.
#'
#' Note: in examples we use \code{rq_copy_to()} to create data. This is only for the purpose of having
#' easy portable examples. With big data the data is usually already in the remote database or
#' Spark system. The task is almost always to connect and work with this pre-existing remote data
#' and the method to do this is \code{db_td}
#' which builds a reference to a remote table given the table name.
#'
#'
#' @param db database connection
#' @param table_name name of table
#' @param ... not used, force later argument to bind by name
#' @param qualifiers optional named ordered vector of strings carrying additional db hierarchy terms, such as schema.
#' @param limit_was optional, row limit used to produce head_sample. If NULL no head_sample is produced and rq_colnames is used to get column names.
#' @return a relop representation of the data
#'
#' @seealso \code{\link{mk_td}}, \code{\link{local_td}}, \code{\link{rq_copy_to}}, \code{\link{materialize}}, \code{\link{execute}}, \code{\link{to_sql}}
#'
#' @examples
#'
#' if (requireNamespace("DBI", quietly = TRUE) && requireNamespace("RSQLite", quietly = TRUE)) {
#' my_db <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
#' rq_copy_to(my_db,
#' 'd',
#' data.frame(AUC = 0.6, R2 = 0.2),
#' overwrite = TRUE,
#' temporary = TRUE)
#' d <- db_td(my_db, 'd')
#' print(d)
#' sql <- to_sql(d, my_db)
#' cat(sql)
#' print(DBI::dbGetQuery(my_db, sql))
#' cols <- columns_used(d)
#' print(cols)
#'
#' sql2 <- to_sql(d, my_db, using = "AUC")
#' cat(sql2)
#' print(DBI::dbGetQuery(my_db, sql2))
#' DBI::dbDisconnect(my_db)
#' }
#'
#' @export
#'
db_td <- function(db, table_name,
...,
qualifiers = NULL,
limit_was = 6L) {
q_table_name <- quote_table_name(db, table_name, qualifiers = qualifiers)
if((length(limit_was) == 1) && getDBOption(db, "rquery_sample_on_db_td", TRUE)) {
head_sample = rq_head(db, table_name, qualifiers = qualifiers)
columns = colnames(head_sample)
} else {
head_sample = NULL
limit_was = NULL
columns = rq_colnames(db, table_name, qualifiers = qualifiers)
}
mk_td(table_name = table_name,
columns = columns,
q_table_name = q_table_name,
qualifiers = qualifiers,
head_sample = head_sample,
limit_was = limit_was)
}
#' @describeIn db_td old name for db_td
#' @export
dbi_table <- db_td
#' Construct a table description of a local data.frame.
#'
#' @param d data.frame or name of data.frame to use as a data source.
#' @param ... not used, force later arguments to be optional.
#' @param name if not null name to user for table.
#' @param name_source temporary name source.
#' @param env environment to work in.
#' @return a relop representation of the data
#'
#' @seealso \code{\link{db_td}}, \code{\link{mk_td}}
#'
#' @examples
#'
#' d <- data.frame(x = 1)
#' local_td(d)
#' local_td("d")
#' local_td(as.name("d"))
#' local_td(data.frame(x = 1))
#' d %.>% local_td # needs wrapr 1.5.0 or newer to capture name
#'
#' @export
#'
local_td <- function(d,
...,
name = NULL,
name_source = wrapr::mk_tmp_name_source("rqltd"),
env = parent.frame()) {
force(env)
UseMethod("local_td")
}
#' @export
local_td.data.frame <- function(d,
...,
name = NULL,
name_source = wrapr::mk_tmp_name_source("rqltd"),
env = parent.frame()) {
force(env)
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::local_td.data.frame")
table_name <- name
if(is.null(table_name)) {
table_name <- substitute(d)
if(is.name(table_name) || is.character(table_name)) {
table_name <- as.character(table_name)
} else {
table_name = name_source()
}
}
d <- as.data.frame(d)
rownames(d) <- NULL
row_limit = 6L
mk_td(table_name = table_name,
columns = colnames(d),
head_sample = utils::head(d, n = row_limit),
limit_was = row_limit)
}
#' @export
local_td.character <- function(d,
...,
name = NULL,
name_source = wrapr::mk_tmp_name_source("rqltd"),
env = parent.frame()) {
force(env)
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::local_td.character")
table_name <- d
d <- get(table_name, envir = env)
if(!is.data.frame(d)) {
stop("rquery::local_td.character: argument d must be a string that resolves to a data.frame")
}
row_limit = 6L
mk_td(table_name = table_name,
columns = colnames(d),
head_sample = utils::head(d, n = row_limit),
limit_was = row_limit)
}
#' @export
local_td.name <- function(d,
...,
name = NULL,
name_source = wrapr::mk_tmp_name_source("rqltd"),
env = parent.frame()) {
force(env)
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::local_td.name")
table_name <- as.character(d)
d <- get(table_name, envir = env)
if(!is.data.frame(d)) {
stop("rquery::local_td.name: argument d must be a name that resolves to a data.frame")
}
row_limit = 6L
mk_td(table_name = table_name,
columns = colnames(d),
head_sample = utils::head(d, n = row_limit),
limit_was = row_limit)
}
#' @export
tables_used.relop_table_source <- function(node, ...) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::tables_used.relop_table_source")
node$table_name
}
#' @export
column_names.relop_table_source <- function (x, ...) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::column_names.relop_table_source")
x$columns
}
columns_used_relop_table_source <- function (x,
...,
using = NULL) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery:::columns_used_relop_table_source")
cols <- x$columns
if(length(using)>0) {
missing <- setdiff(using, x$columns)
if(length(missing)>0) {
stop(paste("rquery:columns_used request for unknown columns",
paste(missing, collapse = ", ")))
}
cols <- intersect(cols, using)
}
cols
}
#' @export
columns_used.relop_table_source <- function (x, ...,
using = NULL) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::columns_used.relop_table_source")
cols <- columns_used_relop_table_source(x, using = using)
r <- list(cols)
names(r) <- x$table_name
r
}
#' @export
to_sql.relop_table_source <- function (x,
db,
...,
limit = NULL,
source_limit = NULL,
indent_level = 0,
tnum = mk_tmp_name_source('tsql'),
append_cr = TRUE,
using = NULL) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::to_sql.relop_table_source")
dispatch_to_sql_method(
method_name = "to_sql.relop_table_source",
x = x,
db = db,
limit = limit,
source_limit = source_limit,
indent_level = indent_level,
tnum = tnum,
append_cr = append_cr,
using = using)
}
to_sql_relop_table_source <- function(
x,
db,
...,
limit = NULL,
source_limit = NULL,
indent_level = 0,
tnum = mk_tmp_name_source('tsql'),
append_cr = TRUE,
using = NULL) {
wrapr::stop_if_dot_args(substitute(list(...)),
"rquery::to_sql.relop_table_source")
prefix <- paste(rep(' ', indent_level), collapse = '')
tabnam <- quote_table_name(db, x$table_name, qualifiers = x$qualifiers)
cols <- columns_used_relop_table_source(x, using = using)
qcols <- vapply(cols,
function(ui) {
quote_identifier(db, ui)
}, character(1))
qt <- paste(qcols, collapse = paste0(",\n", prefix, " "))
q <- paste0(prefix,
"SELECT\n",
prefix, " ", qt, "\n",
prefix, "FROM\n",
prefix, " ", tabnam)
if((!is.null(limit))||(!is.null(source_limit))) {
limit <- min(limit, source_limit)
q <- paste(q, "LIMIT",
format(ceiling(limit), scientific = FALSE))
}
if(append_cr) {
q <- paste0(q, "\n")
}
q
}
#' @export
format_node.relop_table_source <- function(node) {
max_cols <- 20
cols <- paste0('"', node$columns, '"')
if(length(cols)>max_cols) {
cols <- c(cols[seq_len(max_cols)], "...")
}
paste0("mk_td(\"", node$table_name, "\", c(\n ",
paste(cols, collapse = ",\n "),
"))\n")
}
#' @export
print.relop <- function(x, ...) {
txt <- format(x)
txt <- trimws(gsub("[ \t\r\n]+", " ", txt), which = "both")
print(txt, ...)
if(!is.null(x$head_sample)) {
print(x$head_sample)
if(nrow(x$head_sample) >= x$limit_was) {
cat(" ...")
}
}
}