Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions Database/SQLite/Simple.hs
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ module Database.SQLite.Simple (
) where

import Control.Exception
import Control.Monad (void, when, forM_)
import Control.Monad (void, when, unless, forM_)
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State.Strict
import Data.Int (Int64)
Expand Down Expand Up @@ -542,7 +542,7 @@ withTransactionPrivate conn action ttype =
mask $ \restore -> do
begin
r <- restore action `onException` rollback
commit
commit `onException` rollback
return r
where
begin = execute_ conn $ case ttype of
Expand All @@ -553,9 +553,11 @@ withTransactionPrivate conn action ttype =
commit = execute_ conn $ case ttype of
Savepoint name -> Query $ "RELEASE '" <> name <> "'"
_ -> "COMMIT TRANSACTION"
rollback = execute_ conn $ case ttype of
Savepoint name -> Query $ "ROLLBACK TO '" <> name <> "'"
_ -> "ROLLBACK TRANSACTION"
rollback = do
autocommit <- BaseD.getAutoCommit $ connectionHandle conn
unless autocommit $ execute_ conn $ case ttype of
Savepoint name -> Query $ "ROLLBACK TO '" <> name <> "'"
_ -> "ROLLBACK TRANSACTION"


-- | Run an IO action inside a SQL transaction started with @BEGIN IMMEDIATE
Expand Down Expand Up @@ -611,15 +613,17 @@ withTransaction conn action =
-- | Run an IO action inside an SQLite @SAVEPOINT@. If the action throws any
-- kind of an exception, the transaction will be rolled back to the savepoint
-- with @ROLLBACK TO@. Otherwise the results are released to the outer
-- transaction if any with @RELEASE@.
-- transaction with @RELEASE@. Outside of a transaction, the action is run
-- with 'withTransaction'.
--
-- See <https://sqlite.org/lang_savepoint.html> for a full description of
-- savepoint semantics.
withSavepoint :: Connection -> IO a -> IO a
withSavepoint conn action = do
n <- atomicModifyIORef' (connectionTempNameCounter conn) $ \n -> (n + 1, n)
autocommit <- BaseD.getAutoCommit $ connectionHandle conn
withTransactionPrivate conn action $
Savepoint $ "sqlite_simple_savepoint_" <> T.pack (show n)
if autocommit then Deferred else Savepoint $ "sqlite_simple_savepoint_" <> T.pack (show n)

fmtError :: Show v => String -> Query -> [v] -> a
fmtError msg q xs =
Expand Down
13 changes: 7 additions & 6 deletions Database/SQLite/Simple/FromField.hs
Original file line number Diff line number Diff line change
Expand Up @@ -159,16 +159,17 @@ instance FromField Bool where
fromField f = returnError ConversionFailed f "expecting an SQLInteger column type"

instance FromField T.Text where
fromField (Field (SQLText txt) _) = Ok txt
fromField f = returnError ConversionFailed f "need a text"
fromField f@(Field sqlData _) = case sqlData of
SQLText v -> Ok v
SQLInteger v -> Ok $ T.pack $ show v
SQLFloat v -> Ok $ T.pack $ show v
_ -> returnError ConversionFailed f "need convertible to text"

instance FromField LT.Text where
fromField (Field (SQLText txt) _) = Ok . LT.fromStrict $ txt
fromField f = returnError ConversionFailed f "need a text"
fromField f = LT.fromStrict <$> fromField f

instance FromField [Char] where
fromField (Field (SQLText t) _) = Ok $ T.unpack t
fromField f = returnError ConversionFailed f "expecting SQLText column type"
fromField f = T.unpack <$> fromField f

