Skip to content
Framework

Database

db_execute_file()

Run every statement in a SQL file

Runs the statements in a .sql file in order, by default in one transaction, so a failure leaves the database as it was.

Usage

db_execute_file(conn, path, transaction = TRUE)

Arguments

Name Default Description
conn

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

path

The .sql file. A relative path is looked for from the project root, then from the working directory. It is read as UTF-8; a byte-order mark is dropped.

transaction TRUE

Run the whole file in one transaction (default). MySQL commits schema changes (CREATE, ALTER, DROP) at once whatever the client does. Pass FALSE for statements that cannot run in a transaction, such as PostgreSQL's CREATE INDEX CONCURRENTLY or VACUUM; each statement then commits as it runs.

Value

The number of statements (or SQL Server batches) run.

Details

Statements end at a ; outside single quotes ('' escapes one), double quotes, backticks, -- and /* */ comments, and PostgreSQL dollar quotes ($$ or $tag$). MySQL files also have # comments and backslash escapes. SQLite files are split with SQLite's own rule, so a trigger's BEGIN ... END; body stays whole. SQL Server files are split into batches at lines holding only GO, as sqlcmd does, and each batch runs whole. Statements holding only comments are dropped. MySQL's client-side DELIMITER command is not supported.

A failed statement stops the file with an error naming its number and line. The connection must be writable: not opened with read_only = TRUE and without read_only: true in its settings.

Examples

Not run

if (FALSE) {
db_execute_file("warehouse", "sql/schema.sql")
conn <- db_connect("analysis")
db_execute_file(conn, "sql/build.sql")
DBI::dbDisconnect(conn)
}

Related reference

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