-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathddb_ops.R
192 lines (182 loc) · 5.91 KB
/
ddb_ops.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
# ddb_ops.R
# ::rtemis::
# 2022-3 EDG rtemis.org
#' Read CSV using DuckDB
#'
#' Lazy-read a CSV file, optionally filter rows, remove duplicates,
#' clean column names, convert character to factor, and collect.
#'
#' @param filename Character: file name; either full path or just the file name,
#' if `datadir` is also provided
#' @param datadir Character: Optional path if `filename` is not full path
#' @param sep Character: Field delimiter/separator
#' @param header Logical: If TRUE, first line will be read as column names
#' @param quotechar Character: Quote character
#' @param ignore_errors Logical: If TRUE, ignore parsing errors (sometimes it's
#' either this or no data, so)
#' @param make_unique Logical: If TRUE, keep only unique rows
#' @param select_columns Character vector: Column names to select
#' @param filter_column Character: Name of column to filter on, e.g. "ID"
#' @param filter_vals Numeric or Character vector: Values in
#' `filter_column` to keep.
#' @param character2factor Logical: If TRUE, convert character columns to
#' factors
#' @param collect Logical: If TRUE, collect data and return structure class
#' as defined by `returnobj`
#' @param progress Logical: If TRUE, print progress (no indication this works)
#' @param returnobj Character: "data.frame" or "data.table" object class to
#' return. If "data.table", data.frame object returned from
#' `DBI::dbGetQuery` is passed to `data.table::setDT`; will add to
#' execution time if very large, but then that's when you need a data.table
#' @param data.table.key Character: If set, this correspond to a column name in the
#' dataset. This column will be set as key in the data.table output
#' @param clean_colnames Logical: If TRUE, clean colnames with
#' [clean_colnames]
#' @param verbose Logical: If TRUE, print messages to console
#'
#' @author E.D. Gennatas
#' @export
#' @examples \dontrun{
#' ir <- ddb_data("/Data/massive_dataset.csv",
#' filter_column = "ID",
#' filter_vals = 8001:9999
#' )
#' }
ddb_data <- function(filename,
datadir = NULL,
sep = ",",
header = TRUE,
quotechar = "",
ignore_errors = TRUE,
make_unique = TRUE,
select_columns = NULL,
filter_column = NULL,
filter_vals = NULL,
character2factor = FALSE,
collect = TRUE,
progress = TRUE,
returnobj = c("data.table", "data.frame"),
data.table.key = NULL,
clean_colnames = TRUE,
verbose = TRUE) {
# Intro ----
dependency_check("DBI", "duckdb")
returnobj <- match.arg(returnobj)
if (!is.null(data.table.key)) returnobj <- "data.table"
path <- if (is.null(datadir)) {
normalizePath(filename)
} else {
file.path(normalizePath(datadir), filename)
}
check_files(path, verbose = FALSE)
fileext <- tools::file_ext(path)
out <- paste(
bold(green("\u25B6")),
ifelse(collect, "Reading", "Lazy-reading"),
hilite(basename(path))
)
if (!is.null(filter_column)) {
out <- paste(
out, bold(green("\u29e8")),
"filtering on", bold(filter_column)
)
}
startTime <- intro(out, verbose = verbose)
distinct <- ifelse(make_unique, "DISTINCT ", NULL)
select <- if (!is.null(select_columns)) {
ls2sel(select_columns)
} else {
"*"
}
# SQL ----
sql <- if (fileext == "parquet") {
paste0(
"SELECT ",
paste0(distinct, select),
" FROM read_parquet('", path, "')"
)
} else {
paste0(
"SELECT ",
paste0(distinct, select),
" FROM read_csv_auto('", path, "',
sep='", sep, "', quote='", quotechar, "',
header=", header, ", ignore_errors=", ignore_errors, ")"
)
}
sql <- if (!is.null(filter_column)) {
vals <- if (is.numeric(filter_vals)) {
paste0(filter_vals, collapse = ", ")
} else {
paste0("'", paste0(filter_vals, collapse = "', '"), "'")
}
paste(
sql,
"WHERE", filter_column, "in (", vals, ");"
)
} else {
paste0(sql, ";")
}
# Collect ----
if (collect) {
conn <- DBI::dbConnect(duckdb::duckdb())
on.exit(DBI::dbDisconnect(conn, shutdown = TRUE))
# on.exit(
# tryCatch(DBI::dbRollback(conn), error = function(e) {
# }))
if (progress) DBI::dbExecute(conn, "PRAGMA enable_progress_bar;")
out <- DBI::dbGetQuery(conn, sql)
if (clean_colnames) {
names(out) <- clean_colnames(out)
}
if (returnobj == "data.table") {
data.table::setDT(out)
if (!is.null(data.table.key)) {
data.table::setkeyv(out, data.table.key)
}
}
if (character2factor) {
out <- preprocess(out, character2factor = TRUE)
}
} else {
out <- sql
}
# Outro ----
outro(startTime, verbose = verbose)
out
} # rtemis::ddb_data
# output: '"alpha", "beta", "gamma"'
ls2sel <- function(x) {
paste0(
'"', paste0(x, collapse = '", "'), '"'
)
}
#' Collect a lazy-read duckdb table
#'
#' Collect a table read with `ddb_data(x, collect = FALSE)`
#'
#' @param sql Character: DuckDB SQL query, usually output of
#' [ddb_data] with `collect = FALSE`
#' @param progress Logical: If TRUE, show progress bar
#' @param returnobj Character: data.frame or data.table: class of object to return
#'
#' @author E.D. Gennatas
#' @export
#' @examples
#' \dontrun{
#' sql <- ddb_data("/Data/iris.csv", collect = FALSE)
#' ir <- ddb_ollect(sql)
#' }
ddb_collect <- function(sql,
progress = TRUE,
returnobj = c("data.frame", "data.table")) {
returnobj <- match.arg(returnobj)
conn <- DBI::dbConnect(duckdb::duckdb())
on.exit(DBI::dbDisconnect(conn, shutdown = TRUE))
if (progress) DBI::dbExecute(conn, "PRAGMA enable_progress_bar;")
out <- DBI::dbGetQuery(conn, sql)
if (returnobj == "data.table") {
setDT(out)
}
out
} # rtemis::ddb_collect