Skip to content
Framework

Database

db_copy_from()

Load a CSV file into an existing table

Loads a CSV file into a table, fast where the driver allows. The CSV's header names the columns, which must exist in the table; other columns get their defaults. Values go to the database as text (or NULL for the values in na), and the database converts them to the columns' types. Nothing is trimmed.

Usage

db_copy_from(conn, table, csv, delim = "comma", na = c("", "NA"))

Arguments

Name Default Description
conn

An open connection from db_connect(), or a connection name, which is opened for the load and closed afterward.

table

The table, optionally with its schema ("cdm.concept"). Each part is quoted for the driver, so names keep their case.

csv

The CSV file. A relative path is looked for from the project root, then from the working directory.

delim "comma"

The delimiter: "comma", "tab", "semicolon", or "space".

na c("", "NA")

Values loaded as NULL. Default: empty fields and NA, as data_read() reads them.

Value

The number of rows loaded.

Details

PostgreSQL loads with COPY ... FROM STDIN (DBI::dbWriteTable(copy = TRUE)), DuckDB inserts each chunk with one INSERT ... SELECT from a registered data frame, and SQLite, MySQL, and SQL Server use DBI::dbAppendTable(). The file is read in chunks of 50,000 rows, so a large file does not need to fit in memory.

The whole load runs in one transaction, so a failure loads nothing. The connection must be writable, as for db_execute_file().

Examples

Not run

if (FALSE) {
db_execute_file("warehouse", "sql/schema.sql")
db_copy_from("warehouse", "cdm.concept", "inputs/raw/CONCEPT.csv", delim = "tab")
}

Related reference

Search guides and reference for R, Python, Stata, the CLI, and Framework Cloud.