con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "cars", head(cars, 3))
dbReadTable(con, "cars") # there are 3 rows
## successful transaction
dbWithTransaction(con, {
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (1, 1);")
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (2, 2);")
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (3, 3);")
})
dbReadTable(con, "cars") # there are now 6 rows
## failed transaction -- note the missing comma
tryCatch(
dbWithTransaction(con, {
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (1, 1);")
dbExecute(con, "INSERT INTO cars (speed dist) VALUES (2, 2);")
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (3, 3);")
}),
error = identity
)
dbReadTable(con, "cars") # still 6 rows
## early exit, silently
dbWithTransaction(con, {
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (1, 1);")
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (2, 2);")
if (nrow(dbReadTable(con, "cars")) > 7) dbBreak()
dbExecute(con, "INSERT INTO cars (speed, dist) VALUES (3, 3);")
})
dbReadTable(con, "cars") # still 6 rows
dbDisconnect(con)
Run the code above in your browser using DataLab