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 |
|
| path |
The |
|
| transaction | TRUE |
Run the whole file in one transaction (default). MySQL
commits schema changes (CREATE, ALTER, DROP) at once whatever the client
does. Pass |
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)
}