instance FromField ByteString where
fromField (Field (SQLBlob blb) _) = Ok blb
Expand Down
2 changes: 1 addition & 1 deletion cabal.project
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ packages: .
source-repository-package
type: git
location: https://github.com/simplex-chat/direct-sqlcipher.git
tag: 34309410eb2069b029b8fc1872deb1e0db123294
tag: 2330df3dc8c4b660674d3c02d76bb86f66c2abee
1 change: 1 addition & 0 deletions sqlcipher-simple.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ test-suite test
build-depends: base
, base16-bytestring
, bytestring >= 0.9
, directory
, HUnit
, sqlcipher-simple
, direct-sqlcipher
Expand Down
2 changes: 1 addition & 1 deletion stack.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ extra-deps:
# - direct-sqlcipher-2.3.26
# - ../direct-sqlcipher
- github: simplex-chat/direct-sqlcipher
commit: 34309410eb2069b029b8fc1872deb1e0db123294
commit: 2330df3dc8c4b660674d3c02d76bb86f66c2abee
47 changes: 36 additions & 11 deletions test/Errors.hs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ module Errors (
, testErrorsImmediateTransaction
, testErrorsExclusiveTransaction
, testErrorsSavepoint
, testErrorsBusyCommit
, testErrorsEndedTransaction
) where

import Control.Exception
Expand All @@ -19,6 +21,8 @@ import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import Data.Word
import Data.Time (Day, UTCTime)
import System.Directory (getTemporaryDirectory, removeFile)
import System.IO (hClose, openTempFile)

import Common
import Database.SQLite.Simple.Types (Null)
Expand All @@ -29,6 +33,12 @@ assertResultErrorThrown action expectedError =
(action >> assertFailure ("Expected error: " ++ show expectedError ++ ", but nothing was thrown"))
(\(e :: ResultError) -> assertEqual "assertResultErrorThrown" expectedError e)

assertBusyThrown :: IO a -> Assertion
assertBusyThrown action =
catch
(action >> assertFailure "Expected ErrorBusy, but nothing was thrown")
(\(e :: SQLError) -> assertEqual "assertBusyThrown" ErrorBusy (sqlError e))

assertFormatErrorCaught :: IO a -> Assertion
assertFormatErrorCaught action = do
catch (action >> return False) (\(e :: FormatError) -> length (show e) `seq` return True) >>=
Expand Down Expand Up @@ -67,7 +77,7 @@ testErrorsColumns TestEnv{..} = TestCase $ do
}
-- Mismatching types (source int,text doesn't match dst string,int)
assertResultErrorThrown (query_ conn "SELECT id, t FROM cols" :: IO [(String, Int)])
ConversionFailed {errSQLType = "INTEGER", errHaskellType = "[Char]", errMessage = "expecting SQLText column type"}
ConversionFailed {errSQLType = "TEXT", errHaskellType = "Int", errMessage = "need an int"}
-- Mismatching types (source string doesn't match dst integer)
assertResultErrorThrown (query_ conn "SELECT 'foo'" :: IO [Only Integer])
ConversionFailed {errSQLType = "TEXT", errHaskellType = "Integer", errMessage = "need an int"}
Expand All @@ -85,15 +95,8 @@ testErrorsColumns TestEnv{..} = TestCase $ do
ConversionFailed {errSQLType = "TEXT", errHaskellType = "Bool", errMessage = "expecting an SQLInteger column type"}
assertResultErrorThrown (query_ conn "SELECT 2" :: IO [Only Bool])
ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Bool", errMessage = "bool must be 0 or 1, got 2"}
-- Mismatching types (sources don't match destination string types (text, string)
assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only T.Text])
ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Text", errMessage = "need a text"}
assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only LT.Text])
ConversionFailed {errSQLType = "INTEGER", errHaskellType = "Text", errMessage = "need a text"}
assertResultErrorThrown (query_ conn "SELECT 1.0" :: IO [Only T.Text])
ConversionFailed {errSQLType = "FLOAT", errHaskellType = "Text", errMessage = "need a text"}
assertResultErrorThrown (query_ conn "SELECT 1.0" :: IO [Only LT.Text])
ConversionFailed {errSQLType = "FLOAT", errHaskellType = "Text", errMessage = "need a text"}
numbers <- query_ conn "SELECT 1, 1.0" :: IO [(T.Text, LT.Text)]
[("1", "1.0")] @=? numbers
-- Mismatching types (sources don't match destination string types (time/date)
assertResultErrorThrown (query_ conn "SELECT 1" :: IO [Only UTCTime])
ConversionFailed {errSQLType = "INTEGER", errHaskellType = "UTCTime", errMessage = "expecting SQLText column type"}
Expand All @@ -116,7 +119,7 @@ testErrorsColumns TestEnv{..} = TestCase $ do
assertResultErrorThrown
(do [Only _t1] <- query conn "SELECT b FROM cols_blobs WHERE id = ?" (Only (1 :: Int)) :: IO [Only String]
return ())
ConversionFailed {errSQLType = "BLOB", errHaskellType = "[Char]", errMessage = "expecting SQLText column type"}
ConversionFailed {errSQLType = "BLOB", errHaskellType = "Text", errMessage = "need convertible to text"}
execute_ conn "CREATE TABLE cols_bools (id INTEGER PRIMARY KEY, b BOOLEAN)"
-- 3 = invalid value for bool, must be 0 or 1
execute_ conn "INSERT INTO cols_bools (b) VALUES (3)"
Expand Down Expand Up @@ -297,6 +300,7 @@ testErrorsSavepoint TestEnv{..} = TestCase $ do
"INSERT INTO strans (t) VALUES (:txt)" [":missing" := ("foo" :: String)])
e <- rowExists
False @=? e
withTransaction conn $ return ()
where
rowExists = do
rows <- query_ conn "SELECT t FROM strans" :: IO [Only String]
Expand All @@ -307,3 +311,24 @@ testErrorsSavepoint TestEnv{..} = TestCase $ do
[] ->
return False
_ -> error "should have only one row"

