Skip to content

Commit

Permalink
Fix transaction() not actually using a transaction
Browse files Browse the repository at this point in the history
  • Loading branch information
Octogonapus committed Feb 7, 2024
1 parent 012c095 commit b7254b6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 3 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,5 @@ deps/build.log

# Manifest file
Manifest.toml

.vscode/
4 changes: 1 addition & 3 deletions src/load.jl
Original file line number Diff line number Diff line change
Expand Up @@ -105,14 +105,12 @@ function load(itr, conn::Connection, name::AbstractString="mysql_"*Random.randst
end

function transaction(f::Function, conn)
API.autocommit(conn.mysql, false)
execute(conn, "START TRANSACTION")
try
f()
API.commit(conn.mysql)
catch
API.rollback(conn.mysql)
rethrow()
finally
API.autocommit(conn.mysql, true)
end
end
36 changes: 36 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -350,3 +350,39 @@ ret = columntable(res)

# load on closed connection should throw
@test_throws ArgumentError MySQL.load(ct, conn, "test194")

@testset "transactions" begin
DBInterface.execute(conn, "DROP TABLE IF EXISTS TransactionTest")
DBInterface.execute(conn, "CREATE TABLE TransactionTest (a int)")

conn2 = DBInterface.connect(MySQL.Connection, "", ""; option_file=joinpath(dirname(pathof(MySQL)), "../test/", "my.ini"))

try
# happy path
DBInterface.transaction(conn) do
DBInterface.execute(conn, "INSERT INTO TransactionTest (a) VALUES (1)")

# we can see the result inside our transaction
result = DBInterface.execute(conn, "SELECT * FROM TransactionTest") |> Tables.columntable
@test result.a == [1]

# and can't see it outside our transaction
result = DBInterface.execute(conn2, "SELECT * FROM TransactionTest") |> Tables.columntable
@test isempty(result.a)
end
result = DBInterface.execute(conn, "SELECT * FROM TransactionTest") |> Tables.columntable
@test result.a == [1]
result = DBInterface.execute(conn2, "SELECT * FROM TransactionTest") |> Tables.columntable
@test result.a == [1]

# roll back due to exception
@test_throws ErrorException DBInterface.transaction(conn) do
DBInterface.execute(conn, "INSERT INTO TransactionTest (a) VALUES (2)")
error("force rollback")
end
result = DBInterface.execute(conn, "SELECT * FROM TransactionTest") |> Tables.columntable
@test result.a == [1] # the table did not change
finally
close(conn2)
end
end

0 comments on commit b7254b6

Please sign in to comment.