0 | module Oracle.Transaction
 1 |
 2 | import Oracle.Error
 3 | import Oracle.FFI.Transaction
 4 | import Oracle.Internal.Pointer
 5 | import Oracle.Types.Error
 6 |
 7 | %default total
 8 |
 9 | --------------------------------------------------------------------------------
10 | --          Commit
11 | --------------------------------------------------------------------------------
12 |
13 | ||| Commit the current transaction on a connection.
14 | |||
15 | ||| All changes made since the last commit or rollback become permanent.
16 | |||
17 | ||| Returns:
18 | ||| - Right () on success.
19 | ||| - Left OracleError on failure.
20 | |||
21 | export
22 | commit : Connection -> IO (Either OracleError ())
23 | commit conn = do
24 |   rc <- primIO (prim__commit conn.ptr)
25 |   case rc == 0 of
26 |     True  =>
27 |       pure (Right ())
28 |     False => do
29 |       lasterr <- getLastError
30 |       pure (Left lasterr)
31 |
32 | --------------------------------------------------------------------------------
33 | --          Rollback
34 | --------------------------------------------------------------------------------
35 |
36 | ||| Roll back the current transaction on a connection.
37 | |||
38 | ||| All changes made since the last commit or rollback are discarded.
39 | |||
40 | ||| Returns:
41 | ||| - Right () on success.
42 | ||| - Left OracleError on failure.
43 | |||
44 | export
45 | rollback : Connection -> IO (Either OracleError ())
46 | rollback conn = do
47 |   rc <- primIO (prim__rollback conn.ptr)
48 |   case rc == 0 of
49 |     True  =>
50 |       pure (Right ())
51 |     False => do
52 |       lasterr <- getLastError
53 |       pure (Left lasterr)
54 |
55 | --------------------------------------------------------------------------------
56 | --          Transaction Bracket
57 | --------------------------------------------------------------------------------
58 |
59 | ||| Execute an action inside a transaction.
60 | |||
61 | ||| The transaction behavior is:
62 | ||| - If the action returns Right -> commit is performed.
63 | ||| - If the action returns Left -> rollback is performed.
64 | |||
65 | ||| The original error is preserved if rollback succeeds.
66 | |||
67 | ||| Example:
68 | |||
69 | ||| ```idris
70 | ||| withTransaction conn $ do
71 | |||   execute stmt1
72 | |||   execute stmt2
73 | ||| ```
74 | |||
75 | export
76 | withTransaction : Connection -> IO (Either OracleError a) -> IO (Either OracleError a)
77 | withTransaction conn action = do
78 |   result <- action
79 |   case result of
80 |     Left err    => do
81 |       _ <- rollback conn
82 |       pure (Left err)
83 |     Right value => do
84 |       committed <- commit conn
85 |       case committed of
86 |         Left err =>
87 |           pure (Left err)
88 |         Right () =>
89 |           pure (Right value)
90 |