forked from duckdb/duckdb-r
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsv.R
More file actions
234 lines (217 loc) · 6.38 KB
/
Copy pathcsv.R
File metadata and controls
234 lines (217 loc) · 6.38 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
# Explained in handbook/usage/data-import/README.md.
#' Reads a CSV file into DuckDB
#'
#' Directly reads a CSV file into DuckDB, tries to detect and create the correct schema for it.
#' This usually is much faster than reading the data into R and writing it to DuckDB.
#'
#' If the table already exists in the database, the csv is appended to it. Otherwise the table is created.
#'
#' @inheritParams duckdb_register
#' @param files One or more CSV file names, should all have the same structure though
#' @inheritParams rlang::args_dots_empty
#' @param header Whether or not the CSV files have a separate header in the first line
#' @param na.strings Which strings in the CSV files should be considered to be NULL
#' @param nrow.check How many rows should be read from the CSV file to figure out data types
#' @param delim Which field separator should be used
#' @param quote Which quote character is used for columns in the CSV file
#' @param col.names Override the detected or generated column names
#' @param col.types Character vector of column types in the same order as col.names,
#' or a named character vector where names are column names and types pairs.
#' Valid types are [DuckDB data types](https://duckdb.org/docs/sql/data_types/overview.html), e.g. VARCHAR, DOUBLE, DATE, BIGINT, BOOLEAN, etc.
#' @param lower.case.names Transform column names to lower case
#' @param sep Alias for delim for compatibility
#' @param transaction Should a transaction be used for the entire operation
#' @param temporary Set to `TRUE` to create a temporary table
#' @return The number of rows in the resulted table, invisibly.
#' @export
#' @examplesIf identical(Sys.getenv("IN_PKGDOWN"), "true")
#' con <- dbConnect(duckdb())
#'
#' data <- data.frame(a = 1:3, b = letters[1:3])
#' path <- tempfile(fileext = ".csv")
#'
#' write.csv(data, path, row.names = FALSE)
#'
#' duckdb_read_csv(con, "data", path)
#' dbReadTable(con, "data")
#'
#' dbDisconnect(con)
#'
#'
#' # Providing data types for columns
#' path <- tempfile(fileext = ".csv")
#' write.csv(iris, path, row.names = FALSE)
#'
#' con <- dbConnect(duckdb())
#' duckdb_read_csv(con, "iris", path,
#' col.types = c(
#' Sepal.Length = "DOUBLE",
#' Sepal.Width = "DOUBLE",
#' Petal.Length = "DOUBLE",
#' Petal.Width = "DOUBLE",
#' Species = "VARCHAR"
#' )
#' )
#' dbReadTable(con, "iris")
#' dbDisconnect(con)
#'
duckdb_read_csv <- function(
conn,
name,
files,
...,
header = TRUE,
na.strings = "",
nrow.check = 500,
delim = ",",
quote = "\"",
col.names = NULL,
col.types = NULL,
lower.case.names = FALSE,
sep = delim,
transaction = TRUE,
temporary = FALSE
) {
# FIXME: Warning as of duckdb 1.1.1, turn this into an error later
if (...length() > 0) {
warning("Arguments passed to ... are currently not used")
}
if (length(na.strings) > 1) {
abort("na.strings must be of length 1")
}
if (!missing(sep)) {
delim <- sep
}
headers <- lapply(
files,
utils::read.csv,
sep = delim,
na.strings = na.strings,
quote = quote,
nrows = nrow.check,
header = header,
...
)
if (length(files) > 1) {
nn <- sapply(headers, ncol)
if (!all(nn == nn[1])) {
abort("Files have different numbers of columns")
}
nms <- sapply(headers, names)
if (!all(nms == nms[, 1])) {
abort("Files have different variable names or order")
}
if (is.null(col.types)) {
types <- sapply(headers, function(df) {
sapply(df, dbDataType, dbObj = conn)
})
if (!all(types == types[, 1])) {
abort("Files have different variable types")
}
}
}
fields <- set_csv_fields(
found = headers[[1]][FALSE, , drop = FALSE],
col.names,
col.types
)
if (lower.case.names) {
names(fields) <- tolower(names(fields))
}
if (transaction) {
dbBegin(conn)
on.exit(tryCatch(dbRollback(conn), error = function(e) {}))
}
tablename <- dbQuoteIdentifier(conn, name)
if (!dbExistsTable(conn, tablename)) {
dbCreateTable(conn, tablename, fields, temporary = temporary)
}
for (i in seq_along(files)) {
thefile <- dbQuoteString(conn, enc2native(normalizePath(files[i])))
dbExecute(
conn,
sprintf(
"COPY %s FROM %s (DELIMITER %s, QUOTE %s, HEADER %s, NULL %s)",
tablename,
thefile,
dbQuoteString(conn, delim),
dbQuoteString(conn, quote),
tolower(header),
dbQuoteString(conn, na.strings[1])
)
)
}
out <- dbGetQuery(conn, paste("SELECT COUNT(*) FROM", tablename))[[1]]
if (transaction) {
dbCommit(conn)
on.exit(NULL)
}
invisible(out)
}
#' Column names and types logic for duckdb_read_csv()
#'
#' @param found the detected (found) header and types from `utils::read_csv`
#' @param col.names user provided column names
#' @param col.types user provider column types and maybe names too
#'
#' @noRd
#' @return returns a valid fields argument for `dbCreateTable`
set_csv_fields <- function(found, col.names, col.types) {
if (is.null(col.types) && is.null(col.types)) {
return(found)
}
if (!is.null(names(col.types)) && !is.null(col.names)) {
warning(
"Ignoring `col.names` as column names provided by `col.types` parameter"
)
return(col.types)
}
if (!is.null(col.types)) {
if (length(col.types) != ncol(found)) {
abort(paste0(
"You supplied ",
length(col.types),
" values to `col.names`, but file has ",
ncol(found),
" columns."
))
}
if (!is.null(names(col.types))) {
return(col.types)
} else {
if (length(col.types) != ncol(found)) {
abort(paste0(
"You supplied ",
length(col.types),
" values to `col.types`, but file has ",
ncol(found),
" columns."
))
}
fields <- col.types
names(fields) <- col.names
return(fields)
}
} else {
fields <- col.types
names(fields) <- names(found)
}
fields
}
#' Deprecated functions
#'
#' `read_csv_duckdb()` has been superseded by `duckdb_read_csv()`.
#' The order of the arguments has changed.
#'
#' @rdname deprecated
#' @export
#' @keywords internal
read_csv_duckdb <- function(conn, files, tablename, ...) {
.Deprecated(
"duckdb_read_csv",
old = "read_csv_duckdb",
msg = "Use 'duckdb_read_csv' instead, with changed order of arguments."
)
# Different order of arguments!
duckdb_read_csv(conn, tablename, files, ...)
}