testErrorsBusyCommit :: (Connection -> IO () -> IO ()) -> TestEnv -> Test
testErrorsBusyCommit transaction _ = TestCase $ do
dir <- getTemporaryDirectory
bracket (openTempFile dir "busy.db") (removeFile . fst) $ \(path, h) -> do
hClose h
withConnection path $ \writer -> withConnection path $ \reader -> do
let insert = transaction writer $ execute_ writer "INSERT INTO busy DEFAULT VALUES"
execute_ writer "CREATE TABLE busy (id INTEGER PRIMARY KEY)"
withTransaction reader $ do
_ <- query_ reader "SELECT id FROM busy" :: IO [Only Int]
assertBusyThrown insert
insert
[Only n] <- query_ reader "SELECT count(*) FROM busy"
(1 :: Int) @=? n

testErrorsEndedTransaction :: TestEnv -> Test
testErrorsEndedTransaction TestEnv{..} = TestCase $
catch
(withTransaction conn (execute_ conn "ROLLBACK") >> assertFailure "Expected SQLError, but nothing was thrown")
(\(e :: SQLError) -> "cannot commit - no transaction is active" @=? sqlErrorDetails e)
3 changes: 3 additions & 0 deletions test/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ tests =
, TestLabel "Errors" . testErrorsImmediateTransaction
, TestLabel "Errors" . testErrorsExclusiveTransaction
, TestLabel "Errors" . testErrorsSavepoint
, TestLabel "Errors" . testErrorsBusyCommit withImmediateTransaction
, TestLabel "Errors" . testErrorsBusyCommit withSavepoint
, TestLabel "Errors" . testErrorsEndedTransaction
, TestLabel "Utf8" . testUtf8Simplest
, TestLabel "Utf8" . testBlobs
, TestLabel "Instances" . testUserFromField
Expand Down
2 changes: 1 addition & 1 deletion test/With.hs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ expectedTypeError =
ConversionFailed
{ errSQLType = "NULL"
, errHaskellType = "Text"
, errMessage = "need a text"
, errMessage = "need convertible to text"
}

mkTest :: AccessMode -> BindingMode -> Table -> PathKind -> TestEnv -> Test
Expand Down
Loading