Skip to content
Framework

Database

db_copy_from()

Load a CSV file into an existing 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, and the database converts them to the columns' types. PostgreSQL loads with COPY ... FROM STDIN, DuckDB from the parsed file directly, SQL Server with pyodbc's fast executemany, and SQLite and MySQL with executemany. Rows load in chunks, so a large file does not need to fit in memory.

Usage

db_copy_from(
    connection: Connection | str,
    table: str,
    csv: str | Path,
    delim: str = 'comma',
    na: Sequence[str] = ('', 'NA'),
) -> int

Arguments

Name Type Default Description
connection required Connection | str

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

table required str

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

csv required str | Path

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

delim str 'comma'

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

na Sequence[str] ('', 'NA')

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

Value

The number of rows loaded.

Raises

  • FrameworkError: The file is missing, the connection is read-only, or the load failed. The whole load runs in one transaction, so a failure loads nothing.

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