takusen-oracle (empty) → 0.9.0
raw patch · 21 files changed
+6553/−0 lines, 21 filesdep +QuickCheckdep +basedep +mtlbuild-type:Customsetup-changed
Dependencies added: QuickCheck, base, mtl, old-time, random, takusen-oracle, time
Files
- Control/Exception/MonadIO.hs +48/−0
- Database/Enumerator.hs +1315/−0
- Database/InternalEnumerator.hs +268/−0
- Database/Oracle/Enumerator.hs +1059/−0
- Database/Oracle/OCIConstants.hs +178/−0
- Database/Oracle/OCIFunctions.hs +822/−0
- Database/Oracle/Test/Enumerator.hs +378/−0
- Database/Oracle/Test/OCIFunctions.hs +448/−0
- Database/Test/Enumerator.lhs +480/−0
- Database/Test/Performance.lhs +99/−0
- Database/Test/Util.lhs +129/−0
- Database/Util.hs +283/−0
- Foreign/C/Test/UTF8.hs +138/−0
- Foreign/C/UTF8.hs +313/−0
- LICENSE +32/−0
- Main.hs +69/−0
- Setup.hs +137/−0
- Test/Main.hs +7/−0
- Test/MiniUnit.hs +178/−0
- Test/MiniUnitTest.hs +64/−0
- takusen-oracle.cabal +108/−0
+ Control/Exception/MonadIO.hs view
@@ -0,0 +1,48 @@+ +module Control.Exception.MonadIO +( + CaughtMonadIO(..) + , gtry, gtryJust, gbracket, gfinally +) where + +import Control.Monad.Trans +import Control.Exception +import Control.Monad.Reader + + +gtry :: (Exception e, CaughtMonadIO m) => m b -> m (Either e b) +gtryJust :: (Exception e, CaughtMonadIO m) => (e -> Maybe b) -> m b1 -> m (Either b b1) +class MonadIO m => CaughtMonadIO m where + gcatch :: (Exception e) => m a -> (e -> m a) -> m a + gcatchJust :: (Exception e) => (e -> Maybe b) -> m a -> (b -> m a) -> m a + +gtry a = gcatch (liftM Right a) (return . Left) +gtryJust p a = gcatchJust p (liftM Right a) (return . Left) + +instance CaughtMonadIO IO where + gcatch = Control.Exception.catch + gcatchJust = catchJust + +instance CaughtMonadIO m => CaughtMonadIO (ReaderT a m) where + gcatch a h = ReaderT $ + \r -> gcatch (runReaderT a r) (\e -> runReaderT (h e) r) + gcatchJust p a h = ReaderT $ + \r -> gcatch (runReaderT a r) (\e -> + case p e of + Nothing -> throw e + Just e' -> runReaderT (h e') r + ) + +gbracket :: (CaughtMonadIO m) => + m t -> (t -> m a) -> (t -> m b) -> m b +gbracket acq rel act = do + r <- acq + gcatch (do + v <- act r + rel r + return v + ) + (\e@(SomeException _) -> rel r >> throw e) + +gfinally :: (CaughtMonadIO m) => m t -> m a -> m t +gfinally a f = gbracket (return ()) (const f) (const a)
+ Database/Enumerator.hs view
@@ -0,0 +1,1315 @@+ +-- | +-- Module : Database.Enumerator +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + +-- Abstract database interface, providing a left-fold enumerator +-- and cursor operations. + +-- There is a stub: "Database.Stub.Enumerator". +-- This lets you run the test cases without having a working DBMS installation. +-- This isn't so valuable now, because it's dead easy to install Sqlite, +-- but it's still there if you want to try it. + +-- Additional reading: + +-- * <http://pobox.com/~oleg/ftp/Haskell/misc.html#fold-stream> + +-- * <http://pobox.com/~oleg/ftp/papers/LL3-collections-enumerators.txt> + +-- * <http://www.eros-os.org/pipermail/e-lang/2004-March/009643.html> + +-- Note that there are a few functions that are exported from each DBMS-specific +-- implementation which are exposed to the API user, and which are part of +-- the Takusen API, but are not (necessarily) in this module. +-- They include: + +-- * @connect@ (obviously DBMS specific) + +-- * @prepareQuery, prepareLargeQuery, prepareCommand, sql, sqlbind, prefetch, cmdbind@ + +-- These functions will typically have the same names and intentions, +-- but their specific types and usage may differ between DBMS. + + +{-# LANGUAGE CPP #-} +{-# LANGUAGE GeneralizedNewtypeDeriving #-} +{-# LANGUAGE OverlappingInstances #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE ScopedTypeVariables #-} + + +module Database.Enumerator + ( + -- * Usage + + -- $usage_example + + -- ** Iteratee Functions + + -- $usage_iteratee + + -- ** result and result' + + -- $usage_result + + -- ** Rank-2 types, ($), and the monomorphism restriction + + -- $usage_rank2_types + + -- ** Bind Parameters + + -- $usage_bindparms + + -- ** Multiple (and nested) Result Sets + + -- $usage_multiresultset + + -- * Sessions and Transactions + DBM -- The data constructor is not exported + , IE.ISession, IE.ConnectA + , withSession, withContinuedSession + , commit, rollback, beginTransaction + , withTransaction + , IE.IsolationLevel(..) + , execDDL, execDML, inquire + + -- * Exceptions and handlers + , IE.DBException(..) + , formatDBException, basicDBExceptionReporter + , reportRethrow, reportRethrowMsg + , catchDB, catchDBError, ignoreDBError, IE.throwDB + , IE.ColNum, IE.RowNum + , IE.SqlState, IE.SqlStateClass, IE.SqlStateSubClass + + -- * Preparing and Binding + , IE.PreparedStmt -- data constructor not exported + , withPreparedStatement + , withBoundStatement + , IE.Statement, IE.Command, IE.EnvInquiry + , IE.PreparationA, IE.IPrepared + , IE.BindA, IE.DBBind, IE.bindP + + -- * Iteratees and Cursors + , IE.IQuery, doQuery, IE.DBType + , IterResult, IterAct + , IE.currentRowNum, NextResultSet(..), RefCursor(..) + , cursorIsEOF, cursorCurrent, cursorNext + , withCursor + , IE.Position + + -- * Utilities + , ifNull, result, result' + + ) where + +import Prelude hiding (catch) +import Data.Dynamic +import Data.IORef +-- import Data.Time +import Data.Maybe (fromMaybe, isNothing) +-- import Control.Monad (liftM) +-- import Control.Monad.Trans (liftIO) +import Control.Exception +import Control.Monad.Fix +import Control.Monad.Reader +import Control.Exception.MonadIO +import qualified Database.InternalEnumerator as IE +-- import System.Time + +-- ----------------------------------------------------------- + + +-- ----------------------------------------------------------- + + +-- | 'IterResult' and 'IterAct' give us some type sugar. +-- Without them, the types of iteratee functions become +-- quite unwieldy. + +type IterResult seedType = Either seedType seedType +type IterAct m seedType = seedType -> m (IterResult seedType) + +-- | Catch 'Database.InteralEnumerator.DBException's thrown in the 'DBM' +-- monad. + +catchDB :: CaughtMonadIO m => m a -> (IE.DBException -> m a) -> m a +catchDB = gcatch + + + +-- |This simple handler reports the error to @stdout@ and swallows it +-- i.e. it doesn't propagate. + +basicDBExceptionReporter :: CaughtMonadIO m => IE.DBException -> m () +basicDBExceptionReporter e = liftIO (putStrLn (formatDBException e)) + +-- | This handler reports the error and propagates it +-- (usually to force the program to halt). + +reportRethrow :: CaughtMonadIO m => IE.DBException -> m a +--reportRethrow e = basicDBExceptionReporter e >> IE.throwDB e +reportRethrow = reportRethrowMsg "" + +-- | Same as reportRethrow, but you can prefix some text to the error +-- (perhaps to indicate which part of your program raised it). + +reportRethrowMsg :: CaughtMonadIO m => String -> IE.DBException -> m a +reportRethrowMsg m e = liftIO (putStr m) >> basicDBExceptionReporter e >> IE.throwDB e + +-- | A show for 'Database.InteralEnumerator.DBException's. + +formatDBException :: IE.DBException -> String +formatDBException (IE.DBError (ssc, sssc) e m) = + ssc ++ sssc ++ " " ++ show e ++ ": " ++ m +formatDBException (IE.DBFatal (ssc, sssc) e m) = + ssc ++ sssc ++ " " ++ show e ++ ": " ++ m +formatDBException (IE.DBUnexpectedNull r c) = + "Unexpected null in row " ++ show r ++ ", column " ++ show c ++ "." +formatDBException (IE.DBNoData) = "Fetch: no more data." + + +-- |If you want to trap a specific error number, use this. +-- It passes anything else up. + +catchDBError :: (CaughtMonadIO m) => + Int -> m a -> (IE.DBException -> m a) -> m a +catchDBError n action handler = catchDB action + (\dberror -> + case dberror of + IE.DBError ss e m | e == n -> handler dberror + _ -> IE.throwDB dberror + ) + +-- | Analogous to 'catchDBError', but ignores specific errors instead +-- (propagates anything else). + +ignoreDBError :: (CaughtMonadIO m) => Int -> m a -> m a +ignoreDBError n action = catchDBError n action (\e -> return undefined) + +-- -------------------------------------------------------------------- +-- -- ** Session monad +-- -------------------------------------------------------------------- + +-- The DBM data constructor is NOT exported. + +-- One may think to quantify over sess in |withSession|. We won't need +-- any mark then, I gather. +-- The quantification over Session is quite bothersome: need to enumerate +-- all class constraints for the Session (like IQuery, DBType, etc). + +newtype IE.ISession sess => DBM mark sess a = DBM (ReaderT sess IO a) +#ifndef __HADDOCK__ + deriving (Functor, Monad, MonadIO, MonadFix, MonadReader sess) +#else + -- Haddock can't cope with the "MonadReader sess" instance + deriving (Functor, Monad, MonadIO, MonadFix) +#endif +unDBM (DBM x) = x + + +instance IE.ISession si => CaughtMonadIO (DBM mark si) where + gcatch a h = DBM ( gcatch (unDBM a) (unDBM . h) ) + gcatchJust p a h = DBM ( gcatchJust p (unDBM a) (unDBM . h) ) + +-- | Typeable constraint is to prevent the leakage of Session and other +-- marked objects. + +withSession :: (Typeable a, IE.ISession sess) => + IE.ConnectA sess -> (forall mark. DBM mark sess a) -> IO a +withSession (IE.ConnectA connecta) m = + bracket connecta IE.disconnect (runReaderT (unDBM m)) + + +-- | Persistent database connections. +-- This issue has been brought up by Shanky Surana. The following design +-- is inspired by that exchange. + +-- On one hand, implementing persistent connections is easy. One may say we should +-- have added them long time ago, to match HSQL, HDBC, and similar +-- database interfaces. Alas, implementing persistent connection +-- safely is another matter. The simplest design is like the following + +-- > withContinuedSession :: (Typeable a, IE.ISession sess) => +-- > IE.ConnectA sess -> (forall mark. DBM mark sess a) -> +-- > IO (a, IE.ConnectA sess) +-- > withContinuedSession (IE.ConnectA connecta) m = do +-- > conn <- connecta +-- > r <- runReaderT (unDBM m) conn +-- > return (r,(return conn)) + +-- so that the connection object is returned as the result and can be +-- used again with withContinuedSession or withSession. The problem is +-- that nothing prevents us from writing: + +-- > (r1,conn) <- withContinuedSession (connect "...") query1 +-- > r2 <- withSession conn query2 +-- > r3 <- withSession conn query3 + +-- That is, we store the suspended connection and then use it twice. +-- But the first withSession closes the connection. So, the second +-- withSession gets an invalid session object. Invalid in a sense that +-- even memory may be deallocated, so there is no telling what happens +-- next. Also, as we can see, it is difficult to handle errors and +-- automatically dispose of the connections if the fatal error is +-- encountered. + +-- All these problems are present in other interfaces... In the +-- case of a suspended connection, the problem is how to enforce the +-- /linear/ access to a variable. It can be enforced, via a +-- state-changing monad. The implementation below makes +-- the non-linear use of a suspended connection a run-time checkable +-- condition. It will be generic and safe - fatal errors close the +-- connection, an attempt to use a closed connection raises an error, and +-- we cannot reuse a connection. We have to write: + +-- > (r1, conn1) <- withContinuedSession conn ... +-- > (r2, conn2) <- withContinuedSession conn1 ... +-- > (r3, conn3) <- withContinuedSession conn2 ... + +-- etc. If we reuse a suspended connection or use a closed connection, +-- we get a run-time (exception). That is of course not very +-- satisfactory - and yet better than a segmentation fault. + +withContinuedSession :: (Typeable a, IE.ISession sess) => + IE.ConnectA sess -> (forall mark. DBM mark sess a) + -> IO (a, IE.ConnectA sess) +withContinuedSession (IE.ConnectA connecta) m = + do conn <- connecta -- this invalidates connecta + -- Note: if there was an error, then disconnect, + -- but don't disconnect in the success case + -- (the connecta action will raise an error if the + -- connection is re-used). + r <- runReaderT (unDBM m) conn + `catch` (\e@(SomeException _) -> IE.disconnect conn >> throw e) + -- make a new, one-shot connecta + hasbeenused <- newIORef False + let connecta = do + fl <- readIORef hasbeenused + when fl $ error "connecta has been re-used" + writeIORef hasbeenused True + return conn + return (r,IE.ConnectA connecta) + + + +beginTransaction :: + (MonadReader s (ReaderT s IO), IE.ISession s) => + IE.IsolationLevel -> DBM mark s () +beginTransaction il = DBM (ask >>= \s -> lift $ IE.beginTransaction s il) +commit :: IE.ISession s => DBM mark s () +commit = DBM( ask >>= lift . IE.commit ) +rollback :: IE.ISession s => DBM mark s () +rollback = DBM( ask >>= lift . IE.rollback ) + + +executeCommand :: IE.Command stmt s => stmt -> DBM mark s Int +executeCommand stmt = DBM( ask >>= \s -> lift $ IE.executeCommand s stmt ) + +-- | DDL operations don't manipulate data, so we return no information. +-- If there is a problem, an exception will be raised. + +execDDL :: IE.Command stmt s => stmt -> DBM mark s () +execDDL stmt = void (executeCommand stmt) + +-- | Returns the number of rows affected. + +execDML :: IE.Command stmt s => stmt -> DBM mark s Int +execDML = executeCommand + +-- | Allows arbitrary actions to be run the DBM monad. +-- The back-end developer must supply instances of EnvInquiry, +-- which is hidden away in "Database.InternalEnumerator". +-- An example of this is 'Database.Sqlite.Enumerator.LastInsertRowid'. + +inquire :: IE.EnvInquiry key s result => key -> DBM mark s result +inquire key = DBM( ask >>= \s -> lift $ IE.inquire key s ) + +-- -------------------------------------------------------------------- +-- -- ** Statements; Prepared statements +-- -------------------------------------------------------------------- + +executePreparation :: IE.IPrepared stmt sess bstmt bo => + IE.PreparationA sess stmt -> DBM mark sess (IE.PreparedStmt mark stmt) +executePreparation (IE.PreparationA action) = + DBM( ask >>= \sess -> lift $ liftM IE.PreparedStmt (action sess)) + +data NextResultSet mark stmt = NextResultSet (IE.PreparedStmt mark stmt) +data RefCursor a = RefCursor a + + + +-- The exception handling in withPreparedStatement looks awkward, +-- but there's a good reason... + +-- Suppose there's some sort of error when we call destroyStmt. +-- The exception handler also must call destroyStmt (because the exception +-- might have also come from the invocation of action), but calling destroyStmt +-- might also raise a new exception (for example, a different error is raised +-- if you re-try a failed CLOSE-cursor, because the transaction is aborted). +-- So we wrap this call with a catch, and ensure that the original exception +-- is preserved and re-raised. + +-- | Prepare a statement and run a DBM action over it. +-- This gives us the ability to re-use a statement, +-- for example by passing different bind values for each execution. + +-- The Typeable constraint is to prevent the leakage of marked things. +-- The type of bound statements should not be exported (and should not be +-- in Typeable) so the bound statement can't leak either. + +withPreparedStatement :: + (Typeable a, IE.IPrepared stmt sess bstmt bo) + => IE.PreparationA sess stmt + -- ^ preparation action to create prepared statement; + -- this action is usually created by @prepareQuery\/Command@ + -> (IE.PreparedStmt mark stmt -> DBM mark sess a) + -- ^ DBM action that takes a prepared statement + -> DBM mark sess a +withPreparedStatement pa action = do + ps <- executePreparation pa + gcatch ( do + v <- action ps + destroyStmt ps + return v + ) (\e@(SomeException _) -> gcatch (destroyStmt ps >> throw e) (\e2@(SomeException _) -> throw e)) + + +-- Not exported. + +destroyStmt :: (IE.ISession sess, IE.IPrepared stmt sess bstmt bo) + => IE.PreparedStmt mark stmt -> DBM mark sess () +destroyStmt (IE.PreparedStmt stmt) = DBM( ask >>= \s -> lift $ IE.destroyStmt s stmt) + + + +-- | Applies a prepared statement to bind variables to get a bound statement, +-- which is passed to the provided action. +-- Note that by the time it is passed to the action, the query or command +-- has usually been executed. +-- A bound statement would normally be an instance of +-- 'Database.InternalEnumerator.Statement', so it can be passed to +-- 'Database.Enumerator.doQuery' +-- in order to process the result-set, and also an instance of +-- 'Database.InternalEnumerator.Command', so that we can write +-- re-usable DML statements (inserts, updates, deletes). + +-- The Typeable constraint is to prevent the leakage of marked things. +-- The type of bound statements should not be exported (and should not be +-- in Typeable) so the bound statement can't leak either. + +withBoundStatement :: + (Typeable a, IE.IPrepared stmt s bstmt bo) + => IE.PreparedStmt mark stmt + -- ^ prepared statement created by withPreparedStatement + -> [IE.BindA s stmt bo] + -- ^ bind values + -> (bstmt -> DBM mark s a) + -- ^ action to run over bound statement + -> DBM mark s a +withBoundStatement (IE.PreparedStmt stmt) ba f = + DBM ( ask >>= \s -> + lift $ IE.bindRun s stmt ba (\b -> runReaderT (unDBM (f b)) s)) + + +-- -------------------------------------------------------------------- +-- -- ** Buffers and QueryIteratee +-- -------------------------------------------------------------------- + + +-- |The class QueryIteratee is not for the end user. It provides the +-- interface between the low- and the middle-layers of Takusen. The +-- middle-layer - enumerator - is database-independent then. + +class MonadIO m => QueryIteratee m q i seed b | + i -> m, i -> seed, q -> b where + iterApply :: q -> [b] -> seed -> i -> m (IterResult seed) + allocBuffers :: q -> i -> IE.Position -> m [b] + +-- |This instance of the class is the terminating case +-- i.e. where the iteratee function has one argument left. +-- The argument is applied, and the result returned. + +instance (IE.DBType a q b, MonadIO m) => + QueryIteratee m q (a -> seed -> m (IterResult seed)) seed b where + iterApply q [buf] seed fn = do + v <- liftIO $ IE.fetchCol q buf + fn v seed + + allocBuffers r _ n = liftIO $ + sequence [IE.allocBufferFor (undefined::a) r n] + +-- |This instance of the class implements the starting and continuation cases. + +instance (QueryIteratee m q i' seed b, IE.DBType a q b) + => QueryIteratee m q (a -> i') seed b where + iterApply q (buffer:moreBuffers) seed fn = do + v <- liftIO $ IE.fetchCol q buffer + iterApply q moreBuffers seed (fn v) + allocBuffers q fn n = do + buffer <- liftIO $ IE.allocBufferFor (undefined::a) q n + moreBuffers <- allocBuffers q (undefined::i') (n+1) + return (buffer:moreBuffers) + + + +-- -------------------------------------------------------------------- +-- -- ** A Query monad and cursors +-- -------------------------------------------------------------------- + + +type CollEnumerator i m s = i -> s -> m s +type Self i m s = i -> s -> m s +type CFoldLeft i m s = Self i m s -> CollEnumerator i m s + +-- |A DBCursor is an IORef-mutable-pair @(a, Maybe f)@, where @a@ is the result-set so far, +-- and @f@ is an IO action that fetches and returns the next row (when applied to True), +-- or closes the cursor (when applied to False). +-- If @Maybe@ f is @Nothing@, then the result-set has been exhausted +-- (or the iteratee function terminated early), +-- and the cursor has already been closed. + +newtype DBCursor mark ms a = + DBCursor (IORef (a, Maybe (Bool-> ms (DBCursor mark ms a)))) + + +-- | The left-fold interface. + +doQuery :: (IE.Statement stmt sess q, + QueryIteratee (DBM mark sess) q i seed b, + IE.IQuery q sess b) => + stmt -- ^ query + -> i -- ^ iteratee function + -> seed -- ^ seed value + -> DBM mark sess seed +doQuery stmt iteratee seed = do + (lFoldLeft, finalizer) <- doQueryMaker stmt iteratee + gcatch (fix lFoldLeft iteratee seed) + (\e@(SomeException _) -> do + finalizer + liftIO (throw e) + ) + + +-- An auxiliary function, not seen by the user. + +doQueryMaker stmt iteratee = do + sess <- ask + -- if buffer allocation raises an exception + -- (which it might) then we need to clean up the query object. + query <- liftIO (IE.makeQuery sess stmt) + buffers <- gcatch (allocBuffers query iteratee 1) + (\e@(SomeException _) -> liftIO (IE.destroyQuery query >> throw e) ) + let + finaliser = + liftIO (mapM_ (IE.freeBuffer query) buffers >> IE.destroyQuery query) + hFoldLeft self iteratee initialSeed = do + let + handle seed True = iterApply query buffers seed iteratee + >>= handleIter + handle seed False = finaliser >> return seed + handleIter (Right seed) = self iteratee seed + handleIter (Left seed) = finaliser >> return seed + liftIO (IE.fetchOneRow query) >>= handle initialSeed + return (hFoldLeft, finaliser) + + +-- Another auxiliary function, also not seen by the user. + +openCursor stmt iteratee seed = do + ref <- liftIO (newIORef (seed,Nothing)) + (lFoldLeft, finalizer) <- doQueryMaker stmt iteratee + let update v = liftIO $ modifyIORef ref (\ (_, f) -> (v, f)) + let + close finalseed = do + liftIO$ modifyIORef ref (const (finalseed, Nothing)) + finalizer + return (DBCursor ref) + let + k' fni seed' = + let + k fni' seed'' = do + let k'' flag = if flag then k' fni' seed'' else close seed'' + liftIO$ modifyIORef ref (const (seed'', Just k'')) + return seed'' + in do + liftIO$ modifyIORef ref (const (seed', Nothing)) + lFoldLeft k fni seed' >>= update + return $ DBCursor ref + k' iteratee seed + + + +-- |cursorIsEOF's return value tells you if there are any more rows or not. +-- If you call 'cursorNext' when there are no more rows, +-- a 'DBNoData' exception is thrown. +-- Cursors are automatically closed and freed when: + +-- * the iteratee returns @Left a@ + +-- * the query result-set is exhausted. + +-- To make life easier, we've created a 'withCursor' function, +-- which will clean up if an error (exception) occurs, +-- or the code exits early. +-- You can nest them to get interleaving, if you desire: + +-- > withCursor query1 iter1 [] $ \c1 -> do +-- > withCursor query2 iter2 [] $ \c2 -> do +-- > r1 <- cursorCurrent c1 +-- > r2 <- cursorCurrent c2 +-- > ... +-- > return something + + +-- Note that the type of the functions below is set up so to perpetuate +-- the mark. + +cursorIsEOF :: DBCursor mark (DBM mark s) a -> DBM mark s Bool +cursorIsEOF (DBCursor ref) = do + (_, maybeF) <- liftIO $ readIORef ref + return $ isNothing maybeF + +-- |Returns the results fetched so far, processed by iteratee function. + +cursorCurrent :: DBCursor mark (DBM mark s) a -> DBM mark s a +cursorCurrent (DBCursor ref) = do + (v, _) <- liftIO $ readIORef ref + return v + +-- |Advance the cursor. Returns the cursor. The return value is usually ignored. + +cursorNext :: DBCursor mark (DBM mark s) a + -> DBM mark s (DBCursor mark (DBM mark s) a) +cursorNext (DBCursor ref) = do + (_, maybeF) <- liftIO $ readIORef ref + maybe (IE.throwDB IE.DBNoData) ($ True) maybeF + + +-- Returns the cursor. The return value is usually ignored. +-- This function is not available to the end user (i.e. not exported). +-- The cursor is closed automatically when its region exits. + +cursorClose c@(DBCursor ref) = do + (_, maybeF) <- liftIO $ readIORef ref + maybe (return c) ($ False) maybeF + + +-- |Ensures cursor resource is properly tidied up in exceptional cases. +-- Propagates exceptions after closing cursor. +-- The Typeable constraint is to prevent cursors and other marked values +-- (like cursor computations) from escaping. + +withCursor :: + ( Typeable a, IE.Statement stmt sess q + , QueryIteratee (DBM mark sess) q i seed b + , IE.IQuery q sess b + ) => + stmt -- ^ query + -> i -- ^ iteratee function + -> seed -- ^ seed value + -> (DBCursor mark (DBM mark sess) seed -> DBM mark sess a) -- ^ action taking cursor parameter + -> DBM mark sess a +withCursor stmt iteratee seed = + gbracket (openCursor stmt iteratee seed) cursorClose + + +-- Although withTransaction has the same structure as a bracket, +-- we can't use bracket because the resource-release action +-- (commit or rollback) differs between the success and failure cases. + +-- |Perform an action as a transaction: commit afterwards, +-- unless there was an exception, in which case rollback. + +withTransaction :: (IE.ISession s) => + IE.IsolationLevel -> DBM mark s a -> DBM mark s a + +withTransaction isolation action = do + beginTransaction isolation + gcatch ( do + v <- action + commit + return v + ) (\e@(SomeException _) -> rollback >> throw e ) + + +-- -------------------------------------------------------------------- +-- -- ** Misc. +-- -------------------------------------------------------------------- + + +-- |Useful utility function, for SQL weenies. + +ifNull :: Maybe a -- ^ nullable value + -> a -- ^ value to substitute if first parameter is null i.e. 'Data.Maybe.Nothing' + -> a +ifNull value subst = fromMaybe subst value + + + +-- | Another useful utility function. +-- Use this to return a value from an iteratee function (the one passed to +-- 'Database.Enumerator.doQuery'). +-- Note that you should probably nearly always use the strict version. + +result :: (Monad m) => IterAct m a +result x = return (Right x) + + +-- |A strict version. This is recommended unless you have a specific need for laziness, +-- as the lazy version will gobble stack and heap. +-- If you have a large result-set (in the order of 10-100K rows or more), +-- it is likely to exhaust the standard 1M GHC stack. +-- Whether or not 'result' eats memory depends on what @x@ does: +-- if it's a delayed computation then it almost certainly will. +-- This includes consing elements onto a list, +-- and arithmetic operations (counting, summing, etc). + +result' :: (Monad m) => IterAct m a +result' x = return (Right $! x) + + +-- That's the code... now for the documentation. + + +-- ==================================================================== +-- == Usage notes +-- ==================================================================== + + +-- $usage_example + +-- Let's look at some example code: + +-- > -- sample code, doesn't necessarily compile +-- > module MyDbExample is +-- > +-- > import Database.Oracle.Enumerator +-- > import Database.Enumerator +-- > ... +-- > +-- > query1Iteratee :: (Monad m) => Int -> String -> Double -> IterAct m [(Int, String, Double)] +-- > query1Iteratee a b c accum = result' ((a, b, c):accum) +-- > +-- > -- non-query actions. +-- > otherActions session = do +-- > execDDL (sql "create table blah") +-- > execDML (cmdbind "insert into blah (...) values (?, ?, ?, ...)" [bindP "v1", bindP (1::Int), ...]) +-- > commit +-- > -- Use withTransaction to delimit a transaction. +-- > -- It will commit at the end, or rollback if an error occurs. +-- > withTransaction Serialisable ( do +-- > execDML (sql "update blah ...") +-- > execDML (sql "insert into blah ...") +-- > ) +-- > +-- > main :: IO () +-- > main = do +-- > withSession (connect "user" "password" "server") ( do +-- > -- simple query, returning reversed list of rows. +-- > r <- doQuery (sql "select a, b, c from x") query1Iteratee [] +-- > liftIO $ putStrLn $ show r +-- > otherActions session +-- > ) + +-- Notes: + +-- * connection is made by 'Database.Enumerator.withSession', +-- which also disconnects when done i.e. 'Database.Enumerator.withSession' +-- delimits the connection. +-- You must pass it a connection action, which is back-end specific, +-- and created by calling the 'Database.Sqlite.Enumerator.connect' +-- function from the relevant back-end. + +-- * inside the session, the usual transaction delimiter commands are usable +-- e.g. 'Database.Enumerator.beginTransaction' 'Database.InternalEnumerator.IsolationLevel', +-- 'Database.Enumerator.commit', 'Database.Enumerator.rollback', and +-- 'Database.Enumerator.withTransaction'. +-- We also provide 'Database.Enumerator.execDML' and 'Database.Enumerator.execDDL'. + +-- * non-DML and -DDL commands - i.e. queries - are processed by +-- 'Database.Enumerator.doQuery' (this is the API for our left-fold). +-- See more explanation and examples below in /Iteratee Functions/ and +-- /Bind Parameters/ sections. + +-- The first argument to 'Database.Enumerator.doQuery' must be an instance of +-- 'Database.InternalEnumerator.Statement'. +-- Each back-end will provide a useful set of @Statement@ instances +-- and associated constructor functions for them. +-- For example, currently all back-ends have: + +-- * for basic, all-text statements (no bind variables, default row-caching) +-- which can be used as queries or commands: + +-- > sql "select ..." + +-- * for a select with bind variables: + +-- > sqlbind "select ?, ... where col = ? and ..." [bindP ..., bindP ...] + +-- * for a select with bind variables and row caching: + +-- > prefetch 100 "select ?, ... where col = ? and ..." [bindP ..., bindP ...] + +-- * for a DML command with bind variables: + +-- > cmdbind "insert into ... values (?, ?, ...)" [bindP ..., bindP ...] + +-- * for a reusable prepared statement: we have to first create the +-- prepared statement, and then bind in a separate step. +-- This separation lets us re-use prepared statements: + +-- > let stmt = prepareQuery (sql "select ? ...") +-- > withPreparedStatement stmt $ \pstmt -> +-- > withBoundStatement pstmt [bindP ..., bindP ...] $ \bstmt -> do +-- > result <- doQuery bstmt iter seed +-- > ... + +-- The PostgreSQL backend additionally requires that when preparing statements, +-- you (1) give a name to the prepared statement, +-- and (2) specify types for the bind parameters. +-- The list of bind-types is created by applying the +-- 'Database.PostgreSQL.Enumerator.bindType' function +-- to dummy values of the appropriate types. e.g. + +-- > let stmt = prepareQuery "stmtname" (sql "select ...") [bindType "", bindType (0::Int)] +-- > withPreparedStatement stmt $ \pstmt -> ... + +-- A longer explanation of prepared statements and +-- bind variables is in the Bind Parameters section below. + + +-- $usage_iteratee + +-- 'Database.Enumerator.doQuery' takes an iteratee function, of n arguments. +-- Argument n is the accumulator (or seed). +-- For each row that is returned by the query, +-- the iteratee function is called with the data from that row in +-- arguments 1 to n-1, and the current accumulated value in the argument n. + +-- The iteratee function returns the next value of the accumulator, +-- wrapped in an 'Data.Either.Either'. +-- If the 'Data.Either.Either' value is @Left@, then the query will terminate, +-- returning the wrapped accumulator\/seed value. +-- If the value is @Right@, then the query will continue, with the next row +-- begin fed to the iteratee function, along with the new accumulator\/seed value. + +-- In the example above, @query1Iteratee@ simply conses the new row (as a tuple) +-- to the front of the accumulator. +-- The initial seed passed to 'Database.Enumerator.doQuery' was an empty list. +-- Consing the rows to the front of the list results in a list +-- with the rows in reverse order. + +-- The types of values that can be used as arguments to the iteratee function +-- are back-end specific; they must be instances of the class +-- 'Database.InternalEnumerator.DBType'. +-- Most backends directly support the usual lowest-common-denominator set +-- supported by most DBMS's: 'Data.Int.Int', 'Data.Char.String', +-- 'Prelude.Double', 'Data.Time.UTCTime'. +-- ('Data.Int.Int64' is often, but not always, supported.) + +-- By directly support we mean there is type-specific marshalling code +-- implemented. +-- Indirect support for 'Text.Read.Read'- and 'Text.Show.Show'-able types +-- is supported by marshalling to and from 'Data.Char.String's. +-- This is done automatically by the back-end; +-- there is no need for user-code to perform the marshalling, +-- as long as instances of 'Text.Read.Read' and 'Text.Show.Show' are defined. + +-- The iteratee function operates in the 'DBM' monad, +-- so if you want to do IO in it you must use 'Control.Monad.Trans.liftIO' +-- (e.g. @liftIO $ putStrLn \"boo\"@ ) to lift the IO action into 'DBM'. + +-- The iteratee function is not restricted to just constructing lists. +-- For example, a simple counter function would ignore its arguments, +-- and the accumulator would simply be the count e.g. + +-- > counterIteratee :: (Monad m) => Int -> IterAct m Int +-- > counterIteratee _ i = result' $ (1 + i) + +-- The iteratee function that you pass to 'Database.Enumerator.doQuery' +-- needs type information, +-- at least for the arguments if not the return type (which is typically +-- determined by the type of the seed). +-- The type synonyms 'IterAct' and 'IterResult' give some convenience +-- in writing type signatures for iteratee functions: + +-- > type IterResult seedType = Either seedType seedType +-- > type IterAct m seedType = seedType -> m (IterResult seedType) + +-- Without them, the type for @counterIteratee@ would be: + +-- > counterIteratee :: (Monad m) => Int -> Int -> m (Either Int Int) + +-- which doesn't seem so onerous, but for more elaborate seed types +-- (think large tuples) it certainly helps e.g. + +-- > iter :: Monad m => +-- > String -> Double -> UTCTime -> [(String, Double, UTCTime)] +-- > -> m (Either [(String, Double, UTCTime)] [(String, Double, UTCTime)] ) + +-- reduces to (by using 'IterAct' and 'IterResult'): + +-- > iter :: Monad m => +-- > String -> Double -> UTCTime -> IterAct m [(String, Double, UTCTime)] + + + +-- $usage_result + +-- The 'result' (lazy) and @result\'@ (strict) functions are another convenient shorthand +-- for returning values from iteratee functions. The return type from an iteratee is actually +-- @Either seed seed@, where you return @Right@ if you want processing to continue, +-- or @Left@ if you want processing to stop before the result-set is exhausted. +-- The common case is: + +-- > query1Iteratee a b c accum = return (Right ((a, b, c):accum)) + +-- which we can write as + +-- > query1Iteratee a b c accum = result $ (a, b, c):accum) + +-- We have lazy and strict versions of @result@. The strict version is almost certainly +-- the one you want to use. If you come across a case where the lazy function is useful, +-- please tell us about it. The lazy function tends to exhaust the stack for large result-sets, +-- whereas the strict function does not. +-- This is due to the accumulation of a large number of unevaluated thunks, +-- and will happen even for simple arithmetic operations such as counting or summing. + +-- If you use the lazy function and you have stack\/memory problems, do some profiling. +-- With GHC: + +-- * ensure the iteratee has its own cost-centre (make it a top-level function) + +-- * compile with @-prof -auto-all@ + +-- * run with @+RTS -p -hr -RTS@ + +-- * run @hp2ps@ over the resulting @.hp@ file to get a @.ps@ document, and take a look at it. +-- Retainer sets are listed on the RHS, and are prefixed with numbers e.g. (13)CAF, (2)SYSTEM. +-- At the bottom of the @.prof@ file you'll find the full descriptions of the retainer sets. +-- Match the number in parentheses on the @.ps@ graph with a SET in the @.prof@ file; +-- the one at the top of the @.ps@ graph is the one using the most memory. + +-- You'll probably find that the lazy iteratee is consuming all of the stack with lazy thunks, +-- which is why we recommend the strict function. + + + +-- $usage_rank2_types + +-- In some examples we use the application operator ($) instead of parentheses +-- (some might argue that this is a sign of developer laziness). +-- At first glance, ($) and conventional function application via juxtaposition +-- seem to be interchangeable e.g. + +-- > liftIO (putStrLn (show x)) + +-- looks equivalent to + +-- > liftIO $ putStrLn $ show x + +-- But they're not, because Haskell's type system gives us a nice compromise. + +-- In a Hindley-Milner type system (like ML) there is no difference between +-- ($) and function application, because polymorphic functions are not +-- first-class and cannot be passed to other functions. +-- At the other end of the scale, ($) and function application in System F +-- are equivalent, because polymorphic functions can be passed to other +-- functions. However, type inference in System F is undecidable. + +-- Haskell hits the sweet spot: maintaining full inference, +-- and permitting rank-2 polymorphism, in exchange for very few +-- type annotations. Only functions that take polymorphic functions (and +-- thus are higher-rank) need type signatures. Rank-2 types can't be +-- inferred. The function ($) is a regular, rank-1 function, and so +-- it can't take polymorphic functions as arguments and return +-- polymorphic functions. + +-- Here's an example where ($) fails: +-- we supply a simple test program in the README file. +-- If you change the @withSession@ line to use ($), like so +-- (and remove the matching end-parenthese): + +-- > withSession (connect "sqlite_db") $ do + +-- then you get the error: + +-- > Main.hs:7:38: +-- > Couldn't match expected type `forall mark. DBM mark Session a' +-- > against inferred type `a1 b' +-- > In the second argument of `($)', namely +-- > ... + +-- Another way of rewriting it is like this, where we separate the +-- 'Database.Enumerator.DBM' action into another function: + +-- > {-# OPTIONS -fglasgow-exts #-} +-- > module Main where +-- > import Database.Sqlite.Enumerator +-- > import Control.Monad.Trans (liftIO) +-- > main = flip catchDB reportRethrow $ +-- > withSession (connect "sqlite_db") hello +-- > +-- > hello = withTransaction RepeatableRead $ do +-- > let iter (s::String) (_::String) = result s +-- > result <- doQuery (sql "select 'Hello world.'") iter "" +-- > liftIO (putStrLn result) + +-- which gives this error: + +-- > Main.hs:9:2: +-- > Inferred type is less polymorphic than expected +-- > Quantified type variable `mark' is mentioned in the environment: +-- > hello :: DBM mark Session () (bound at Main.hs:15:0) +-- > ... + +-- This is just the monomorphism restriction in action. +-- Sans a type signature, the function `hello' is monomorphised +-- (that is, `mark' is replaced with (), per GHC rules). +-- This is easily fixed by adding this type declaration: + +-- > hello :: DBM mark Session () + + + + +-- $usage_bindparms + +-- Support for bind variables varies between DBMS's. + +-- We call 'Database.Enumerator.withPreparedStatement' function to prepare +-- the statement, and then call 'Database.Enumerator.withBoundStatement' +-- to provide the bind values and execute the query. +-- The value returned by 'Database.Enumerator.withBoundStatement' +-- is an instance of the 'Database.InternalEnumerator.Statement' class, +-- so it can be passed to 'Database.Enumerator.doQuery' for result-set processing. + +-- When we call 'Database.Enumerator.withPreparedStatement', we must pass +-- it a \"preparation action\", which is simply an action that returns +-- the prepared query. The function to create this action varies between backends, +-- and by convention is called 'Database.PostgreSQL.Enumerator.prepareQuery'. +-- For DML statements, you must use 'Database.PostgreSQL.Enumerator.prepareCommand', +-- as the library needs to do something different depending on whether or not the +-- statement returns a result-set. + +-- For queries with large result-sets, we provide +-- 'Database.PostgreSQL.Enumerator.prepareLargeQuery', +-- which takes an extra parameter: the number of rows to prefetch +-- in a network call to the server. +-- This aids performance in two ways: +-- 1. you can limit the number of rows that come back to the +-- client, in order to use less memory, and +-- 2. the client library will cache rows, so that a network call to +-- the server is not required for every row processed. + +-- With PostgreSQL, we must specify the types of the bind parameters +-- when the query is prepared, so the 'Database.PostgreSQL.Enumerator.prepareQuery' +-- function takes a list of 'Database.PostgreSQL.Enumerator.bindType' values. +-- Also, PostgreSQL requires that prepared statements are named, +-- although you can use \"\" as the name. + +-- With Sqlite and Oracle, we simply pass the query text to +-- 'Database.PostgreSQL.Sqlite.prepareQuery', +-- so things are slightly simpler for these backends. + +-- Perhaps an example will explain it better: + +-- > postgresBindExample = do +-- > let +-- > query = sql "select blah from blahblah where id = ? and code = ?" +-- > iter :: (Monad m) => String -> IterAct m [String] +-- > iter s acc = result $ s:acc +-- > bindVals = [bindP (12345::Int), bindP "CODE123"] +-- > bindTypes = [bindType (0::Int), bindType ""] +-- > withPreparedStatement (prepareQuery "stmt1" query bindTypes) $ \pstmt -> do +-- > withBoundStatement pstmt bindVals $ \bstmt -> do +-- > actual <- doQuery bstmt iter [] +-- > liftIO (print actual) + +-- Note that we pass @bstmt@ to 'Database.Enumerator.doQuery'; +-- this is the bound statement object created by +-- 'Database.Enumerator.withBoundStatement'. + +-- The Oracle\/Sqlite example code is almost the same, except for the +-- call to 'Database.Sqlite.Enumerator.prepareQuery': + +-- > sqliteBindExample = do +-- > let +-- > query = sql "select blah from blahblah where id = ? and code = ?" +-- > iter :: (Monad m) => String -> IterAct m [String] +-- > iter s acc = result $ s:acc +-- > bindVals = [bindP (12345::Int), bindP "CODE123"] +-- > withPreparedStatement (prepareQuery query) $ \pstmt -> do +-- > withBoundStatement pstmt bindVals $ \bstmt -> do +-- > actual <- doQuery bstmt iter [] +-- > liftIO (print actual) + +-- It can be a bit tedious to always use the @withPreparedStatement+withBoundStatement@ +-- combination, so for the case where you don't plan to re-use the query, +-- we support a short-cut for bundling the query text and parameters. +-- The next example is valid for PostgreSQL, Sqlite, and Oracle +-- (the Sqlite implementation provides a dummy 'Database.Sqlite.Enumerator.prefetch' +-- function to ensure we have a consistent API). +-- Sqlite has no facility for prefetching - it's an embedded database, so no +-- network round-trip - so the Sqlite implementation ignores the prefetch count: + +-- > bindShortcutExample = do +-- > let +-- > iter :: (Monad m) => String -> IterAct m [String] +-- > iter s acc = result $ s:acc +-- > bindVals = [bindP (12345::Int), bindP "CODE123"] +-- > query = prefetch 1000 "select blah from blahblah where id = ? and code = ?" bindVals +-- > actual <- doQuery query iter [] +-- > liftIO (print actual) + +-- A caveat of using prefetch with PostgreSQL is that you must be inside a transaction. +-- This is because the PostgreSQL implementation uses a cursor and \"FETCH FORWARD\" +-- to implement fetching a block of rows in a single network call, +-- and PostgreSQL requires that cursors are only used inside transactions. +-- It can be as simple as wrapping calls to 'Database.Enumerator.doQuery' by +-- 'Database.Enumerator.withTransaction', +-- or you may prefer to delimit your transactions elsewhere (the API supports +-- 'Database.InternalEnumerator.beginTransaction' and +-- 'Database.InternalEnumerator.commit', if you prefer to use them): + +-- > withTransaction RepeatableRead $ do +-- > actual <- doQuery query iter [] +-- > liftIO (print actual) + +-- You may have noticed that for 'Data.Int.Int' and 'Prelude.Double' literal +-- bind values, we have to tell the compiler the type of the literal. +-- This is due to interaction with the numeric literal defaulting mechanism. +-- For non-numeric literals the compiler can (usually) determine the correct types to use. + +-- If you omit type information for numeric literals, from GHC the error +-- message looks something like this: + +-- > Database/PostgreSQL/Test/Enumerator.lhs:194:4: +-- > Overlapping instances for Database.InternalEnumerator.DBBind a +-- > Session +-- > Database.PostgreSQL.PGEnumerator.PreparedStmt +-- > Database.PostgreSQL.PGEnumerator.BindObj +-- > arising from use of `bindP' at Database/PostgreSQL/Test/Enumerator.lhs:194:4-8 +-- > Matching instances: +-- > Imported from Database.PostgreSQL.PGEnumerator: +-- > instance (Database.InternalEnumerator.DBBind (Maybe a) +-- > Session +-- > Database.PostgreSQL.PGEnumerator.PreparedStmt +-- > Database.PostgreSQL.PGEnumerator.BindObj) => +-- > Database.InternalEnumerator.DBBind a +-- > Session +-- > Database.PostgreSQL.PGEnumerator.PreparedStmt +-- > Database.PostgreSQL.PGEnumerator.BindObj +-- > Imported from Database.PostgreSQL.PGEnumerator: +-- > instance Database.InternalEnumerator.DBBind (Maybe Double) +-- > .... + + +-- $usage_multiresultset + +-- Support for returning multiple result sets from a single +-- statement exists for PostgreSQL and Oracle. +-- Such functionality does not exist in Sqlite. + +-- The general idea is to invoke a database procedure or function which +-- returns cursor variables. The variables can be processed by +-- 'Database.Enumerator.doQuery' in one of two styles: linear or nested. + +-- /Linear style:/ + +-- If we assume the existence of the following PostgreSQL function, +-- which is used in the test suite in "Database.PostgreSQL.Test.Enumerator": + +-- > CREATE OR REPLACE FUNCTION takusenTestFunc() RETURNS SETOF refcursor AS $$ +-- > DECLARE refc1 refcursor; refc2 refcursor; +-- > BEGIN +-- > OPEN refc1 FOR SELECT n*n from t_natural where n < 10 order by 1; +-- > RETURN NEXT refc1; +-- > OPEN refc2 FOR SELECT n, n*n, n*n*n from t_natural where n < 10 order by 1; +-- > RETURN NEXT refc2; +-- > END;$$ LANGUAGE plpgsql; + +-- ... then this code shows how linear processing of cursors would be done: + +-- > withTransaction RepeatableRead $ do +-- > withPreparedStatement (prepareQuery "stmt1" (sql "select * from takusenTestFunc()") []) $ \pstmt -> do +-- > withBoundStatement pstmt [] $ \bstmt -> do +-- > dummy <- doQuery bstmt iterMain [] +-- > result1 <- doQuery (NextResultSet pstmt) iterRS1 [] +-- > result2 <- doQuery (NextResultSet pstmt) iterRS2 [] +-- > where +-- > iterMain :: (Monad m) => (RefCursor String) -> IterAct m [RefCursor String] +-- > iterMain c acc = result (acc ++ [c]) +-- > iterRS1 :: (Monad m) => Int -> IterAct m [Int] +-- > iterRS1 i acc = result (acc ++ [i]) +-- > iterRS2 :: (Monad m) => Int -> Int -> Int -> IterAct m [(Int, Int, Int)] +-- > iterRS2 i i2 i3 acc = result (acc ++ [(i, i2, i3)]) + +-- Notes: + +-- * the use of a 'Database.Enumerator.RefCursor' 'Data.Char.String' +-- type in the iteratee function indicates +-- to the backend that it should save each cursor value returned, +-- which it does by stuffing them into a list attached to the +-- prepared statement object. +-- This means that we /must/ use 'Database.Enumerator.withPreparedStatement' +-- to create a prepared statement object; the prepared statament oject +-- is the container for the cursors returned. + +-- * in this example we choose to discard the results of the first iteratee. +-- This is not necessary, but in this case the only column is a +-- 'Database.Enumerator.RefCursor', and the values are already saved +-- in the prepared statement object. + +-- * saved cursors are consumed one-at-a-time by calling 'Database.Enumerator.doQuery', +-- passing 'Database.Enumerator.NextResultSet' @pstmt@ +-- (i.e. passing the prepared statement oject wrapped by +-- 'Database.Enumerator.NextResultSet'). +-- This simply pulls the next cursor off the list +-- - they're processed in the order they were pushed on (FIFO) - +-- and processes it with the given iteratee. + +-- * if you try to process too many cursors i.e. make too many calls +-- to 'Database.Enumerator.doQuery' passing 'Database.Enumerator.NextResultSet' @pstmt@, +-- then an exception will be thrown. +-- OTOH, failing to process returned cursors will not raise errors, +-- but the cursors will remain open on the server according to whatever scoping +-- rules the server applies. +-- For PostgreSQL, this will be until the transaction (or session) ends. + +-- /Nested style:/ + +-- The linear style of cursor processing is the only style supported by +-- MS SQL Server and ODBC (which we do not yet support). +-- However, PostgreSQL and Oracle also support using nested cursors in queries. + +-- Again for PostgreSQL, assuming we have these functions in the database: + +-- > CREATE OR REPLACE FUNCTION takusenTestFunc(lim int4) RETURNS refcursor AS $$ +-- > DECLARE refc refcursor; +-- > BEGIN +-- > OPEN refc FOR SELECT n, takusenTestFunc2(n) from t_natural where n < lim order by n; +-- > RETURN refc; +-- > END; $$ LANGUAGE plpgsql; + +-- > CREATE OR REPLACE FUNCTION takusenTestFunc2(lim int4) RETURNS refcursor AS $$ +-- > DECLARE refc refcursor; +-- > BEGIN +-- > OPEN refc FOR SELECT n from t_natural where n < lim order by n; +-- > RETURN refc; +-- > END; $$ LANGUAGE plpgsql; + +-- ... then this code shows how nested queries might work: + +-- > selectNestedMultiResultSet = do +-- > let +-- > q = "SELECT n, takusenTestFunc(n) from t_natural where n < 10 order by n" +-- > iterMain (i::Int) (c::RefCursor String) acc = result' ((i,c):acc) +-- > iterInner (i::Int) (c::RefCursor String) acc = result' ((i,c):acc) +-- > iterInner2 (i::Int) acc = result' (i:acc) +-- > withTransaction RepeatableRead $ do +-- > rs <- doQuery (sql q) iterMain [] +-- > flip mapM_ rs $ \(outer, c) -> do +-- > rs <- doQuery c iterInner [] +-- > flip mapM_ rs $ \(inner, c) -> do +-- > rs <- doQuery c iterInner2 [] +-- > flip mapM_ rs $ \i -> do +-- > liftIO (putStrLn (show outer ++ " " ++ show inner ++ " " ++ show i)) + +-- Just to make it clear: the outer query returns a result-set that includes +-- a 'Database.Enumerator.RefCursor' column. Each cursor from that column is passed to +-- 'Database.Enumerator.doQuery' to process it's result-set; +-- here we use 'Control.Monad.mapM_' to apply an IO action to the list returned by +-- 'Database.Enumerator.doQuery'. + +-- For Oracle the example is slightly different. +-- The reason it's different is that: + +-- * Oracle requires that the parent cursor must remain open +-- while processing the children +-- (in the PostgreSQL example, 'Database.Enumerator.doQuery' +-- closes the parent cursor after constructing the list, +-- before the list is processed. This is OK because PostgreSQL +-- keeps the child cursors open on the server until they are explicitly +-- closed, or the transaction or session ends). + +-- * our current Oracle implementation prevents marshalling +-- of the cursor in the result-set buffer to a Haskell value, +-- so each fetch overwrites the buffer value with a new cursor. +-- This means you have to fully process a given cursor before +-- fetching the next one. + +-- Contrast this with the PostgreSQL example above, +-- where the entire result-set is processed to give a +-- list of RefCursor values, and then we run a list of actions +-- over this list with 'Control.Monad.mapM_'. +-- This is possible because PostgreSQL refcursors are just the +-- database cursor names, which are Strings, which we can marshal +-- to Haskell values easily. + +-- > selectNestedMultiResultSet = do +-- > let +-- > q = "select n, cursor(SELECT nat2.n, cursor" +-- > ++ " (SELECT nat3.n from t_natural nat3 where nat3.n < nat2.n order by n)" +-- > ++ " from t_natural nat2 where nat2.n < nat.n order by n)" +-- > ++ " from t_natural nat where n < 10 order by n" +-- > iterMain (outer::Int) (c::RefCursor StmtHandle) acc = do +-- > rs <- doQuery c (iterInner outer) [] +-- > result' ((outer,c):acc) +-- > iterInner outer (inner::Int) (c::RefCursor StmtHandle) acc = do +-- > rs <- doQuery c (iterInner2 outer inner) [] +-- > result' ((inner,c):acc) +-- > iterInner2 outer inner (i::Int) acc = do +-- > liftIO (putStrLn (show outer ++ " " ++ show inner ++ " " ++ show i)) +-- > result' (i:acc) +-- > withTransaction RepeatableRead $ do +-- > rs <- doQuery (sql q) iterMain [] +-- > return () + +-- Note that the PostgreSQL example can also be written like this +-- (except, of course, that the actual query text is that +-- from the PostgreSQL example). + + + +-- -------------------------------------------------------------------- +-- -- Haddock notes: +-- -------------------------------------------------------------------- + +-- The best way (that I've found) to get a decent introductory/explanatory +-- section for the module is to break the explanation into named chunks +-- (these begin with -- $<chunk-name>), +-- put the named chunks at the end, and reference them in the export list. + +-- You *can* write the introduction inline, as part of the module description, +-- but Haddock has no way to make headings. +-- Instead, if you make an explicit export-list then you can use +-- the "-- *", "-- **", etc, syntax to give section headings. + +-- (Note: if you don't use an explicit export list, then Haddock will use "-- *" etc +-- comments to make headings. The headings will appear in the docs in the the locations +-- as they do in the source, as do functions, data types, etc.) + +-- - One blank line continues a comment block. Two or more end it. +-- - The module comment must contain a empty line between "Portability: ..." and the description. +-- - bullet-lists: +-- - items must be preceded by an empty line. +-- - each list item must start with "*". +-- - code-sections: +-- - must be preceded by an empty line. +-- - use " >" rather than @...@, because "@" allows markup translation, where " >" doesn't. +-- - @inline code (monospaced font)@ +-- - /emphasised text/ +-- - links: "Another.Module", 'someIdentifier' (same module), +-- 'Another.Module.someIdentifier', <http:/www.haskell.org/haddock> +
+ Database/InternalEnumerator.hs view
@@ -0,0 +1,268 @@+ +-- | +-- Module : Database.InternalEnumerator +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + +-- This is the interface between the middle Enumerator layer and the +-- low-level, Database-specific layer. This file is not exported to the end user. + +-- Only the programmer for a new back-end needs to consult this file. + + +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE FunctionalDependencies #-} +{-# LANGUAGE DeriveDataTypeable #-} + +module Database.InternalEnumerator + ( + -- * Session object. + ISession(..), ConnectA(..) + , Statement(..), Command(..), EnvInquiry(..) + , PreparationA(..), IPrepared(..) + , PreparedStmt(..) + , BindA(..), DBBind(..) + , IsolationLevel(..) + , Position + , IQuery(..) + , DBType(..) + , throwIfDBNull + -- * Exceptions and handlers + , DBException(..) + , throwDB + , ColNum, RowNum + , SqlState, SqlStateClass, SqlStateSubClass + ) where + +import Data.Typeable +import Control.Exception (throw, Exception) + +data IsolationLevel = + ReadUncommitted + | ReadCommitted + | RepeatableRead + | Serialisable + | Serializable -- ^ for alternative spellers + deriving (Show, Eq, Ord, Enum) + + +-- | A wrapper around the action to open the database. That wrapper is not +-- exported to the end user. The only reason for the wrapper is to +-- guarantee that the only thing to do with the result of +-- 'Database.Enumerator.Sqlite.connect' function is to pass it out +-- directly to 'Database.Enumerator.withSession'. + +newtype ConnectA sess = ConnectA (IO sess) deriving Typeable + + + +-- Position within the result set. Not for the end user. + +type Position = Int + +-- Needed for exceptions + +type RowNum = Int +type ColNum = Int + +-- -------------------------------------------------------------------- +-- -- ** Exceptions and handlers +-- -------------------------------------------------------------------- + +type SqlStateClass = String +type SqlStateSubClass = String +type SqlState = (SqlStateClass, SqlStateSubClass) + +data DBException + -- | DBMS error message. + = DBError SqlState Int String + | DBFatal SqlState Int String + -- | the iteratee function used for queries accepts both nullable (Maybe) and + -- non-nullable types. If the query itself returns a null in a column where a + -- non-nullable type was specified, we can't handle it, so DBUnexpectedNull is thrown. + | DBUnexpectedNull RowNum ColNum + -- | Thrown by cursor functions if you try to fetch after the end. + | DBNoData + deriving (Typeable, Show) + +instance Exception DBException + +-- | Throw a DBException. It's just a type-specific 'Control.Exception.throwDyn'. + +throwDB :: DBException -> a +throwDB = throw + + +-- -------------------------------------------------------------------- +-- -- ** Session interface +-- -------------------------------------------------------------------- + +-- | The 'ISession' class describes a database session to a particular +-- DBMS. Oracle has its own Session object, SQLite has its own +-- session object (which maintains the connection handle to the database +-- engine and other related stuff). Session objects for different databases +-- normally have different types -- yet they all belong to the class ISession +-- so we can do generic operations like @commit@, @execDDL@, etc. +-- in a database-independent manner. + +-- Session objects per se are created by database connection\/login functions. + +-- The class 'ISession' is thus an interface between low-level (and +-- database-specific) code and the Enumerator, database-independent +-- code. +-- The 'ISession' class is NOT visible to the end user -- neither the class, +-- nor any of its methods. + +-- The 'ISession' class describes the mapping from connection object to +-- the session object. The connection object is created by the end user +-- (and this is how the end user tells which particular back end he wants). +-- The session object is not accessible by the end user in any way. +-- Even the type of the session object should be hidden! + +class ISession sess where + disconnect :: sess -> IO () + beginTransaction :: sess -> IsolationLevel -> IO () + commit :: sess -> IO () + rollback :: sess -> IO () + + +-- We can have several types of statements: just plain strings, +-- strings bundled with tuning parameters, prepared statements. +-- BTW, statement with unbound variables should have a different type +-- from that of the statement without bound variables or the statement +-- with all bound variables. + +-- | 'Command' is not a query: command deletes or updates rows, creates\/drops +-- tables, or changes database state. +-- 'executeCommand' returns the number of affected rows (or 0 if DDL i.e. not DML). + +class ISession sess => Command stmt sess where + -- insert/update/delete; returns number of rows affected + executeCommand :: sess -> stmt -> IO Int + +class ISession sess => + EnvInquiry inquirykey sess result | inquirykey sess -> result where + inquire :: inquirykey -> sess -> IO result + + +-- | 'Statement' defines the API for query objects i.e. +-- which types can be queries. + +class ISession sess => Statement stmt sess q | stmt sess -> q where + makeQuery :: sess -> stmt -> IO q + + +-- |The class IQuery describes the class of query objects. Each +-- database (that is, each Session object) has its own Query object. +-- We may assume that a Query object includes (at least, conceptually) +-- a (pointer to) a Session object, so a Query object determines the +-- Session object. +-- A back-end provides an instance (or instances) of IQuery. +-- The end user never seens the IQuery class (let alone its methods). + +-- Can a session have several types of query objects? +-- Let's assume that it can: but a statement plus the session uniquely +-- determine the query, + +-- Note that we explicitly use IO monad because we will have to explicitly +-- do FFI. + +class ISession sess => IQuery q sess b | q -> sess, q -> b + where + fetchOneRow :: q -> IO Bool + currentRowNum :: q -> IO Int + freeBuffer :: q -> b -> IO () + destroyQuery :: q -> IO () + +-- |A \'buffer\' means a column buffer: a data structure that points to a +-- block of memory allocated for the values of one particular +-- column. Since a query normally fetches a row of several columns, we +-- typically deal with a list of column buffers. Although the column data +-- are typed (e.g., Integer, CalendarDate, etc), column buffers hide that +-- type. Think of the column buffer as Dynamics. The class DBType below +-- describes marshalling functions, to fetch a typed value out of the +-- \'untyped\' columnBuffer. + +-- Different DBMS's (that is, different session objects) have, in +-- general, columnBuffers of different types: the type of Column Buffer +-- is specific to a database. +-- So, ISession (m) uniquely determines the buffer type (b)?? +-- Or, actually, a query uniquely determines the buffer. + + +-- | The class DBType is not used by the end-user. +-- It is used to tie up low-level database access and the enumerator. +-- A database-specific library must provide a set of instances for DBType. + +class DBType a q b | q -> b where + allocBufferFor :: a -> q -> Position -> IO b + fetchCol :: q -> b -> IO a + +-- | Used by instances of DBType to throw an exception +-- when a null (Nothing) is returned. +-- Will work for any type, as you pass the fetch action in the fetcher arg. + +throwIfDBNull :: (Monad m) => m (RowNum, ColNum) -> m (Maybe a) -> m a +throwIfDBNull pos fetcher = do + v <- fetcher + case v of + Nothing -> do + (row,col) <- pos + throwDB (DBUnexpectedNull row col) + Just m -> return m + + + +-- ------------------------------------------------------------------------ +-- Prepared commands and statements + +newtype PreparedStmt mark stmt = PreparedStmt stmt + +-- | This type is not visible to the end user (cf. ConnectA). It forms a private +-- `communication channel' between Database.Enumerator and a back end. + +-- Why don't we make a user-visible class with a @prepare@ method? +-- Because it means to standardize the preparation method signature +-- across all databases. Some databases need more parameters, some +-- fewer. There may be several statement preparation functions within one +-- database. So, instead of standardizing the signature of the +-- preparation function, we standardize on the _result_ of that +-- function. To be more precise, we standardize on the properties of the +-- result: whatever it is, the eventual prepared statement should be +-- suitable to be passed to 'bindRun'. + +newtype PreparationA sess stmt = PreparationA (sess -> IO stmt) + + +class ISession sess => IPrepared stmt sess bound_stmt bo + | stmt -> bound_stmt, stmt -> bo where + bindRun :: sess -> stmt -> [BindA sess stmt bo] -> (bound_stmt -> IO a) -> IO a + -- Should this be here? we have a need to free statements + -- separately from result-sets (which are handled by IQuery.destroyQuery). + -- It might be useful to prepare a statement, use it a number of times + -- (so many result-sets are created+destroyed), and then destroy it, + -- so it has a lifecycle independent of Queries. + destroyStmt :: sess -> stmt -> IO () + + +-- | The binding object (bo) below is very abstract, on purpose. +-- It may be |IO a|, it may be String, it may be a function, etc. +-- The binding object can hold the result of marshalling, +-- or bo can hold the current counter, etc. +-- Different databases do things very differently: +-- compare PostgreSQL and the Stub (which models Oracle). + +newtype BindA sess stmt bo = BindA (sess -> stmt -> bo) + +-- | The class DBBind is not used by the end-user. +-- It is used to tie up low-level database access and the enumerator. +-- A database-specific library must provide a set of instances for DBBind. +-- The latter are the dual of DBType. + +class ISession sess => DBBind a sess stmt bo | stmt -> bo where + -- | This is really just a wrapper that lets us write lists of + -- heterogenous bind values e.g. @[bindP \"string\", bindP (0::Int), ...]@ + bindP :: a -> BindA sess stmt bo
+ Database/Oracle/Enumerator.hs view
@@ -0,0 +1,1059 @@+ +-- | +-- Module : Database.Oracle.Enumerator +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + +-- Oracle OCI implementation of Database.Enumerator. + + +{-# LANGUAGE OverlappingInstances #-} +{-# LANGUAGE UndecidableInstances #-} +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE DeriveDataTypeable #-} +{-# LANGUAGE ScopedTypeVariables #-} + +module Database.Oracle.Enumerator + ( Session, connect + , prepareQuery, prepareLargeQuery, prepareCommand, prepareLargeCommand + , sql, sqlbind, prefetch, cmdbind + , StmtHandle, Out(..) + , module Database.Enumerator + ) +where + + +import Database.Enumerator +import Database.InternalEnumerator +import Database.Oracle.OCIConstants +import qualified Database.Oracle.OCIFunctions as OCI +import Database.Oracle.OCIFunctions + ( OCIHandle, EnvHandle, ErrorHandle, ServerHandle, ConnHandle, SessHandle, StmtHandle + , OCIException (..), catchOCI) +import Foreign +import Foreign.C +import Control.Monad +import Control.Exception +import Control.Monad.Trans +import Control.Monad.Reader +import Data.Char (toLower) +import Data.Dynamic +import Data.List (isPrefixOf) +import Data.IORef +import Data.Int +import Data.Time +import System.IO (hPutStrLn, stderr) +import System.Time + + +-- -------------------------------------------------------------------- +-- -- ** Error handling +-- -------------------------------------------------------------------- + +nullAction :: IO () +nullAction = return () + + +between i (l, u) = i >= l && i <= u + +-- Where did I find these mappings?... + +errorSqlState :: Int -> (String, String) +errorSqlState 0 = ("00", "000") +-- 02 - no data +errorSqlState 1403 = ("02", "000") +errorSqlState 1095 = ("02", "000") +-- 23 - integrity violation +errorSqlState 1 = ("23", "000") +errorSqlState e | e >= 2290 && e <= 2299 = ("23", "000") +-- 42 - syntax error or access rule violation +errorSqlState 22 = ("42", "000") +errorSqlState 251 = ("42", "000") +errorSqlState e | e `between` (900, 999) = ("42", "000") +errorSqlState 1031 = ("42", "000") +errorSqlState e | e `between` (1490, 1493) = ("42", "000") +errorSqlState e | e `between` (1700, 1799) = ("42", "000") +errorSqlState e | e `between` (1900, 2099) = ("42", "000") +errorSqlState e | e `between` (2140, 2289) = ("42", "000") +errorSqlState e | e `between` (2420, 2424) = ("42", "000") +errorSqlState e | e `between` (2450, 2499) = ("42", "000") +errorSqlState e | e `between` (3276, 3299) = ("42", "000") +errorSqlState e | e `between` (4040, 4059) = ("42", "000") +errorSqlState e | e `between` (4070, 4099) = ("42", "000") +-- 08 - connection errors +errorSqlState 12154 = ("08", "001") -- TNS: can't resolve service name +-- unspecified error +errorSqlState _ = ("01", "000") + +throwSqlError e m = do + let + s@(ssc,sssc) = errorSqlState e + ec = case ssc of + "XX" -> DBFatal + "58" -> DBFatal + "57" -> DBFatal + "54" -> DBFatal + "53" -> DBFatal + "08" -> DBFatal + _ -> DBError + throwDB (ec s e m) + + +-- |rethrow converts an OCIException to a DBException. +-- The third parameter is an IO action that you can use to clean up any handles. +-- First we get the error message from the Env or ErrorHandle, +-- and then we run the cleanup action to free any allocated handles. +-- (Obviously, we must extract the error message _before_ we free the handles.) +-- If there's no cleanup action required then simply pass nullAction. + +class OCIExceptionHandler a where + rethrow :: a -> OCIException -> IO () -> IO b + +instance OCIExceptionHandler ErrorHandle where + rethrow err ex finaliser = do + (e, m) <- OCI.formatErrorMsg ex err + finaliser + throwSqlError e m + +instance OCIExceptionHandler EnvHandle where + rethrow env ex finaliser = do + (e, m) <- OCI.formatEnvMsg ex env + finaliser + throwSqlError e m + + +-- |What do we do if creating the first handle (Environment) fails? +-- There's no Env- or ErrorHandle to get the error message from, +-- so do the best we can by constructing a message with formatErrorCodeDesc. +-- Still throws DBException. + +reportOCIExc :: OCIException -> IO a +reportOCIExc (OCIException e m) = do + let s = OCI.formatErrorCodeDesc e m + printError s + throwDB (DBError (errorSqlState 0) 0 s) + return undefined + +printError :: String -> IO () +printError s = hPutStrLn stderr s + +-- -------------------------------------------------------------------- +-- -- ** OCI Function Wrappers +-- -------------------------------------------------------------------- + +-- These wrappers ensure that only DBExceptions are thrown, +-- and never OCIExceptions. + +data Session = Session + { envHandle :: EnvHandle + , errorHandle :: ErrorHandle + , connHandle :: ConnHandle + } + deriving Typeable + +class FreeHandle ht where dispose :: ht -> IO () + +instance FreeHandle EnvHandle where dispose h = freeHandle (castPtr h) oci_HTYPE_ENV +instance FreeHandle ErrorHandle where dispose h = freeHandle (castPtr h) oci_HTYPE_ERROR +instance FreeHandle ServerHandle where dispose h = freeHandle (castPtr h) oci_HTYPE_SERVER +instance FreeHandle ConnHandle where dispose h = freeHandle (castPtr h) oci_HTYPE_SVCCTX +instance FreeHandle SessHandle where dispose h = freeHandle (castPtr h) oci_HTYPE_SESSION +instance FreeHandle StmtHandle where dispose h = freeHandle (castPtr h) oci_HTYPE_STMT + + +-- |Reports and ignores any errors when freeing handles. +-- Will catch attempts to free invalid (already freed?) handles. + +freeHandle :: OCIHandle -> CInt -> IO () +freeHandle ocihandle handleType = catchOCI ( do + OCI.handleFree handleType ocihandle + ) (\(OCIException e m) -> do + let s = OCI.formatErrorCodeDesc e m + printError s + ) + +-- |Assumes that if an exception is raised, +-- the Env and Error handles should be freed. + +inOCI :: EnvHandle -> ErrorHandle -> IO a -> IO a +inOCI env err action = catchOCI action $ \e -> do + rethrow err e $ do + dispose err + dispose env + + +-- |Does not free handles when exception raised. + +inSession :: Session -> (EnvHandle -> ErrorHandle -> ConnHandle -> IO a) -> IO () -> IO a +inSession session action finaliser = do + let + env = envHandle session + err = errorHandle session + conn = connHandle session + catchOCI (action env err conn) (\e -> rethrow err e finaliser) + + +getEnv :: IO EnvHandle +getEnv = catchOCI OCI.envCreate reportOCIExc + +getErr :: EnvHandle -> IO ErrorHandle +getErr env = catchOCI ( do + err <- OCI.handleAlloc oci_HTYPE_ERROR (castPtr env) + return (castPtr err) + ) (\e -> rethrow env e (dispose env)) + + +getServer :: EnvHandle -> ErrorHandle -> IO ServerHandle +getServer env err = inOCI env err $ do + server <- OCI.handleAlloc oci_HTYPE_SERVER (castPtr env) + return (castPtr server) + + +getConnection :: EnvHandle -> ErrorHandle -> IO ConnHandle +getConnection env err = inOCI env err $ do + conn <- OCI.handleAlloc oci_HTYPE_SVCCTX (castPtr env) + return (castPtr conn) + + +getSessionHandle :: EnvHandle -> ErrorHandle -> IO SessHandle +getSessionHandle env err = inOCI env err $ do + session <- OCI.handleAlloc oci_HTYPE_SESSION (castPtr env) + return (castPtr session) + + +-- |The idea with multiple logons is to first connect to the server. +-- Then you create a connection and a session, set the user id details, +-- and begin the session. +-- When finished, you end the session, +-- detach from the server, and free the handles. +-- So we should have, globally, one EnvHandle and one ErrorHandle, +-- and then, per session, one ServerHandle, one ConnHandle, and one SessHandle. +-- Also, for each server (or Instance, in Oracle-speak), we could share +-- the ServerHandle among the many ConnHandles and SessHandles. +-- At the moment we're being lazy, +-- and not reusing the Env and ErrorHandles for new connections. + +startServerSession :: String -> String -> EnvHandle -> ErrorHandle -> ServerHandle -> IO ConnHandle +startServerSession user pswd env err server = do + conn <- getConnection env err + -- the connection holds a reference to the server in one of its attributes + OCI.setHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX (castPtr server) oci_ATTR_SERVER + session <- getSessionHandle env err + if (user == "") + then do + OCI.sessionBegin err conn session oci_CRED_EXT + else do + OCI.setHandleAttrString err (castPtr session) oci_HTYPE_SESSION user oci_ATTR_USERNAME + OCI.setHandleAttrString err (castPtr session) oci_HTYPE_SESSION pswd oci_ATTR_PASSWORD + OCI.sessionBegin err conn session oci_CRED_RDBMS + -- the connection also holds a reference to the session in one of its attributes + OCI.setHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX (castPtr session) oci_ATTR_SESSION + -- and we need to create a valid transaction handle for the connection, too. + trans <- OCI.handleAlloc oci_HTYPE_TRANS (castPtr env) + OCI.setHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX (castPtr trans) oci_ATTR_TRANS + return conn + + +logon :: String -> String -> String -> EnvHandle -> ErrorHandle -> IO ConnHandle +logon user pswd dbname env err = inOCI env err $ do + server <- getServer env err + OCI.serverAttach err server dbname + startServerSession user pswd env err server + + +logoff :: ErrorHandle -> ConnHandle -> IO () +logoff err conn = catchOCI (do + session <- OCI.getHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX oci_ATTR_SESSION + server <- OCI.getHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX oci_ATTR_SERVER + OCI.sessionEnd err conn session + OCI.serverDetach err server + dispose session + dispose conn + dispose server + ) (\e -> rethrow err e nullAction) + + + + +dbConnect :: String -> String -> String -> IO Session +dbConnect user pswd dbname = do + env <- getEnv + err <- getErr env + conn <- logon user pswd dbname env err + return (Session env err conn) + + + +dbDisconnect :: Session -> IO () +dbDisconnect session = do + let + env = envHandle session + err = errorHandle session + conn = connHandle session + logoff err conn + dispose err + dispose env + OCI.terminate + + +-- |Oracle only supports ReadCommitted and Serialisable. +-- If you ask for RepeatableRead, we must go one better and choose Serialisable +-- (ReadCommitted is no good because you can get non-reapeatable reads). +-- Oracle has a ReadOnly mode which will give you RepeatableRead, +-- but you can't do any updates. + +-- Oracle's default (and weakest) behaviour is ReadCommitted; +-- there's no equivalent for ReadUncommitted. + +beginTrans :: Session -> IsolationLevel -> IO () +beginTrans session isolation = inSession session + (\_ err conn -> do + case isolation of + ReadUncommitted -> OCI.beginTrans err conn oci_TRANS_READWRITE + ReadCommitted -> OCI.beginTrans err conn oci_TRANS_READWRITE + RepeatableRead -> OCI.beginTrans err conn oci_TRANS_SERIALIZABLE + Serialisable -> OCI.beginTrans err conn oci_TRANS_SERIALIZABLE + Serializable -> OCI.beginTrans err conn oci_TRANS_SERIALIZABLE + ) nullAction + + + +commitTrans :: Session -> IO () +commitTrans session = inSession session + (\_ err conn -> OCI.commitTrans err conn) + nullAction + +rollbackTrans :: Session -> IO () +rollbackTrans session = inSession session + (\_ err conn -> OCI.rollbackTrans err conn) + nullAction + + + +getStmt :: Session -> IO StmtHandle +getStmt session = inSession session + (\ env err _ -> do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + return (castPtr stmt) + ) nullAction + + +closeStmt :: Session -> StmtHandle -> IO () +closeStmt _ stmt = dispose stmt + + +-- FIXME stmt should not be closed by these functions, +-- because they don't create it. +-- stmt should be closed in function that creates it. + +setPrefetchCount :: Session -> StmtHandle -> Int -> IO () +setPrefetchCount session stmt count = inSession session + (\_ err _ -> with count $ \countPtr -> + OCI.setHandleAttr err (castPtr stmt) oci_HTYPE_STMT countPtr oci_ATTR_PREFETCH_ROWS + ) (closeStmt session stmt) + + +stmtPrepare :: Session -> StmtHandle -> String -> IO () +stmtPrepare session stmt sql = inSession session + (\_ err _ -> OCI.stmtPrepare err stmt sql + ) (closeStmt session stmt) + + +word32ToInt :: Word32 -> Int +word32ToInt n = fromIntegral n + +getRowCount :: Session -> StmtHandle -> IO Int +getRowCount session stmt = inSession session + (\_ err _ -> do + rc <- OCI.getHandleAttr err (castPtr stmt) oci_HTYPE_STMT oci_ATTR_ROW_COUNT + return (word32ToInt rc) + ) (closeStmt session stmt) + + +execute :: Session -> StmtHandle -> Int -> IO Int +execute session stmt iterations = inSession session + (\_ err conn -> do + OCI.stmtExecute err conn stmt iterations + getRowCount session stmt + ) (closeStmt session stmt) + + +fetchRow :: Session -> PreparedStmtObj -> IO CInt +fetchRow session stmt = inSession session + (\_ err _ -> OCI.stmtFetch err (stmtHandle stmt)) + nullAction -- cleanup handled by doQuery1Maker + + +defineCol :: Session -> PreparedStmtObj -> Int -> Int -> CInt -> IO OCI.ColumnInfo +defineCol session stmt posn bufsize sqldatatype = inSession session + (\_ err _ -> OCI.defineByPos err (stmtHandle stmt) posn bufsize sqldatatype) + (closeStmt session (stmtHandle stmt)) + +bindByPos :: Session -> PreparedStmtObj -> Int -> CShort -> OCI.BufferPtr -> Int -> CInt -> IO () +bindByPos session stmt posn nullind val bufsize sqldatatype = inSession session + (\_ err _ -> OCI.bindByPos err (stmtHandle stmt) posn nullind val bufsize sqldatatype) + (closeStmt session (stmtHandle stmt)) + +bindOutputByPos :: Session -> PreparedStmtObj -> Int -> OCI.BindBuffer -> Int -> CInt -> IO OCI.BindHandle +bindOutputByPos session stmt posn buffer bufsize sqldatatype = inSession session + (\_ err _ -> OCI.bindOutputByPos err (stmtHandle stmt) posn buffer bufsize sqldatatype) + (closeStmt session (stmtHandle stmt)) + +-- -------------------------------------------------------------------- +-- -- ** Sessions +-- -------------------------------------------------------------------- + +connect :: String -> String -> String -> ConnectA Session +connect user pswd dbname = ConnectA (dbConnect user pswd dbname) + +-- -------------------------------------------------------------------- +-- -- Statements and Commands +-- -------------------------------------------------------------------- + +-- ==== A wrapper for SQL statements ==== + +-- When we execute queries with the OCI, +-- we need to specify how many times the statement should be executed. +-- For select statements it is zero (!?), while everything else is one +-- (>1 executions is for array binds). + +-- For a select, if you have defined output buffers then the iterations +-- parameter for 'execute' +-- says how many rows to put in the buffers immediately after the execute +-- (so there's no need for a call to OCIStmtFetch). +-- We don't use this, and set up the buffers after the execute. + +-- So there's a distinction between queries and commands. +-- Note that PL/SQL blocks which populate output bind buffers +-- are treated like queries by our library, +-- so we need some way of distinguishing between queries and commands. + +newtype QueryString = QueryString String + +sql :: String -> QueryString +sql str = QueryString str + + +instance Command QueryString Session where + executeCommand sess (QueryString str) = doCommand sess str + +doCommand sess str = do + stmt <- getStmt sess + -- stmtPrepare and execute both close the stmt if an exception is thrown, + -- so there should be no need for bracket here. + stmtPrepare sess stmt str + rc <- execute sess stmt 1 + closeStmt sess stmt + return rc + + +instance Command String Session where + executeCommand sess str = executeCommand sess (sql str) + +data CommandBind = CommandBind String [BindA Session PreparedStmtObj BindObj] + +cmdbind :: String -> [BindA Session PreparedStmtObj BindObj] -> CommandBind +cmdbind sql parms = CommandBind sql parms + +instance Command CommandBind Session where + executeCommand sess (CommandBind sqltext bas) = do + let (PreparationA pa) = prepareStmt' 0 sqltext FreeWithQuery CommandType + ps <- pa sess + bindRun sess ps bas (\(BoundStmt bs) -> getRowCount sess (stmtHandle bs)) + +instance Command BoundStmt Session where + executeCommand s (BoundStmt pstmt) = + getRowCount s (stmtHandle pstmt) + + +instance ISession Session where + disconnect sess = dbDisconnect sess + beginTransaction sess isolation = beginTrans sess isolation + commit sess = commitTrans sess + rollback sess = rollbackTrans sess + + +-- We need to keep track of the scope of the PreparedStmtObj +-- i.e. should it be freed when the Query (result-set) is freed, +-- or does it have a longer lifetime? +-- PreparedStmtObjs created by prepareStmt have a lifetime possibly +-- longer than the result-set; users should use withPreparedStatement +-- to manage these. + +-- PreparedStmtObjs can also be created internally by various instances +-- of makeQuery (in class Statement), and these will usually have the +-- same lifetime/scope as that of the Query (result-set). + +data StmtLifetime = FreeWithQuery | FreeManually + +-- We also need to note if the statement is a query (select) +-- or some sort of command. This influences subsequent behaviour in two ways: +-- 1. when execute is done, we specify either 0 or 1 iterations, +-- for selects or or commands, respectively (see bindRun) +-- 2. when fetchRow is called by doQuery, for selects we call OCI stmtFetch, +-- but for commands we ignore the call (do nothing), because the +-- output buffers will already have been filled. + +data StmtType = SelectType | CommandType + +data PreparedStmtObj = PreparedStmtObj + { stmtLifetime :: StmtLifetime + , stmtType :: StmtType + , stmtHandle :: StmtHandle + , stmtSession :: Session + , stmtCursors :: IORef [RefCursor StmtHandle] + -- stmtBuffers are actually output bind buffers. + -- we package them to look like ColumnBuffers + -- (as created by allocBuffer) so that we can use them + -- like ColumnBuffers. + , stmtBuffers :: IORef [ColumnBuffer] + } + + +beginsWithSelect "" = False +beginsWithSelect text = isPrefixOf "select" . map toLower $ text +inferStmtType text = if beginsWithSelect text then SelectType else CommandType + +prepareQuery :: QueryString -> PreparationA Session PreparedStmtObj +prepareQuery (QueryString sqltext) = + prepareStmt' (prefetchRowCount defaultResourceUsage) sqltext FreeManually SelectType + +prepareLargeQuery :: Int -> QueryString -> PreparationA Session PreparedStmtObj +prepareLargeQuery count (QueryString sqltext) = + prepareStmt' count sqltext FreeManually SelectType + +prepareCommand :: QueryString -> PreparationA Session PreparedStmtObj +prepareCommand (QueryString sqltext) = + prepareStmt' 0 sqltext FreeManually CommandType + +-- | Seems like an odd alternative to 'prepareCommand' (what is a large command?) +-- but is actually useful for when the outer query it a procedure call that +-- returns one or more cursors. The prefetch count for the inner cursors is +-- inherited from the outer statement, which in this case is a command, rather +-- than a select. Normally prefetch would be irrelevant (and indeed it is for +-- the outer command), but we also save it in the statement so that it can be +-- reused for the child cursors. + +prepareLargeCommand :: Int -> QueryString -> PreparationA Session PreparedStmtObj +prepareLargeCommand n (QueryString sqltext) = + prepareStmt' n sqltext FreeManually CommandType + +prepareStmt' count sqltext lifetime stmtype = + PreparationA (\sess -> do + stmt <- getStmt sess + stmtPrepare sess stmt (OCI.substituteBindPlaceHolders sqltext) + setPrefetchCount sess stmt count + newPreparedStmt lifetime stmtype sess stmt + ) + +newPreparedStmt lifetime iteration sess stmt = do + c <- newIORef [] + b <- newIORef [] + + return (PreparedStmtObj lifetime iteration stmt sess c b) + +-- -------------------------------------------------------------------- +-- -- ** Binding +-- -------------------------------------------------------------------- + +newtype BoundStmt = BoundStmt { boundStmt :: PreparedStmtObj } + +type BindObj = Int -> IO () +newtype Out a = Out a + +instance IPrepared PreparedStmtObj Session BoundStmt BindObj where + bindRun sess stmt bas action = do + sequence_ (zipWith (\i (BindA ba) -> ba sess stmt i) [1..] bas) + let iteration = case (stmtType stmt) of + SelectType -> 0 + CommandType -> 1 + execute sess (stmtHandle stmt) iteration + writeIORef (stmtCursors stmt) [] + action (BoundStmt stmt) + destroyStmt sess pstmt = closeStmt sess (stmtHandle pstmt) + +instance DBBind (Maybe String) Session PreparedStmtObj BindObj where + bindP = makeBindAction + +instance DBBind (Out (Maybe String)) Session PreparedStmtObj BindObj where + bindP (Out v) = makeOutputBindAction v + +instance DBBind (Maybe Int) Session PreparedStmtObj BindObj where + bindP = makeBindAction + +instance DBBind (Out (Maybe Int)) Session PreparedStmtObj BindObj where + bindP (Out v) = makeOutputBindAction v + +-- I don't think Oracle supports int64 in v8i's OCI API... + +-- instance DBBind (Maybe Int64) Session PreparedStmtObj BindObj where +-- bindP = makeBindAction + +instance DBBind (Maybe Double) Session PreparedStmtObj BindObj where + bindP = makeBindAction + +instance DBBind (Out (Maybe Double)) Session PreparedStmtObj BindObj where + bindP (Out v) = makeOutputBindAction v + +instance DBBind (Maybe CalendarTime) Session PreparedStmtObj BindObj where + bindP = makeBindAction + +instance DBBind (Maybe UTCTime) Session PreparedStmtObj BindObj where + bindP = makeBindAction + +instance DBBind (Out (Maybe UTCTime)) Session PreparedStmtObj BindObj where + bindP (Out v) = makeOutputBindAction v + +-- StmtHandles (i.e. RefCursors) are output only, I think +-- (altough you have to pass a valid one in, or it'll hurl). +-- We create the StmtHandle here, so the user doesn't have to +-- (is this a bad idea?...) + +instance DBBind (Out (Maybe StmtHandle)) Session PreparedStmtObj BindObj where + bindP (Out v) = BindA (\sess stmt pos -> do + stmt2 <- getStmt sess + bindOutputMaybe sess stmt (Just stmt2) pos + ) + + + +-- Instances for non-Maybe types i.e. bare Int, Double, String, etc. + +instance DBBind (Maybe a) Session PreparedStmtObj BindObj + => DBBind a Session PreparedStmtObj BindObj where + bindP x = bindP (Just x) + +instance DBBind (Out (Maybe a)) Session PreparedStmtObj BindObj + => DBBind (Out a) Session PreparedStmtObj BindObj where + bindP (Out x) = bindP (Out (Just x)) + +-- Default instances, using generic Show. + +instance (Show a) => DBBind (Maybe a) Session PreparedStmtObj BindObj where + bindP (Just x) = bindP (Just (show x)) + bindP Nothing = bindP (Nothing `asTypeOf` Just "") + +instance (Show a) => DBBind (Out (Maybe a)) Session PreparedStmtObj BindObj where + bindP (Out (Just x)) = bindP (Out (Just (show x))) + bindP (Out Nothing) = bindP (Out (Nothing `asTypeOf` Just "")) + + +makeBindAction x = BindA (\ses st -> bindMaybe ses st x) + +bindMaybe :: (OracleBind a) + => Session -> PreparedStmtObj -> Maybe a -> Int -> IO () +bindMaybe sess stmt v pos = + bindWithValue v $ \ptrv -> do + bindByPos sess stmt pos (bindNullInd v) (castPtr ptrv) (bindDataSize v) (bindType v) + +-- Note currying... we don't provide the column-position; +-- it's provided when bindRun is invoked. + +makeOutputBindAction v = BindA (\sess stmt -> bindOutputMaybe sess stmt v) + +bindOutputMaybe :: (OracleBind a) + => Session -> PreparedStmtObj -> Maybe a -> Int -> IO () +bindOutputMaybe sess stmt v pos = do + buffer <- mallocForeignPtrBytes (bindBufferSize v) + nullind <- mallocForeignPtr + sizeind <- mallocForeignPtr + withForeignPtr buffer $ \bufptr -> + withForeignPtr nullind $ \indptr -> + withForeignPtr sizeind $ \szeptr -> do + poke (castPtr indptr) (bindNullInd v) + poke (castPtr szeptr) (bindDataSize v) -- input size + bindWriteBuffer (castPtr bufptr) v + bindOutputByPos sess stmt pos (nullind, buffer, sizeind) (bindBufferSize v) (bindType v) + let + colbuf = ColumnBuffer + { colBufBufferFPtr = buffer + , colBufNullFPtr = nullind + , colBufSizeFPtr = sizeind + , colBufColPos = 0 + , colBufSqlType = (bindType v) + } + appendOutputBindBuffer stmt colbuf + +-- If the bind values are output, then we save them in a list. +-- We can then use a doQuery to fetch the values, +-- just like the Postgres technique of returning values +-- as a set of tuples. +-- I guess there'll only ever be a single row to fetch +-- in the Oracle case, though. + +appendOutputBindBuffer stmt buffer = do + buffers <- readIORef (stmtBuffers stmt) + modifyIORef (stmtBuffers stmt) (++ [buffer { colBufColPos = 1 + length buffers }]) + + + + +class OracleBind a where + bindWithValue :: a -> (Ptr Word8 -> IO ()) -> IO () + bindWriteBuffer :: Ptr Word8 -> a -> IO () + bindDataSize :: a -> Int + bindBufferSize :: a -> Int + bindBufferSize v = bindDataSize v + bindNullInd :: a -> CShort + -- non-Maybe types aren't nullable, so null-ind is always 0 + -- for values in these types. + bindNullInd _ = 0 + bindType :: a -> CInt + +instance OracleBind a => OracleBind (Maybe a) where + bindWithValue (Just v) a = bindWithValue v a + bindWithValue Nothing a = return () + bindWriteBuffer b (Just v) = bindWriteBuffer b v + bindWriteBuffer b Nothing = return () + bindDataSize (Just v) = bindDataSize v + bindDataSize Nothing = 0 + bindBufferSize (Just v) = bindBufferSize v + bindBufferSize x@Nothing = + let (Just v) = (Just undefined) `asTypeOf` x in bindBufferSize v + bindNullInd (Just v) = 0 + bindNullInd Nothing = -1 + bindType (Just v) = bindType v + bindType Nothing = bindType (undefined :: a) + +instance OracleBind String where + -- FIXME should these be withUTF8String{Len} ? + bindWithValue v a = withCString v (\p -> a (castPtr p)) + bindWriteBuffer b s = withCStringLen s (\(p,l) -> + copyBytes (castPtr b) p (1+l)) + bindDataSize s = fromIntegral (length s) + bindBufferSize _ = 32000 + bindType _ = oci_SQLT_CHR + +instance OracleBind Int where + bindWithValue v a = withBinaryValue toCInt v (\p v -> poke (castPtr p) v) a + bindWriteBuffer b v = poke (castPtr b) v + bindDataSize _ = (sizeOf (toCInt 0)) + bindType _ = oci_SQLT_INT + +instance OracleBind Double where + bindWithValue v a = withBinaryValue toCDouble v (\p v -> poke (castPtr p) v) a + bindWriteBuffer b v = poke (castPtr b) v + bindDataSize _ = (sizeOf (toCDouble 0.0)) + bindType _ = oci_SQLT_FLT + +instance OracleBind CalendarTime where + bindWithValue v a = withBinaryValue id v (\p dt -> calTimeToBuffer (castPtr p) dt) a + bindWriteBuffer b v = calTimeToBuffer (castPtr b) v + bindDataSize _ = 7 + bindType _ = oci_SQLT_DAT + +instance OracleBind UTCTime where + bindWithValue v a = withBinaryValue id v (\p dt -> utcTimeToBuffer (castPtr p) dt) a + bindWriteBuffer b v = utcTimeToBuffer (castPtr b) v + bindDataSize _ = 7 + bindType _ = oci_SQLT_DAT + +instance OracleBind StmtHandle where + bindWithValue v a = alloca (\p -> poke p v >> a (castPtr p)) + bindWriteBuffer b v = poke (castPtr b) v + bindDataSize _ = sizeOf nullPtr + bindType _ = oci_SQLT_RSET + +withBinaryValue :: (OracleBind b) => + (b -> a) -- ^ convert Haskell value to C value + -> b -- ^ value to convert (we call bindSize on this value to get buffer size) + -> (Ptr Word8 -> a -> IO ()) -- ^ action to place converted value into buffer + -> (Ptr Word8 -> IO ()) -- ^ action to run over buffer; buffer will be freed on completion + -> IO () +withBinaryValue fn v pok action = + -- FIXME is bindBufferSize better here? + --allocaBytes (bindBufferSize v) $ \p -> do + allocaBytes (bindDataSize v) $ \p -> do + pok p (fn v) + action (castPtr p) + +clength = fromIntegral . length + +toCInt :: Int -> CInt; toCInt = fromIntegral +fromCInt :: CInt -> Int; fromCInt = fromIntegral +toCChar :: Char -> CChar; toCChar = toEnum . fromEnum +fromCChar :: CChar -> Char; fromCChar = toEnum . fromEnum +toCDouble :: Double -> CDouble; toCDouble = realToFrac +fromCDouble :: CDouble -> Double; fromCDouble = realToFrac +toCFloat :: Float -> CFloat; toCFloat = realToFrac +fromCFloat :: CFloat -> Float; fromCFloat = realToFrac + + +-- -------------------------------------------------------------------- +-- -- ** Queries +-- -------------------------------------------------------------------- + +-- We save a reference to the parent PreparedStmtObj. +-- In a lot of cases (the simple ones) the parent is that same +-- as the PreparedStmtObj. +-- It only differs when we use the NextResultSet instance of makeQuery. +-- It is only Nothing when we are processing a RefCursor; +-- in this case we don't want to save any nested cursors returned +-- by the query. + +data Query = Query + { queryStmt :: PreparedStmtObj + , querySess :: Session + , queryParent :: Maybe PreparedStmtObj + } + + +data QueryResourceUsage = QueryResourceUsage { prefetchRowCount :: Int } + +defaultResourceUsage :: QueryResourceUsage +defaultResourceUsage = QueryResourceUsage 100 -- sensible default? + +data QueryStringTuned = QueryStringTuned QueryResourceUsage String [BindA Session PreparedStmtObj BindObj] + +sqlbind :: String -> [BindA Session PreparedStmtObj BindObj] -> QueryStringTuned +sqlbind sql parms = QueryStringTuned defaultResourceUsage sql parms + +prefetch :: Int -> String -> [BindA Session PreparedStmtObj BindObj] -> QueryStringTuned +prefetch count sql parms = QueryStringTuned (QueryResourceUsage count) sql parms + +instance Statement BoundStmt Session Query where + makeQuery sess bstmt = return (Query (boundStmt bstmt) sess (Just (boundStmt bstmt))) + +instance Statement PreparedStmtObj Session Query where + makeQuery sess pstmt = return (Query pstmt sess (Just pstmt)) + +instance Statement QueryString Session Query where + makeQuery sess (QueryString sqltext) = makeQuery sess sqltext + +instance Statement String Session Query where + makeQuery sess sqltext = makeQuery sess (QueryStringTuned defaultResourceUsage sqltext []) + +-- Important to use FreeManually here... +-- If we destroy the StmtHandle when the query is done, +-- it does not allow us to re-use the StmtHandle, +-- which is vital for nested cursors +-- (mainly because I haven't figured out how to +-- marshal StmtHandles back to Haskell-land). +-- However, this means we have to process StmtHandles +-- immediately; we can't save them up and process them later, +-- after the parent query is done. + +-- Contrast this with the Postgres back-end, where the RefCursor +-- just contains a String, which is the cursor name. +-- It's no trouble to marshal a String back to Haskell-land. + +instance Statement (RefCursor StmtHandle) Session Query where + makeQuery sess (RefCursor stmt) = do + pstmt <- newPreparedStmt FreeManually SelectType sess stmt + return (Query pstmt sess Nothing) + +-- For NextResultSet, we call makeQuery passing (RefCursor StmtHandle). +-- This creates a query with no parent statement. +-- All other instances of Statement make a statement its own parent. + +instance Statement (NextResultSet mark PreparedStmtObj) Session Query where + makeQuery sess (NextResultSet (PreparedStmt pstmt)) = do + cursors <- readIORef (stmtCursors pstmt) + if null cursors then throwDB (DBError ("02", "000") (-1) "No more result sets to process.") else return () + writeIORef (stmtCursors pstmt) (tail cursors) + makeQuery sess (head cursors) + +instance Statement QueryStringTuned Session Query where + makeQuery sess (QueryStringTuned resUsage sqltext bas) = do + let + (PreparationA action) = + prepareStmt' (prefetchRowCount resUsage) sqltext FreeWithQuery SelectType + pstmt <- action sess + sequence_ (zipWith (\i (BindA ba) -> ba sess pstmt i) [1..] bas) + execute sess (stmtHandle pstmt) 0 + return (Query pstmt sess (Just pstmt)) + +instance Statement CommandBind Session Query where + makeQuery sess (CommandBind sqltext bas) = do + let + (PreparationA action) = + prepareStmt' 1 sqltext FreeWithQuery CommandType + pstmt <- action sess + sequence_ (zipWith (\i (BindA ba) -> ba sess pstmt i) [1..] bas) + execute sess (stmtHandle pstmt) 1 + return (Query pstmt sess (Just pstmt)) + + +data ColumnBuffer = ColumnBuffer + { colBufBufferFPtr :: OCI.ColumnResultBuffer + , colBufNullFPtr :: ForeignPtr CShort + , colBufSizeFPtr :: ForeignPtr CUShort + , colBufColPos :: Int + , colBufSqlType :: CInt + } + +instance IQuery Query Session ColumnBuffer where + destroyQuery query = do + let pstmt = queryStmt query + case stmtLifetime pstmt of + FreeWithQuery -> closeStmt (stmtSession pstmt) (stmtHandle pstmt) + _ -> return () + fetchOneRow query = do + let pstmt = queryStmt query + -- Only call fetchRow if there are no bind output buffers + -- If there are bind output buffers then assume this was a + -- procedure call. + -- In this case you will always get the same row over and over, + -- so you'd better be careful with your iteratees + buffers <- readIORef (stmtBuffers pstmt) + if not (null buffers) then return True + else do + rc <- fetchRow (querySess query) pstmt + return (rc /= oci_NO_DATA) + currentRowNum query = + getRowCount (querySess query) (stmtHandle (queryStmt query)) + freeBuffer q buffer = return () + + +-- This is where we differ the behaviour depending on the +-- type of statement: is it a regular query, +-- where we just create column buffers, or do we have +-- bind output buffers, in which case we return those +-- as the column buffers? + +allocBuffer query (bufsize, ociBufferType) colpos = do + buffers <- readIORef (stmtBuffers (queryStmt query)) + if null buffers + then do + (_, buf, nullptr, sizeptr) <- liftIO $ defineCol (querySess query) (queryStmt query) colpos bufsize ociBufferType + return $ ColumnBuffer + { colBufBufferFPtr = buf + , colBufNullFPtr = nullptr + , colBufSizeFPtr = sizeptr + , colBufColPos = colpos + , colBufSqlType = ociBufferType + } + else do + if length buffers >= colpos + then return (buffers !! (colpos - 1)) + else + throwDB (DBError ("02", "000") (-1) ( "There are " ++ show (length buffers) + ++ " output buffers, but you have asked for buffer " ++ show colpos )) + +-- When you allocate a StmtHandle define buffer (as opposed to a bind buffer) +-- you have to populate it with a valid StmtHandle before you call fetch. +-- FIXME when is this freed? When is the StmtHandle destroyed? + +allocStmtBuffer query colpos = do + colbuf <- allocBuffer query (sizeOf nullPtr, oci_SQLT_RSET) colpos + buffers <- readIORef (stmtBuffers (queryStmt query)) + -- if buffers is null then assume this is a define buffer, + -- rather than a bind buffer. + -- Bind buffers are stuffed into the stmtBuffers list + -- when they are created. + if null buffers + then do + -- If this is a define buffer (as opposed to bind buffer) + -- then shove a valid StmtHandle into it. + stmt <- getStmt (querySess query) + withForeignPtr (colBufBufferFPtr colbuf) $ \p -> poke (castPtr p) stmt + else return () + return colbuf + + +bufferToString :: ColumnBuffer -> IO (Maybe String) +bufferToString buffer = OCI.bufferToString (undefined, colBufBufferFPtr buffer, colBufNullFPtr buffer, colBufSizeFPtr buffer) + +bufferToCaltime :: ColumnBuffer -> IO (Maybe CalendarTime) +bufferToCaltime buffer = OCI.bufferToCaltime (colBufNullFPtr buffer) (colBufBufferFPtr buffer) + +bufferToUTCTime :: ColumnBuffer -> IO (Maybe UTCTime) +bufferToUTCTime buffer = OCI.bufferToUTCTime (colBufNullFPtr buffer) (colBufBufferFPtr buffer) + +calTimeToBuffer :: OCI.BufferPtr -> CalendarTime -> IO () +calTimeToBuffer buf ct = OCI.calTimeToBuffer buf ct + +utcTimeToBuffer :: OCI.BufferPtr -> UTCTime -> IO () +utcTimeToBuffer buf utc = OCI.utcTimeToBuffer buf utc + +bufferToInt :: ColumnBuffer -> IO (Maybe Int) +bufferToInt buffer = OCI.bufferToInt (colBufNullFPtr buffer) (colBufBufferFPtr buffer) + +bufferToDouble :: ColumnBuffer -> IO (Maybe Double) +bufferToDouble buffer = OCI.bufferToDouble (colBufNullFPtr buffer) (colBufBufferFPtr buffer) + +bufferToStmtHandle :: ColumnBuffer -> IO (RefCursor StmtHandle) +bufferToStmtHandle buffer = do + v <- OCI.bufferToStmtHandle (colBufBufferFPtr buffer) + return (RefCursor v) + + +-- Right now the StmtHandle in the buffer is updated with a new +-- cursor on each fetch. +-- If we call defineByPos before each fetch then we can provide +-- a fresh StmtHandle for each fetch (thus preserving the handles +-- from previous fetches), but this will require support from +-- Database.Enumerator i.e. we need to add a function, say reallocBuffers, +-- which is called before each row is fetched, +-- which will give us an opportunity to reallocate memory for buffers +-- if it is required. +-- This might be a bad idea though, because it is likely to lead +-- to space leaks. Perhaps the current approach of reusing the +-- StmtHandle is better from a memory management point-of-view. +-- That said, the Oracle DBMS has a fairly low limit (on the order +-- of 100 or so) on the number of open cursors, so perhaps space +-- leaks aren't as likely as I think. + +instance DBType (RefCursor StmtHandle) Query ColumnBuffer where + allocBufferFor _ q n = allocStmtBuffer q n + fetchCol q buffer = do + rawstmt <- OCI.bufferToStmtHandle (colBufBufferFPtr buffer) + appendRefCursor q (RefCursor rawstmt) + +appendRefCursor query refc = do + case queryParent query of + -- no parent stmt? => probably just a doQuery over a RefCursor. + -- Don't bother saving returned RefCursors. + Nothing -> return () + Just pstmt -> modifyIORef (stmtCursors pstmt) (++ [refc]) + return refc + + +instance DBType (Maybe String) Query ColumnBuffer where + allocBufferFor _ q n = allocBuffer q (16000, oci_SQLT_CHR) n + fetchCol q buffer = bufferToString buffer + +instance DBType (Maybe Int) Query ColumnBuffer where + allocBufferFor _ q n = allocBuffer q (4, oci_SQLT_INT) n + fetchCol q buffer = bufferToInt buffer + +instance DBType (Maybe Double) Query ColumnBuffer where + allocBufferFor _ q n = allocBuffer q (8, oci_SQLT_FLT) n + fetchCol q buffer = bufferToDouble buffer + +instance DBType (Maybe UTCTime) Query ColumnBuffer where + allocBufferFor _ q n = allocBuffer q (7, oci_SQLT_DAT) n + fetchCol q buffer = bufferToUTCTime buffer + +instance DBType (Maybe CalendarTime) Query ColumnBuffer where + allocBufferFor _ q n = allocBuffer q (7, oci_SQLT_DAT) n + fetchCol q buffer = bufferToCaltime buffer + +-- |This single polymorphic instance covers all of the +-- type-specific non-Maybe instances e.g. String, Int, Double, etc. + +instance DBType (Maybe a) Query ColumnBuffer + => DBType a Query ColumnBuffer where + allocBufferFor v q n = allocBufferFor (Just v) q n + fetchCol q buffer = throwIfDBNull (buffer_pos q buffer) (fetchCol q buffer) + +buffer_pos q buffer = do + row <- currentRowNum q + return (row, colBufColPos buffer) + + +-- |A polymorphic instance which assumes that the value is in a String column, +-- and uses Read to convert the String to a Haskell data value. + +instance (Show a, Read a) => DBType (Maybe a) Query ColumnBuffer where + allocBufferFor _ q n = allocBuffer q (16000, oci_SQLT_CHR) n + fetchCol q buffer = do + v <- bufferToString buffer + case v of + Just s -> if s == "" then return Nothing else return (Just (read s)) + Nothing -> return Nothing
+ Database/Oracle/OCIConstants.hs view
@@ -0,0 +1,178 @@+ +-- | +-- Module : Database.Oracle.OCIConstants +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + +-- Contains CInt equivalents of the #defines in the oci library headers. +-- This is not a complete set; just enough to get the Haskell libraries working. +-- This also might not be particularly portable, but I don't think Oracle are going +-- to change these in a hurry (that would break compiled programs, wouldn't it?). + + +module Database.Oracle.OCIConstants where + +import Foreign.C.Types + + +-- ** Used all over the place: + +oci_DEFAULT :: CInt +oci_DEFAULT = 0 + + +-- ** Handle types: + +-- | Found in $ORAHOME\/oci\/include\/oci.h + +[ oci_HTYPE_ENV + , oci_HTYPE_ERROR + , oci_HTYPE_SVCCTX + , oci_HTYPE_STMT + , oci_HTYPE_BIND + , oci_HTYPE_DEFINE + , oci_HTYPE_DESCRIBE + , oci_HTYPE_SERVER + , oci_HTYPE_SESSION + , oci_HTYPE_TRANS + ] = [1..10] :: [CInt] + + +-- ** Error code types: + +-- | Found in $ORAHOME\/oci\/include\/oci.h + +[ oci_SUCCESS + , oci_SUCCESS_WITH_INFO + , oci_RESERVED_FOR_INT_USE + , oci_NO_DATA + , oci_ERROR + , oci_INVALID_HANDLE + , oci_NEED_DATA + , oci_STILL_EXECUTING + , oci_CONTINUE + ] = + [0, 1, 200, 100, -1, -2, 99, -3123, -24200] :: [CInt] + + + +-- ** Attribute types: + +-- | Found in $ORAHOME\/oci\/include\/oci.h + +[ oci_ATTR_ENV + , oci_ATTR_SERVER + , oci_ATTR_SESSION + , oci_ATTR_TRANS + , oci_ATTR_ROW_COUNT + , oci_ATTR_PREFETCH_ROWS + , oci_ATTR_USERNAME + , oci_ATTR_PASSWORD + ] = [5,6,7,8,9,11,22,23] :: [CInt] + +-- ** Authentication options: + +-- | Found in $ORAHOME\/oci\/include\/oci.h + +oci_CRED_RDBMS :: CInt +oci_CRED_RDBMS = 1 +oci_CRED_EXT :: CInt +oci_CRED_EXT = 2 +oci_CRED_PROXY :: CInt +oci_CRED_PROXY = 3 + + + +-- ** Syntax types (i.e. does the DBMS understand v7 or v8 syntax, etc): + +-- | Found in $ORAHOME\/oci\/include\/oci.h + +oci_NTV_SYNTAX :: CInt +oci_NTV_SYNTAX = 1 + + + +-- ** Scrollable Cursor Options: + +-- | Found in $ORAHOME\/oci\/include\/oci.h + +oci_FETCH_NEXT :: CInt +oci_FETCH_NEXT = 2 +oci_FETCH_FIRST :: CInt +oci_FETCH_FIRST = 4 +oci_FETCH_LAST :: CInt +oci_FETCH_LAST = 8 +oci_FETCH_PRIOR :: CInt +oci_FETCH_PRIOR = 16 +oci_FETCH_ABSOLUTE :: CInt +oci_FETCH_ABSOLUTE = 32 +oci_FETCH_RELATIVE :: CInt +oci_FETCH_RELATIVE = 64 +oci_FETCH_RESERVED :: CInt +oci_FETCH_RESERVED = 128 + + + + +-- ** OCI datatypes: + +-- | Found in $ORAHOME\/oci\/include\/ocidfn.h + +oci_SQLT_CHR :: CInt +oci_SQLT_CHR = 1 +oci_SQLT_NUM :: CInt +oci_SQLT_NUM = 2 +oci_SQLT_INT :: CInt +oci_SQLT_INT = 3 +oci_SQLT_FLT :: CInt +oci_SQLT_FLT = 4 +oci_SQLT_STR :: CInt +oci_SQLT_STR = 5 +oci_SQLT_VNU :: CInt +oci_SQLT_VNU = 6 +oci_SQLT_LNG :: CInt +oci_SQLT_LNG = 8 +oci_SQLT_VCS :: CInt +oci_SQLT_VCS = 9 +oci_SQLT_RID :: CInt +oci_SQLT_RID = 11 +oci_SQLT_DAT :: CInt +oci_SQLT_DAT = 12 +oci_SQLT_VBI :: CInt +oci_SQLT_VBI = 15 +oci_SQLT_BIN :: CInt +oci_SQLT_BIN = 23 +oci_SQLT_LBI :: CInt +oci_SQLT_LBI = 24 +oci_SQLT_UIN :: CInt +oci_SQLT_UIN = 68 +oci_SQLT_LVC :: CInt +oci_SQLT_LVC = 94 +oci_SQLT_LVB :: CInt +oci_SQLT_LVB = 95 +oci_SQLT_AFC :: CInt +oci_SQLT_AFC = 96 +oci_SQLT_AVC :: CInt +oci_SQLT_AVC = 97 +oci_SQLT_RSET :: CInt +oci_SQLT_RSET = 116 + + + +-- ** Transaction types; parameters for ociTransStart. + +-- | Found in $ORAHOME\/oci\/include\/oci.h. +-- There are more than this, but they're related to complicated +-- transaction-management stuff in the OCI libraries that I don't understand. +-- These should be sufficient to support the simple transaction model +-- understood by most developers. + +oci_TRANS_READONLY :: CInt +oci_TRANS_READONLY = 0x00000100 -- 256 +oci_TRANS_READWRITE :: CInt +oci_TRANS_READWRITE = 0x00000200 -- 512 +oci_TRANS_SERIALIZABLE :: CInt +oci_TRANS_SERIALIZABLE = 0x00000400 -- 1024
+ Database/Oracle/OCIFunctions.hs view
@@ -0,0 +1,822 @@+ +-- | +-- Module : Database.Oracle.OCIFunctions +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + +-- Simple wrappers for OCI functions (FFI). + +-- The functions in this file are simple wrappers for OCI functions. +-- The wrappers add error detection and exceptions; +-- functions in this module raise 'OCIException'. +-- The next layer up traps these and turns them into 'Database.Enumerator.DBException'. + +-- Note that 'OCIException' /does not/ contain the error number and text +-- returned by 'getOCIErrorMsg'. +-- It is the job of the next layer (module) up to catch the 'OCIException' +-- and then call 'getOCIErrorMsg' to get the actual error details. +-- The 'OCIException' simply contains the error number returned by +-- the OCI call, and some text identifying the wrapper function. +-- See 'formatErrorCodeDesc' for the set of possible values for the OCI error numbers. + +{-# LANGUAGE ForeignFunctionInterface #-} +{-# LANGUAGE DeriveDataTypeable #-} + + +module Database.Oracle.OCIFunctions where + + +import Prelude hiding (catch) +import Database.Oracle.OCIConstants +import Database.Util +import Foreign +import Foreign.C +import Control.Monad +import Control.Exception +import Data.Dynamic +import Data.Time +import System.Time + + +-- | +-- * Each handle type has its own data type, to prevent stupid errors +-- i.e. using the wrong handle at the wrong time. + +-- * In GHC you can simply say @data OCIStruct@ i.e. there's no need for @= OCIStruct@. +-- I've decided to be more portable, as it doesn't cost much. + +-- * Use castPtr if you need to convert handles (say 'OCIHandle' to a more specific type, or vice versa). + +data OCIStruct = OCIStruct +type OCIHandle = Ptr OCIStruct -- generic Handle for OCI functions that return Handles +data OCIBuffer = OCIBuffer -- generic buffer. Could hold anything: value or pointer. +type BufferPtr = Ptr OCIBuffer +type BufferFPtr = ForeignPtr OCIBuffer +type ColumnResultBuffer = ForeignPtr OCIBuffer -- use ForeignPtr to ensure GC'd +-- triple of (nullind, buffer, size) +type BindBuffer = (ForeignPtr CShort, ForeignPtr OCIBuffer, ForeignPtr CUShort) +data Context = Context +type ContextPtr = Ptr Context + +data EnvStruct = EnvStruct +type EnvHandle = Ptr EnvStruct +data ErrorStruct = ErrorStruct +type ErrorHandle = Ptr ErrorStruct +data ServerStruct = ServerStruct +type ServerHandle = Ptr ServerStruct +data UserStruct = UserStruct +type UserHandle = Ptr UserStruct +data ConnStruct = ConnStruct +type ConnHandle = Ptr ConnStruct -- AKA Service Context +data SessStruct = SessStruct +type SessHandle = Ptr SessStruct +data StmtStruct = StmtStruct +type StmtHandle = Ptr StmtStruct +data DefnStruct = DefnStruct +type DefnHandle = Ptr DefnStruct +data ParamStruct = ParamStruct +type ParamHandle = Ptr ParamStruct +data BindStruct = BindStruct +type BindHandle = Ptr BindStruct +type ColumnInfo = (DefnHandle, ColumnResultBuffer, ForeignPtr CShort, ForeignPtr CUShort) + + +-- |Low-level, OCI library errors. + +data OCIException = OCIException CInt String + deriving (Typeable, Show) + +-- If we can't derive Typeable then the following code should do the trick: + +-- > data OCIException = OCIException CInt String +-- > ociExceptionTc :: TyCon +-- > ociExceptionTc = mkTyCon "Database.Oracle.OCIFunctions.OCIException" +-- > instance Typeable OCIException where typeOf _ = mkAppTy ociExceptionTc [] + + +catchOCI :: IO a -> (OCIException -> IO a) -> IO a +throwOCI :: OCIException -> a +instance Exception OCIException +catchOCI = catch +throwOCI = throw + + +mkCInt :: Int -> CInt +mkCInt n = fromIntegral n + +mkCShort :: CInt -> CShort +mkCShort n = fromIntegral n + +mkCUShort :: CInt -> CUShort +mkCUShort n = fromIntegral n + +cStrLen :: CStringLen -> CInt +cStrLen = mkCInt . snd + +cStr :: CStringLen -> CString +cStr = fst + + + +-- --------------------------------------------------------------------------------- +-- -- ** Foreign OCI functions +-- --------------------------------------------------------------------------------- + + +foreign import ccall "OCIEnvCreate" ociEnvCreate :: Ptr EnvHandle -> CInt -> Ptr a -> FunPtr a -> FunPtr a -> FunPtr a -> CInt -> Ptr (Ptr a) -> IO CInt +foreign import ccall "OCIHandleAlloc" ociHandleAlloc :: OCIHandle -> Ptr OCIHandle -> CInt -> CInt -> Ptr a -> IO CInt +foreign import ccall "oci.h OCIHandleFree" ociHandleFree :: OCIHandle -> CInt -> IO CInt +foreign import ccall "oci.h OCIErrorGet" ociErrorGet :: OCIHandle -> CInt -> CString -> Ptr CInt -> CString -> CInt -> CInt -> IO CInt + + +foreign import ccall "oci.h OCIParamGet" ociParamGet :: OCIHandle -> CInt -> ErrorHandle -> Ptr OCIHandle -> CInt -> IO CInt +foreign import ccall "oci.h OCIAttrGet" ociAttrGet + :: OCIHandle -> CInt -> BufferPtr -> Ptr CInt -> CInt -> ErrorHandle -> IO CInt +foreign import ccall "oci.h OCIAttrSet" ociAttrSet + :: OCIHandle -> CInt -> BufferPtr -> CInt -> CInt -> ErrorHandle -> IO CInt + + +foreign import ccall "oci.h OCILogon" ociLogon + :: EnvHandle -> ErrorHandle -> Ptr ConnHandle -> CString -> CInt -> CString -> CInt -> CString -> CInt -> IO CInt +foreign import ccall "oci.h OCILogoff" ociLogoff :: ConnHandle -> ErrorHandle -> IO CInt +foreign import ccall "oci.h OCISessionBegin" ociSessionBegin :: ConnHandle -> ErrorHandle -> SessHandle -> CInt -> CInt -> IO CInt +foreign import ccall "oci.h OCISessionEnd" ociSessionEnd :: ConnHandle -> ErrorHandle -> SessHandle -> CInt -> IO CInt +foreign import ccall "oci.h OCIServerAttach" ociServerAttach :: ServerHandle -> ErrorHandle -> CString -> CInt -> CInt -> IO CInt +foreign import ccall "oci.h OCIServerDetach" ociServerDetach :: ServerHandle -> ErrorHandle -> CInt -> IO CInt +foreign import ccall "oci.h OCITerminate" ociTerminate :: CInt -> IO CInt + +foreign import ccall "oci.h OCITransStart" ociTransStart :: ConnHandle -> ErrorHandle -> Word8 -> CInt -> IO CInt +foreign import ccall "oci.h OCITransCommit" ociTransCommit :: ConnHandle -> ErrorHandle -> CInt -> IO CInt +foreign import ccall "oci.h OCITransRollback" ociTransRollback :: ConnHandle -> ErrorHandle -> CInt -> IO CInt + +foreign import ccall "oci.h OCIStmtPrepare" ociStmtPrepare :: StmtHandle -> ErrorHandle -> CString -> CInt -> CInt -> CInt -> IO CInt +foreign import ccall "oci.h OCIDefineByPos" ociDefineByPos + :: StmtHandle -> Ptr DefnHandle -> ErrorHandle -> CInt -> BufferPtr -> CInt -> CUShort -> Ptr CShort -> Ptr CUShort -> Ptr CUShort -> CInt -> IO CInt +foreign import ccall "oci.h OCIStmtExecute" ociStmtExecute :: ConnHandle -> StmtHandle -> ErrorHandle -> CInt -> CInt -> OCIHandle -> OCIHandle -> CInt -> IO CInt +foreign import ccall "oci.h OCIStmtFetch" ociStmtFetch :: StmtHandle -> ErrorHandle -> CInt -> CShort -> CInt -> IO CInt + +-- stmt, ptr bindHdl, err, pos, valuePtr, sizeOfValue, +-- datatype, indicatorPtr, lenArrayPtr, retCodeArrayPtr, +-- plsqlArrayMaxLen, plsqlCurrEltPtr, mode + +foreign import ccall "oci.h OCIBindByPos" ociBindByPos :: + StmtHandle + -> Ptr BindHandle + -> ErrorHandle + -> CUInt -- ^ position + -> BufferPtr -- ^ buffer containing data + -> CInt -- ^ max size of buffer + -> CUShort -- ^ SQL data type + -> Ptr CShort -- ^ null indicator ptr + -> Ptr CUShort -- ^ input + output size, or array of sizes + -> Ptr CUShort -- ^ array of return codes + -> CUInt -- ^ max array elements + -> Ptr CUInt -- ^ number of array elements + -> CUInt -- ^ mode + -> IO CInt + +foreign import ccall "oci.h OCIBindDynamic" ociBindDynamic :: + BindHandle -> ErrorHandle -> ContextPtr -> FunPtr OCICallbackInBind + -> ContextPtr -> FunPtr OCICallbackOutBind -> IO CInt + +type OCICallbackInBind = ContextPtr -> BindHandle -> CInt -> CInt + -> Ptr BufferPtr -> CInt -> Ptr Word8 -> Ptr CShort -> IO CInt + +type OCICallbackOutBind = ContextPtr -> BindHandle -> CInt -> CInt + -> Ptr BufferPtr -> Ptr CInt -> Ptr Word8 -> Ptr CShort -> Ptr (Ptr CShort) -> IO CInt + +foreign import ccall "wrapper" mkOCICallbackInBind :: + OCICallbackInBind -> IO (FunPtr OCICallbackInBind) +foreign import ccall "wrapper" mkOCICallbackOutBind :: + OCICallbackOutBind -> IO (FunPtr OCICallbackOutBind) + +-- --------------------------------------------------------------------------------- +-- -- ** OCI error reporting +-- --------------------------------------------------------------------------------- + +-- |This is just an auxiliary function for getOCIErrorMsg. + +getOCIErrorMsg2 :: OCIHandle -> CInt -> Ptr CInt -> CString -> CInt -> IO (CInt, String) +getOCIErrorMsg2 ocihandle handleType errCodePtr errMsgBuf maxErrMsgLen = do + rc <- ociErrorGet ocihandle 1 nullPtr errCodePtr errMsgBuf maxErrMsgLen handleType + if rc < 0 + then return (0, "Error message not available.") + else do + msg <- peekCString errMsgBuf + e <- peek errCodePtr + return (e, msg) + + +getOCIErrorMsg :: OCIHandle -> CInt -> IO (CInt, String) +getOCIErrorMsg ocihandle handleType = do + let stringBufferLen = 1000 + allocaBytes stringBufferLen $ \errMsg -> + alloca $ \errCode -> + getOCIErrorMsg2 ocihandle handleType errCode errMsg (mkCInt stringBufferLen) + +fromEnumOCIErrorCode :: CInt -> String +fromEnumOCIErrorCode err + | err == oci_SUCCESS = "OCI_SUCCESS" + | err == oci_SUCCESS_WITH_INFO = "OCI_SUCCESS_WITH_INFO" + | err == oci_NEED_DATA = "OCI_NEED_DATA" + | err == oci_NO_DATA = "OCI_NO_DATA" + | err == oci_INVALID_HANDLE = "OCI_INVALID_HANDLE" + | err == oci_STILL_EXECUTING = "OCI_STILL_EXECUTING" + | err == oci_CONTINUE = "OCI_CONTINUE" + | err == oci_RESERVED_FOR_INT_USE = "OCI_RESERVED_FOR_INT_USE" + | otherwise = "OCI_ERROR" + +formatErrorCodeDesc :: CInt -> String -> String +formatErrorCodeDesc err desc + | err == oci_ERROR = "" + | otherwise = (fromEnumOCIErrorCode err) ++ " - " ++ desc + + +-- |Given the two parts of an 'OCIException' (the error number and text) +-- get the actual error message from the DBMS and construct an error message +-- from all of these pieces. + +formatOCIMsg :: CInt -> String -> OCIHandle -> CInt -> IO (Int, String) +formatOCIMsg e m ocihandle handleType = do + (err, msg) <- getOCIErrorMsg ocihandle handleType + --return (fromIntegral err, (formatErrorCodeDesc e m) ++ " : " ++ (show err) ++ " - " ++ msg) + if msg == "" + then return (fromIntegral err, (formatErrorCodeDesc e m)) + else return (fromIntegral err, (formatErrorCodeDesc e m) ++ " : " ++ msg) + + + +-- |We have two format functions: 'formatEnvMsg' takes the 'EnvHandle', +-- 'formatErrorMsg' takes the 'ErrorHandle'. +-- They're just type-safe wrappers for 'formatMsgCommon'. + +formatMsgCommon :: OCIException -> OCIHandle -> CInt -> IO (Int, String) +formatMsgCommon (OCIException e m) h handleType = do + if e == 0 + then return (0, "") + else case () of + _ | e == oci_ERROR -> do (formatOCIMsg e m h handleType) + | e == oci_SUCCESS_WITH_INFO -> do (formatOCIMsg e m h handleType) + | otherwise -> return (fromIntegral e, formatErrorCodeDesc e m) + +formatErrorMsg :: OCIException -> ErrorHandle -> IO (Int, String) +formatErrorMsg exc err = formatMsgCommon exc (castPtr err) oci_HTYPE_ERROR + +formatEnvMsg :: OCIException -> EnvHandle -> IO (Int, String) +formatEnvMsg exc err = formatMsgCommon exc (castPtr err) oci_HTYPE_ENV + + + +-- |The testForError functions are the only places where OCIException is thrown, +-- so if you want to change or embellish it, your changes will be localised here. +-- These functions factor out common error handling code +-- from the OCI wrapper functions that follow. + +-- Typically an OCI wrapper function would look like: + +-- > handleAlloc handleType env = alloca ptr -> do +-- > rc <- ociHandleAlloc env ptr handleType 0 nullPtr +-- > if rc < 0 +-- > then throwOCI (OCIException rc msg) +-- > else return () + +-- where the code from @if rc < 0@ onwards was identical. +-- 'testForError' replaces the code from @if rc < 0 ...@ onwards. + +testForError :: CInt -> String -> a -> IO a +testForError rc msg retval = do + if rc < 0 + then throwOCI (OCIException rc msg) + else return retval + + +-- |Like 'testForError' but when the value you want to return +-- is at the end of a pointer. +-- Either there was an error, in which case the pointer probably isn't valid, +-- or there is something at the end of the pointer to return. +-- See 'dbLogon' and 'getHandleAttr' for example usage. + +testForErrorWithPtr :: Storable a => CInt -> String -> Ptr a -> IO a +testForErrorWithPtr rc msg retval = do + if rc < 0 + then throwOCI (OCIException rc msg) + else peek retval + + +-- --------------------------------------------------------------------------------- +-- -- ** Allocating Handles (i.e. creating OCI data structures, and memory management) +-- --------------------------------------------------------------------------------- + + +envCreate :: IO EnvHandle +envCreate = alloca $ \ptr -> do + rc <- ociEnvCreate ptr oci_DEFAULT nullPtr nullFunPtr nullFunPtr nullFunPtr 0 nullPtr + testForErrorWithPtr rc "allocate initial end" ptr + +handleAlloc :: CInt -> OCIHandle -> IO OCIHandle +handleAlloc handleType env = alloca $ \ptr -> do + rc <- ociHandleAlloc env ptr handleType 0 nullPtr + testForErrorWithPtr rc "allocate handle" ptr + +handleFree :: CInt -> OCIHandle -> IO () +handleFree handleType ptr = do + rc <- ociHandleFree ptr handleType + testForError rc "free handle" () + + + +setHandleAttr :: ErrorHandle -> OCIHandle -> CInt -> Ptr a -> CInt -> IO () +setHandleAttr err ocihandle handleType handleAttr attrType = do + rc <- ociAttrSet ocihandle handleType (castPtr handleAttr) 0 attrType err + testForError rc "setHandleAttr" () + + +setHandleAttrString :: ErrorHandle -> OCIHandle -> CInt -> String -> CInt -> IO () +setHandleAttrString err ocihandle handleType s attrType = do + withCStringLen s $ \sC -> do + rc <- ociAttrSet ocihandle handleType (castPtr (cStr sC)) (cStrLen sC) attrType err + testForError rc "setHandleAttrString" () + + +-- ociAttrGet returns a pointer to something - maybe a handle or a chunk of memory. +-- Sometimes it's a pointer to a Handle, i.e. a Ptr to a Ptr to a Struct, +-- so we want to peek it to get the Handle. +-- Other times it's a pointer to (say) a few bytes which might contain a number or a string. +-- Deref'ing it returns that value immediately, rather than a Ptr to that value. + +getHandleAttr :: (Storable a) => ErrorHandle -> OCIHandle -> CInt -> CInt -> IO a +getHandleAttr err ocihandle handleType attrType = alloca $ \ptr -> do + -- 3rd arg has type Ptr OCIBuffer. + rc <- ociAttrGet ocihandle handleType (castPtr ptr) nullPtr attrType err + testForErrorWithPtr rc "getAttrHandle" ptr + +getParam :: ErrorHandle -> StmtHandle -> Int -> IO ParamHandle +getParam err stmt posn = alloca $ \ptr -> do + rc <- ociParamGet (castPtr stmt) oci_HTYPE_STMT err ptr (mkCInt posn) + testForErrorWithPtr rc "getParam" (castPtr ptr) + + +-- --------------------------------------------------------------------------------- +-- -- ** Connecting and detaching +-- --------------------------------------------------------------------------------- + +-- |The OCI Logon function doesn't behave as you'd expect when the password is due to expire. +-- 'ociLogon' returns 'Database.Oracle.OCIConstants.oci_SUCCESS_WITH_INFO', +-- but the 'ConnHandle' returned is not valid. +-- In this case we have to change 'Database.Oracle.OCIConstants.oci_SUCCESS_WITH_INFO' +-- to 'Database.Oracle.OCIConstants.oci_ERROR', +-- so that the error handling code will catch it and abort. +-- I don't know why the handle returned isn't valid, +-- as the logon process should be able to complete successfully in this case. + + +dbLogon :: String -> String -> String -> EnvHandle -> ErrorHandle -> IO ConnHandle +dbLogon user pswd db env err = + withCStringLen user $ \userC -> + withCStringLen pswd $ \pswdC -> + withCStringLen db $ \dbC -> + alloca $ \conn -> do + rc <- ociLogon env err conn (cStr userC) (cStrLen userC) (cStr pswdC) (cStrLen pswdC) (cStr dbC) (cStrLen dbC) + case () of + _ | rc == oci_SUCCESS_WITH_INFO -> testForErrorWithPtr oci_ERROR "logon" conn + | otherwise -> testForErrorWithPtr rc "logon" conn + + +dbLogoff :: ErrorHandle -> ConnHandle -> IO () +dbLogoff err conn = do + rc <- ociLogoff conn err + testForError rc "logoff" () + + +terminate :: IO () +terminate = do + rc <- ociTerminate oci_DEFAULT + testForError rc "terminate" () + + + +serverDetach :: ErrorHandle -> ServerHandle -> IO () +serverDetach err server = do + rc <- ociServerDetach server err oci_DEFAULT + testForError rc "server detach" () + + +serverAttach :: ErrorHandle -> ServerHandle -> String -> IO () +serverAttach err server dblink = do + withCStringLen dblink $ \s -> do + rc <- ociServerAttach server err (cStr s) (cStrLen s) oci_DEFAULT + testForError rc "server attach" () + + +-- |Having established a connection (Service Context), now get the Session. +-- You can have more than one session per connection, +-- but I haven't implemented it yet. + +getSession :: ErrorHandle -> ConnHandle -> IO SessHandle +getSession err conn = liftM castPtr (getHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX oci_ATTR_SESSION) + + +sessionBegin :: ErrorHandle -> ConnHandle -> SessHandle -> CInt -> IO () +sessionBegin err conn sess cred = do + rc <- ociSessionBegin conn err sess cred oci_DEFAULT + testForError rc "session begin" () + + +sessionEnd :: ErrorHandle -> ConnHandle -> SessHandle -> IO () +sessionEnd err conn sess = do + rc <- ociSessionEnd conn err sess oci_DEFAULT + testForError rc "session end" () + + + +-- --------------------------------------------------------------------------------- +-- -- ** Transactions +-- --------------------------------------------------------------------------------- + +beginTrans :: ErrorHandle -> ConnHandle -> CInt -> IO () +beginTrans err conn isolation = do + rc <- ociTransStart conn err 0 isolation + testForError rc "begin transaction" () + +commitTrans :: ErrorHandle -> ConnHandle -> IO () +commitTrans err conn = do + rc <- ociTransCommit conn err oci_DEFAULT + testForError rc "commit" () + +rollbackTrans :: ErrorHandle -> ConnHandle -> IO () +rollbackTrans err conn = do + rc <- ociTransRollback conn err oci_DEFAULT + testForError rc "rollback" () + + +-- --------------------------------------------------------------------------------- +-- -- ** Issuing queries +-- --------------------------------------------------------------------------------- + +-- |With the OCI you do queries with these steps: + +-- * prepare your statement (it's just a String) - no communication with DBMS + +-- * execute it (this sends it to the DBMS for parsing etc) + +-- * allocate result set buffers by calling 'defineByPos' for each column + +-- * call fetch for each row. + +-- * call 'handleFree' for the 'StmtHandle' +-- (I assume this is the approved way of terminating the query; +-- the OCI docs aren't explicit about this.) + + +stmtPrepare :: ErrorHandle -> StmtHandle -> String -> IO () +stmtPrepare err stmt sqltext = do + withCStringLen sqltext $ \sqltextC -> do + rc <- ociStmtPrepare stmt err (cStr sqltextC) (cStrLen sqltextC) oci_NTV_SYNTAX oci_DEFAULT + testForError rc "stmtPrepare" () + + +stmtExecute :: ErrorHandle -> ConnHandle -> StmtHandle -> Int -> IO () +stmtExecute err conn stmt iterations = do + rc <- ociStmtExecute conn stmt err (mkCInt iterations) 0 nullPtr nullPtr oci_DEFAULT + testForError rc "stmtExecute" () + + + +-- |defineByPos allocates memory for a single column value. +-- The allocated components are: + +-- * the result (i.e. value) - you have to say how big with bufsize. + +-- * the null indicator (int16) + +-- * the size of the returned data (int16) + +-- Previously it was the caller's responsibility to free the memory after they're done with it. +-- Now we use 'Foreign.ForeignPtr.mallocForeignPtr', so manual memory management is hopefully +-- a thing of the past. +-- The caller will also have to cast the data in bufferptr to the expected type +-- (using 'Foreign.Ptr.castPtr'). + + +defineByPos :: ErrorHandle + -> StmtHandle + -> Int -- ^ Position + -> Int -- ^ Buffer size in bytes + -> CInt -- ^ SQL Datatype (from "Database.Oracle.OCIConstants") + -> IO ColumnInfo -- ^ tuple: (DefnHandle, Ptr to buffer, Ptr to null indicator, Ptr to size of value in buffer) +defineByPos err stmt posn bufsize sqldatatype = do + bufferFPtr <- mallocForeignPtrBytes bufsize + nullIndFPtr <- mallocForeignPtr + retSizeFPtr <- mallocForeignPtr + alloca $ \defnPtr -> + withForeignPtr bufferFPtr $ \bufferPtr -> + withForeignPtr nullIndFPtr $ \nullIndPtr -> + withForeignPtr retSizeFPtr $ \retSizePtr -> do + rc <- ociDefineByPos stmt defnPtr err (mkCInt posn) bufferPtr (mkCInt bufsize) (mkCUShort sqldatatype) nullIndPtr retSizePtr nullPtr oci_DEFAULT + defn <- peek defnPtr -- no need for caller to free defn; I think freeing the stmt handle does it. + testForError rc "defineByPos" (defn, bufferFPtr, nullIndFPtr, retSizeFPtr) + + +-- |Oracle only understands bind variable placeholders using syntax :x, +-- where x is a number or a variable name. +-- Most other DBMS's use ? as a placeholder, +-- so we have this function to substitute ? with :n, +-- where n starts at one and increases with each ?. + +-- We don't use this function in this library though; +-- it's used in the higher-level implementation of Enumerator. +-- We prefer to retain flexibility at this lower-level, +-- and not force arbitrary implementation choices too soon. +-- If you want to use this library and use :x style syntax, you can. + +substituteBindPlaceHolders sql = + sbph sql 1 False "" + +sbph :: String -> Int -> Bool -> String -> String +sbph [] _ _ acc = reverse acc +sbph ('\'':cs) i inQuote acc = sbph cs i (not inQuote) ('\'':acc) +sbph ('?':cs) i False acc = sbph cs (i+1) False ((reverse (show i)) ++ (':':acc)) +sbph (c:cs) i inQuote acc = sbph cs i inQuote (c:acc) + + + +bindByPos :: + ErrorHandle + -> StmtHandle + -> Int -- ^ Position + -> CShort -- ^ Null ind: 0 == not null, -1 == null + -> BufferPtr -- ^ payload + -> Int -- ^ payload size in bytes + -> CInt -- ^ SQL Datatype (from "Database.Oracle.OCIConstants") + -> IO () +bindByPos err stmt pos nullInd bufptr sze sqltype = do + indFPtr <- mallocForeignPtr + sizeFPtr <- mallocForeignPtr + withForeignPtr indFPtr $ \p -> poke p nullInd + -- You can't put any old junk in the return-size field, + -- even if the parameter is IN-only. + -- So tell it how big the input buffer is. + withForeignPtr sizeFPtr $ \p -> poke p (fromIntegral sze) + bufFPtr <- newForeignPtr_ bufptr + bindOutputByPos err stmt pos (indFPtr, bufFPtr, sizeFPtr) sze sqltype + return () + +-- Note that this function takes a ForeignPtr to the output-size +-- (in the triple) and also a size parameter, which is the input size. +-- We need to provide both, apparently, regardless of actual parameter +-- direction. + +bindOutputByPos :: + ErrorHandle + -> StmtHandle + -> Int -- ^ Position + -> BindBuffer -- ^ triple of (null-ind, payload, input-size) + -> Int -- ^ buffer max size in bytes + -> CInt -- ^ SQL Datatype (from "Database.Oracle.OCIConstants") + -> IO BindHandle +bindOutputByPos err stmt pos (nullIndFPtr, bufFPtr, sizeFPtr) sze sqltype = + alloca $ \bindHdl -> + withForeignPtr nullIndFPtr $ \indPtr -> do + withForeignPtr sizeFPtr $ \sizePtr -> + withForeignPtr bufFPtr $ \bufPtr -> do + rc <- ociBindByPos stmt bindHdl err (fromIntegral pos) bufPtr + (fromIntegral sze) (fromIntegral sqltype) + indPtr sizePtr nullPtr 0 nullPtr (fromIntegral oci_DEFAULT) + testForError rc "bindOutputByPos" () + bptr <- peek bindHdl + return bptr + + +-- | Fetch a single row into the buffers. +-- If you have specified a prefetch count > 1 then the row +-- might already be cached by the OCI library. + +stmtFetch :: ErrorHandle -> StmtHandle -> IO CInt +stmtFetch err stmt = do + let numRowsToFetch = 1 + rc <- ociStmtFetch stmt err numRowsToFetch (mkCShort oci_FETCH_NEXT) oci_DEFAULT + if rc == oci_NO_DATA + then return rc + else testForError rc "stmtFetch" rc + +-- From the "Bindind and Defining" chapter in the OCI docs: + +-- Binding RETURNING...INTO variables + +-- An OCI application implements the placeholders in the RETURNING clause +-- as pure OUT bind variables. However, all binds in the RETURNING clause +-- are initially IN and must be properly initialized. +-- To provide a valid value, you can provide a NULL indicator +-- and set that indicator to -1 (NULL). + +-- An application must adhere to the following rules when working with +-- bind variables in a RETURNING clause: + +-- 1. Bind RETURNING clause placeholders in OCI_DATA_AT_EXEC mode using +-- OCIBindByName() or OCIBindByPos(), followed by a call to +-- OCIBindDynamic() for each placeholder. + +-- Note: The OCI only supports the callback mechanism for +-- RETURNING clause binds. The polling mechanism is not supported. + +-- 2. When binding RETURNING clause placeholders, you must supply a valid out +-- bind function as the ocbfp parameter of the OCIBindDynamic() call. +-- This function must provide storage to hold the returned data. + +-- 3. The icbfp parameter of OCIBindDynamic() call should provide a +-- "dummy" function which returns NULL values when called. + +-- 4. The piecep parameter of OCIBindDynamic() must be set to OCI_ONE_PIECE. + +-- 5. No duplicate binds are allowed in a DML statement with a +-- RETURNING clause, such as no duplication between bind variables +-- in the DML section and the RETURNING section of the statement. + +-- |Short-circuit null test: if the buffer contains a null then return Nothing. +-- Otherwise, run the IO action to extract a value from the buffer and return Just it. + +maybeBufferNull :: ForeignPtr CShort -> Maybe a -> IO a -> IO (Maybe a) +maybeBufferNull nullIndFPtr nullVal action = + withForeignPtr nullIndFPtr $ \nullIndPtr -> do + nullInd <- liftM cShort2Int (peek nullIndPtr) + if (nullInd == -1) -- -1 == null, 0 == value + then return nullVal + else do + v <- action + return (Just v) + + +nullByte :: CChar +nullByte = 0 + +cShort2Int :: CShort -> Int +cShort2Int n = fromIntegral n + +cUShort2Int :: CUShort -> Int +cUShort2Int n = fromIntegral n + +cuCharToInt :: CUChar -> Int +cuCharToInt c = fromIntegral c + +byteToInt :: Ptr CUChar -> Int -> IO Int +byteToInt buffer n = do + b <- peekByteOff buffer n + return (cuCharToInt b) + + +bufferToString :: ColumnInfo -> IO (Maybe String) +bufferToString (_, bufFPtr, nullFPtr, sizeFPtr) = + withForeignPtr nullFPtr $ \nullIndPtr -> do + nullInd <- liftM cShort2Int (peek nullIndPtr) + if (nullInd == -1) -- -1 == null, 0 == value + then return Nothing + else do + -- Given a column buffer, extract a string of variable length + -- (you have to terminate it yourself). + withForeignPtr bufFPtr $ \bufferPtr -> + withForeignPtr sizeFPtr $ \retSizePtr -> do + retsize <- liftM cUShort2Int (peek retSizePtr) + --putStrLn ("bufferToString: size = " ++ show retsize) + pokeByteOff (castPtr bufferPtr) retsize nullByte + val <- peekCString (castPtr bufferPtr) + return (Just val) + + +-- | Oracle's excess-something-or-other encoding for years: +-- year = 100*(c - 100) + (y - 100), +-- c = (year div 100) + 100, +-- y = (year mod 100) + 100. + +-- +1999 -> 119, 199 +-- +0100 -> 101, 100 +-- +0001 -> 100, 101 +-- -0001 -> 100, 99 +-- -0100 -> 99, 100 +-- -1999 -> 81, 1 + +makeYear :: Int -> Int -> Int +makeYear c100 y100 = 100 * (c100 - 100) + (y100 - 100) + +makeYearByte :: Int -> Word8 +makeYearByte y = fromIntegral ((rem y 100) + 100) + +makeCentByte :: Int -> Word8 +makeCentByte y = fromIntegral ((quot y 100) + 100) + +dumpBuffer :: Ptr Word8 -> IO () +dumpBuffer buf = do + dumpByte 0 + dumpByte 1 + dumpByte 2 + dumpByte 3 + dumpByte 4 + dumpByte 5 + dumpByte 6 + putStrLn "" + where + dumpByte n = do + b <- (peekByteOff buf n :: IO Word8) + putStr $ (show b) ++ " " + + +bufferToCaltime :: ForeignPtr CShort -> BufferFPtr -> IO (Maybe CalendarTime) +bufferToCaltime nullind fptr = maybeBufferNull nullind Nothing $ + withForeignPtr fptr $ \bufferPtr -> do + let buffer = castPtr bufferPtr + --dumpBuffer (castPtr buffer) + century100 <- byteToInt buffer 0 + year100 <- byteToInt buffer 1 + month <- byteToInt buffer 2 + day <- byteToInt buffer 3 + hour <- byteToInt buffer 4 + minute <- byteToInt buffer 5 + second <- byteToInt buffer 6 + return $ CalendarTime + { ctYear = makeYear century100 year100 + , ctMonth = toEnum (month - 1) + , ctDay = day + , ctHour = hour - 1 + , ctMin = minute - 1 + , ctSec = second - 1 + , ctPicosec = 0 + , ctWDay = Sunday + , ctYDay = -1 + , ctTZName = "UTC" + , ctTZ = 0 + , ctIsDST = False + } + +bufferToUTCTime :: ForeignPtr CShort -> BufferFPtr -> IO (Maybe UTCTime) +bufferToUTCTime nullind fptr = maybeBufferNull nullind Nothing $ + withForeignPtr fptr $ \bufferPtr -> do + let buffer = castPtr bufferPtr + --dumpBuffer (castPtr buffer) + century100 <- byteToInt buffer 0 + year100 <- byteToInt buffer 1 + month <- byteToInt buffer 2 + day <- byteToInt buffer 3 + hour <- byteToInt buffer 4 + minute <- byteToInt buffer 5 + second <- byteToInt buffer 6 + let year = makeYear century100 year100 + return (mkUTCTime year month day (hour-1) (minute-1) (second-1)) + +setBufferByte :: BufferPtr -> Int -> Word8 -> IO () +setBufferByte buf n v = pokeByteOff buf n v + +calTimeToBuffer :: BufferPtr -> CalendarTime -> IO () +calTimeToBuffer buf ct = do + setBufferByte buf 0 (makeCentByte (ctYear ct)) + setBufferByte buf 1 (makeYearByte (ctYear ct)) + setBufferByte buf 2 (fromIntegral ((fromEnum (ctMonth ct)) + 1)) + setBufferByte buf 3 (fromIntegral (ctDay ct)) + setBufferByte buf 4 (fromIntegral (ctHour ct + 1)) + setBufferByte buf 5 (fromIntegral (ctMin ct + 1)) + setBufferByte buf 6 (fromIntegral (ctSec ct + 1)) + +utcTimeToBuffer :: BufferPtr -> UTCTime -> IO () +utcTimeToBuffer buf utc = do + let (LocalTime ltday time) = utcToLocalTime (hoursToTimeZone 0) utc + let (TimeOfDay hour minute second) = time + let (year, month, day) = toGregorian ltday + setBufferByte buf 0 (makeCentByte (fromIntegral year)) + setBufferByte buf 1 (makeYearByte (fromIntegral year)) + setBufferByte buf 2 (fromIntegral month) + setBufferByte buf 3 (fromIntegral day) + setBufferByte buf 4 (fromIntegral (hour+1)) + setBufferByte buf 5 (fromIntegral (minute+1)) + setBufferByte buf 6 (round (second+1)) + + +bufferPeekValue :: (Storable a) => BufferFPtr -> IO a +bufferPeekValue buffer = do + v <- withForeignPtr buffer $ \bufferPtr -> peek $ castPtr bufferPtr + return v + +bufferToA :: (Storable a) => ForeignPtr CShort -> BufferFPtr -> IO (Maybe a) +bufferToA nullind buffer = maybeBufferNull nullind Nothing (bufferPeekValue buffer) + +bufferToCInt :: ForeignPtr CShort -> BufferFPtr -> IO (Maybe CInt) +bufferToCInt = bufferToA + +bufferToInt :: ForeignPtr CShort -> BufferFPtr -> IO (Maybe Int) +bufferToInt nullind b = do + cint <- bufferToCInt nullind b + return $ maybe Nothing (Just . fromIntegral) cint + +bufferToCDouble :: ForeignPtr CShort -> BufferFPtr -> IO (Maybe CDouble) +bufferToCDouble = bufferToA + +bufferToDouble :: ForeignPtr CShort -> BufferFPtr -> IO (Maybe Double) +bufferToDouble nullind b = do + cdbl <- bufferToCDouble nullind b + return $ maybe Nothing (Just . realToFrac) cdbl + +bufferToStmtHandle :: BufferFPtr -> IO StmtHandle +bufferToStmtHandle buffer = do + withForeignPtr buffer $ \bufferPtr -> do + v <- peek (castPtr bufferPtr) + return v
+ Database/Oracle/Test/Enumerator.hs view
@@ -0,0 +1,378 @@+ +-- | +-- Module : Database.Oracle.Test.Enumerator +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + + +-- The Oracle multi-result-set tests require these database objects: + +-- CREATE OR REPLACE VIEW t_whole as +-- select 0 as n from dual union select 1 from dual +-- union select 2 from dual union select 3 from dual +-- union select 4 from dual union select 5 from dual +-- union select 6 from dual union select 7 from dual +-- union select 8 from dual union select 9 from dual +-- ; + +-- CREATE OR REPLACE VIEW t_natural as +-- select n from +-- ( select t1.n + 10 * t10.n + 100 * t100.n as n +-- from t_whole t1, t_whole t10, t_whole t100 +-- ) t where n > 0 order by 1 +-- ; + +-- create or replace package Takusen as type RefCursor is ref cursor; end; + +-- CREATE OR REPLACE PROCEDURE takusenTestProc +-- (refc1 out Takusen.RefCursor, refc2 out Takusen.RefCursor) AS BEGIN +-- OPEN refc1 FOR SELECT n*n from t_natural where n < 10 order by 1; +-- OPEN refc2 FOR SELECT n, n*n, n*n*n from t_natural where n < 10 order by 1; +-- END; + +-- select n, cursor( +-- SELECT nat2.n +-- , cursor(SELECT nat3.n from t_natural nat3 where nat3.n < nat2.n order by n) +-- from t_natural nat2 where nat2.n < nat.n order by n +-- ) +-- from t_natural nat where n < 10 order by n; + + +{-# LANGUAGE OverlappingInstances #-} + +module Database.Oracle.Test.Enumerator (runTest) where + +import qualified Database.Oracle.Test.OCIFunctions as Low +import Database.Oracle.Enumerator +import Database.Util (print_) +import Database.Test.Performance as Perf +import Database.Test.Enumerator +import Control.Monad (when) +import Control.Monad.Trans (liftIO) +import Test.MiniUnit +import Data.Int +import System.Time + + +runTest :: Perf.ShouldRunTests -> [String] -> IO () +runTest runPerf args = do + let (user:pswd:dbname:_) = args + Low.runTest args + flip catchDB basicDBExceptionReporter $ + withSession (connect user pswd dbname) (testBody runPerf) + +testBody runPerf = do + runFixture OracleFunctions + when (runPerf == Perf.RunTests) runPerformanceTests + +runPerformanceTests = do + makeFixture execDrop execDDL_ + beginTransaction RepeatableRead + runTestTT "Oracle performance tests" (map (flip catchDB reportRethrow) + [ timedSelect (prefetch 1000 sqlRows2Power20 []) 30 (2^20) + , timedSelect (prefetch 1 sqlRows2Power17 []) 60 (2^17) + , timedSelect (prefetch 1000 sqlRows2Power17 []) 6 (2^17) + , timedCursor (prefetch 1 sqlRows2Power17 []) 60 (2^17) + , timedCursor (prefetch 1000 sqlRows2Power17 []) 6 (2^17) + ] + ) + commit + destroyFixture execDDL_ + + +runFixture :: OracleFunctions -> DBM mark Session () +runFixture fns = do + makeFixture execDrop execDDL_ + execDDL_ makeFixtureMultiResultSet1 + execDDL_ makeFixtureMultiResultSet2 + execDDL_ makeFixtureMultiResultSet3 + execDDL_ makeFixtureMultiResultSet4 + execDDL_ makeFixtureBindOutput + runTestTT "Oracle tests" (map (runOneTest fns) testList) + execDDL_ dropFixtureBindOutput + execDDL_ dropFixtureMultiResultSet4 + execDDL_ dropFixtureMultiResultSet3 + execDDL_ dropFixtureMultiResultSet2 + execDDL_ dropFixtureMultiResultSet1 + destroyFixture execDDL_ + +runOneTest fns t = catchDB (t fns) reportRethrow + +-- ----------------------------------------------------------- + +selectNoRows _ = selectTest sqlNoRows iterNoRows expectNoRows + +selectTerminatesEarly _ = selectTest sqlTermEarly iterTermEarly expectTermEarly + +selectFloatsAndInts fns = selectTest (sqlFloatsAndInts fns) iterFloatsAndInts expectFloatsAndInts + +selectNullString _ = selectTest sqlNullString iterNullString expectNullString + +selectEmptyString _ = selectTest sqlEmptyString iterEmptyString expectEmptyString + +selectUnhandledNull _ = catchDB ( do + selectTest sqlUnhandledNull iterUnhandledNull expectUnhandledNull + assertFailure sqlUnhandledNull + ) (\e -> return () ) + + + +selectNullDate dateFn = selectTest (sqlNullDate dateFn) iterNullDate expectNullDate + +selectDate dateFn = selectTest (sqlDate dateFn) iterDate expectDate + +selectCalDate dateFn = selectTest (sqlDate dateFn) iterCalDate expectCalDate + +selectBoundaryDates dateFn = selectTest (sqlBoundaryDates dateFn) iterBoundaryDates expectBoundaryDates + +selectCursor fns = actionCursor (sqlCursor fns) + +selectExhaustCursor fns = actionExhaustCursor (sqlCursor fns) + +selectBindString _ = actionBindString + (prepareQuery (sql sqlBindString)) + [bindP "a2", bindP "b1"] + + +selectBindInt _ = actionBindInt + (prepareQuery (sql sqlBindInt)) + [bindP (1::Int), bindP (2::Int)] + + +selectBindIntDoubleString _ = actionBindIntDoubleString + (prefetch 0 sqlBindIntDoubleString [bindP (1::Int), bindP (2.2::Double), bindP "row 1", bindP (3::Int), bindP (4.4::Double), bindP "row 2"]) + +selectBindDate _ = actionBindDate + (prefetch 1 sqlBindDate (map bindP expectBindDate)) + +selectBindBoundaryDates _ = actionBindBoundaryDates + (prefetch 1 sqlBindBoundaryDates (map bindP expectBoundaryDates)) + +selectRebindStmt _ = actionRebind (prepareQuery (sql sqlRebind)) + [bindP (1::Int)] [bindP (2::Int)] + +boundStmtDML _ = actionBoundStmtDML (prepareCommand (sql sqlBoundStmtDML)) +boundStmtDML2 _ = withTransaction RepeatableRead $ do + count <- execDML (cmdbind sqlBoundStmtDML [bindP (100::Int), bindP "100"]) + assertEqual sqlBoundStmtDML 1 count + rollback + + +polymorphicFetchTest _ = actionPolymorphicFetch + (prefetch 0 sqlPolymorphicFetch [bindP expectPolymorphicFetch]) + +polymorphicFetchTestNull _ = actionPolymorphicFetchNull + (prefetch 1 sqlPolymorphicFetchNull []) + +exceptionRollback _ = actionExceptionRollback sqlInsertTest4 sqlExceptionRollback + + +-- FIXME check definitions of whole and natural numbers + +dropFixtureMultiResultSet1 = "DROP VIEW t_whole" +makeFixtureMultiResultSet1 = "CREATE OR REPLACE VIEW t_whole as" + ++ " select 0 as n from dual union select 1 from dual" + ++ " union select 2 from dual union select 3 from dual" + ++ " union select 4 from dual union select 5 from dual" + ++ " union select 6 from dual union select 7 from dual" + ++ " union select 8 from dual union select 9 from dual" + +dropFixtureMultiResultSet2 = "DROP VIEW t_natural" +makeFixtureMultiResultSet2 = "CREATE OR REPLACE VIEW t_natural as" + ++ " select n from" + ++ " ( select t1.n + 10 * t10.n + 100 * t100.n as n" + ++ " from t_whole t1, t_whole t10, t_whole t100" + ++ " ) t where n > 0 order by 1" + + +dropFixtureMultiResultSet3 = "DROP package Takusen" +makeFixtureMultiResultSet3 = + "create or replace package Takusen as type RefCursor is ref cursor; end;" + +dropFixtureMultiResultSet4 = "DROP PROCEDURE takusenTestProc" +makeFixtureMultiResultSet4 = "CREATE OR REPLACE PROCEDURE takusenTestProc" + ++ " (refc1 out Takusen.RefCursor, refc2 out Takusen.RefCursor) AS BEGIN" + ++ " OPEN refc1 FOR SELECT n*n from t_natural where n < 10 order by 1;" + ++ " OPEN refc2 FOR SELECT n, n*n, n*n*n from t_natural where n < 10 order by 1;" + ++ " END;" + +-- What would you need to do to make database functions and procedures +-- callable from Haskell as if they were local functions (IO actions)? + +-- wrapPLSQLFunc funcname parms = +-- let +-- sqltext = "begin " ++ (head args) ++ " := " ++ funcname ++ "(" ++ placeholders ++ "); end;" +-- placeholders = concat (intersperse "," (tail args)) +-- args = take (length parms) (map (\n -> ":x" ++ show n) [1..]) +-- in cmdbind sqltext parms + +-- wrapPLSQLProc procname parms = +-- let +-- sqltext = "begin " ++ procname ++ "(" ++ placeholders ++ "); end;" +-- placeholders = concat (intersperse "," args) +-- args = take (length parms) (map (\n -> ":x" ++ show n) [1..]) +-- in cmdbind sqltext parms + +-- convertCcy :: String -> Double -> String -> UTCTime -> DBM mark Session (String, Double) +-- convertCcy ccyFrom valFrom ccyTo onDate = do +-- sqlcmd = wrapPLSQLFunc "pk_fx.convert_ccy" +-- [ bindP (Out (0 :: Double)) +-- , bindP ccyFrom +-- , bindP valFrom +-- , bindP ccyTo +-- , bindP onDate +-- ] +-- let +-- iter :: Monad m => Double -> IterAct m Double +-- iter val seed = return (Left val) +-- result = doQuery sqlcmd iter undefined +-- return result + +selectMultiResultSet _ = do + let refcursor :: Maybe StmtHandle; refcursor = Just undefined + withTransaction RepeatableRead $ do + withPreparedStatement (prepareCommand (sql "begin takusenTestProc(:1,:2); end;")) $ \pstmt -> do + withBoundStatement pstmt [bindP (Out refcursor), bindP (Out refcursor)] $ \bstmt -> do + dummy <- doQuery bstmt iterMain () + result1 <- doQuery (NextResultSet pstmt) iterRS1 [] + assertEqual "selectMultiResultSet: RS1" [1,4,9,16,25,36,49,64,81] result1 + result2 <- doQuery (NextResultSet pstmt) iterRS2 [] + let expect = [(1,1,1),(2,4,8),(3,9,27),(4,16,64),(5,25,125),(6,36,216) + ,(7,49,343),(8,64,512),(9,81,729)] + assertEqual "selectMultiResultSet: RS2" expect result2 + return () + where + iterMain :: (Monad m) => RefCursor StmtHandle -> RefCursor StmtHandle -> IterAct m () + iterMain c1 c2 acc = return (Left acc) + iterRS1 :: (Monad m) => Int -> IterAct m [Int] + iterRS1 i acc = result (acc ++ [i]) + iterRS2 :: (Monad m) => Int -> Int -> Int -> IterAct m [(Int, Int, Int)] + iterRS2 i i2 i3 acc = result (acc ++ [(i, i2, i3)]) + + +selectNestedMultiResultSet :: OracleFunctions -> DBM mark Session () +selectNestedMultiResultSet _ = do + let + -- This returns two rows, each of which contains one cursor. + -- The first cursor returns 101, the second 102. + q = "select cursor(select n from dual) from" + ++ " (select 101 as n from dual union select 102 from dual)" + iterMain (c::RefCursor StmtHandle) acc = do + rs <- doQuery c iterInner [] + result' (c:acc) + iterInner (i::Int) acc = do + if (i /= 101 && i /= 102) + then assertFailure "selectNestedMultiResultSet: inner value not 101 or 102" + else return () + result' (i:acc) + withTransaction RepeatableRead $ do + withPreparedStatement (prepareQuery (sql q)) $ \pstmt -> do + withBoundStatement pstmt [] $ \bstmt -> do + rs <- doQuery bstmt iterMain [] + return () + + +selectNestedMultiResultSet2 :: OracleFunctions -> DBM mark Session () +selectNestedMultiResultSet2 _ = do + let + q = "select n, cursor(SELECT nat2.n, cursor" + ++ " (SELECT nat3.n from t_natural nat3 where nat3.n < nat2.n order by n)" + ++ " from t_natural nat2 where nat2.n < nat.n order by n)" + ++ " from t_natural nat where n < 10 order by n" + iterMain (outer::Int) (c::RefCursor StmtHandle) acc = do + rs <- doQuery c (iterInner outer) [] + let expect = drop (9-outer) [8,7,6,5,4,3,2,1] + assertEqual "processOuter" expect (map fst rs) + result' ((outer,c):acc) + iterInner outer (inner::Int) (c::RefCursor StmtHandle) acc = do + rs <- doQuery c (iterInner2 outer inner) [] + let expect = drop (9-inner) [8,7,6,5,4,3,2,1] + assertEqual "processInner" expect rs + result' ((inner,c):acc) + iterInner2 outer inner (i::Int) acc = do + --print_ (show outer ++ " " ++ show inner ++ " " ++ show i) + assertBool "processInner2" (i < inner) + result' (i:acc) + withTransaction RepeatableRead $ do + withPreparedStatement (prepareQuery (sql q)) $ \pstmt -> do + withBoundStatement pstmt [] $ \bstmt -> do + rs <- doQuery bstmt iterMain [] + assertEqual "selectNestedMultiResultSet" [9,8,7,6,5,4,3,2,1] (map fst rs) + --print_ "" + +selectNestedMultiResultSet3 :: OracleFunctions -> DBM mark Session () +selectNestedMultiResultSet3 _ = do + let + q = "select n, cursor(SELECT nat2.n, cursor" + ++ " (SELECT nat3.n from t_natural nat3 where nat3.n < nat2.n order by n)" + ++ " from t_natural nat2 where nat2.n < nat.n order by n)" + ++ " from t_natural nat where n < 10 order by n" + iterMain (outer::Int) (c::RefCursor StmtHandle) acc = do + rs <- doQuery c (iterInner outer) [] + let expect = drop (9-outer) [8,7,6,5,4,3,2,1] + assertEqual "processOuter" expect (map fst rs) + result' ((outer,c):acc) + iterInner outer (inner::Int) (c::RefCursor StmtHandle) acc = do + rs <- doQuery c (iterInner2 outer inner) [] + let expect = drop (9-inner) [8,7,6,5,4,3,2,1] + assertEqual "processInner" expect rs + result' ((inner,c):acc) + iterInner2 outer inner (i::Int) acc = do + --print_ (show outer ++ " " ++ show inner ++ " " ++ show i) + assertBool "processInner2" (i < inner) + result' (i:acc) + withTransaction RepeatableRead $ do + rs <- doQuery (sql q) iterMain [] + assertEqual "selectNestedMultiResultSet" [9,8,7,6,5,4,3,2,1] (map fst rs) + --print_ "" + +dropFixtureBindOutput = "DROP PROCEDURE takusenTestBindProc" + +makeFixtureBindOutput = "CREATE or replace PROCEDURE takusenTestBindProc(x in out number, y in out varchar2)" + ++ " AS BEGIN\n" + ++ " y := 'output ' || y;\n" + ++ " x := x * 2;\n" + ++ " END;" + +bindOutputString _ = do + let sqltext = "begin takusenTestBindProc(:1,:2); end;" + let qry = cmdbind sqltext [bindP (Out (1234::Int)), bindP (Out (Just "message"))] + (x, s) <- doQuery qry iter undefined + assertEqual "bindOutputString: int " 2468 x + assertEqual "bindOutputString: string " "output message" s + where + iter :: (Monad m) => Int -> String -> IterAct m (Int, String) + iter i s _ = return (Left (i, s)) + + +bindOutput _ = do + let sqltext = + "begin :1 := :1 + 1;\n " + ++ ":2 := :2 * 2;\n" + ++ "end;" + let qry = cmdbind sqltext [bindP (Out (44.4 :: Double)), bindP (Out (1234::Int))] + (d, i) <- doQuery qry iter undefined + assertEqual "bindOutput: double " 45.4 d + assertEqual "bindOutput: int " 2468 i + where + iter :: (Monad m) => Double -> Int -> IterAct m (Double, Int) + iter d i _ = return (Left (d, i)) + + +testList :: [OracleFunctions -> DBM mark Session ()] +testList = + [ selectNoRows, selectTerminatesEarly, selectFloatsAndInts + , selectNullString, selectEmptyString, selectUnhandledNull + , selectNullDate, selectDate, selectCalDate, selectBoundaryDates + , selectCursor, selectExhaustCursor + , selectBindString, selectBindInt, selectBindIntDoubleString + , selectBindDate, selectBindBoundaryDates, selectRebindStmt + , boundStmtDML, boundStmtDML2 + , polymorphicFetchTest, polymorphicFetchTestNull, exceptionRollback + , selectMultiResultSet, selectNestedMultiResultSet + , selectNestedMultiResultSet2, selectNestedMultiResultSet3 + , bindOutput, bindOutputString + ]
+ Database/Oracle/Test/OCIFunctions.hs view
@@ -0,0 +1,448 @@+ +-- | +-- Module : Database.Oracle.Test.OCIFunctions +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable + +-- Test harness for "Database.Oracle.OCIFunctions". +-- This module depends on on "Database.Oracle.OCIFunctions". +-- so it should only use functions from there (and "Database.Oracle.OCIConstants"). + + +module Database.Oracle.Test.OCIFunctions (runTest) where + +import qualified Database.Oracle.OCIFunctions as OCI +import Database.Oracle.OCIFunctions (EnvHandle, ErrorHandle, ConnHandle, StmtHandle) +import Database.Oracle.OCIConstants +import Foreign.Ptr +import Foreign.C.String +import Foreign.C.Types +import Foreign +import System.IO +import System.Environment (getArgs) +import Control.Monad +import Test.MiniUnit +import Data.Char + + +nullAction :: IO () +nullAction = return () + +printError :: String -> IO () +printError s = hPutStrLn stderr s + +reportAndIgnore :: ErrorHandle -> OCI.OCIException -> IO () -> IO () +reportAndIgnore err ociexc cleanupAction = do + (e, m) <- OCI.formatErrorMsg ociexc err + printError $ (show e) ++ ": " ++ m + cleanupAction + +reportAndRethrow :: ErrorHandle -> OCI.OCIException -> IO () -> IO () +reportAndRethrow err ociexc cleanupAction = do + (_, m) <- OCI.formatErrorMsg ociexc err + printError m + cleanupAction + OCI.throwOCI ociexc + + +logon :: (String, String, String) -> IO (EnvHandle, ErrorHandle, ConnHandle) +logon (testUser, testPswd, testDb) = do + env <- OCI.envCreate + err <- OCI.handleAlloc oci_HTYPE_ERROR (castPtr env) + OCI.catchOCI ( do + server <- OCI.handleAlloc oci_HTYPE_SERVER (castPtr env) + OCI.serverAttach (castPtr err) (castPtr server) testDb + conn <- OCI.handleAlloc oci_HTYPE_SVCCTX (castPtr env) + -- the connection holds a reference to the server in one of its attributes + OCI.setHandleAttr (castPtr err) (castPtr conn) oci_HTYPE_SVCCTX (castPtr server) oci_ATTR_SERVER + session <- OCI.handleAlloc oci_HTYPE_SESSION (castPtr env) + if (testUser == "") + then do + OCI.sessionBegin (castPtr err) (castPtr conn) (castPtr session) oci_CRED_EXT + else do + OCI.setHandleAttrString (castPtr err) (castPtr session) oci_HTYPE_SESSION testUser oci_ATTR_USERNAME + OCI.setHandleAttrString (castPtr err) (castPtr session) oci_HTYPE_SESSION testPswd oci_ATTR_PASSWORD + OCI.sessionBegin (castPtr err) (castPtr conn) (castPtr session) oci_CRED_RDBMS + -- the connection also holds a reference to the session in one of its attributes + OCI.setHandleAttr (castPtr err) (castPtr conn) oci_HTYPE_SVCCTX (castPtr session) oci_ATTR_SESSION + -- and we need to create a valid transaction handle for the connection, too. + trans <- OCI.handleAlloc oci_HTYPE_TRANS (castPtr env) + OCI.setHandleAttr (castPtr err) (castPtr conn) oci_HTYPE_SVCCTX (castPtr trans) oci_ATTR_TRANS + return (env, castPtr err, castPtr conn) + ) (\ociexc -> do + reportAndIgnore (castPtr err) ociexc nullAction + return (nullPtr, nullPtr, nullPtr) + ) + +logoff :: (EnvHandle, ErrorHandle, ConnHandle) -> IO () +logoff (env, err, conn) = OCI.catchOCI ( do + session <- OCI.getHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX oci_ATTR_SESSION + server <- OCI.getHandleAttr err (castPtr conn) oci_HTYPE_SVCCTX oci_ATTR_SERVER + OCI.sessionEnd err conn session + OCI.serverDetach err server + OCI.handleFree oci_HTYPE_SESSION (castPtr session) + OCI.handleFree oci_HTYPE_SERVER (castPtr server) + OCI.handleFree oci_HTYPE_SVCCTX (castPtr conn) + OCI.handleFree oci_HTYPE_ERROR (castPtr err) + OCI.handleFree oci_HTYPE_ENV (castPtr env) + OCI.terminate + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + + +testCreateEnv :: IO () +testCreateEnv = do + env <- OCI.envCreate + OCI.handleFree oci_HTYPE_ENV (castPtr env) + + +testConnect :: (String, String, String) -> IO () +testConnect args = do + x <- logon args + logoff x + + +getStmt :: EnvHandle -> ErrorHandle -> ConnHandle -> String -> IO StmtHandle +getStmt env err conn sql = do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + OCI.stmtPrepare err (castPtr stmt) sql + OCI.stmtExecute err conn (castPtr stmt) 0 + return (castPtr stmt) + + +testBeginTrans :: (String, String, String) -> IO () +testBeginTrans args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + OCI.beginTrans err conn oci_TRANS_SERIALIZABLE + stmt <- getStmt env err conn "select dummy from dual" + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + + +testExecute :: (String, String, String) -> IO () +testExecute args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- getStmt env err conn "select dummy from dual" + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + + +testFetch :: (String, String, String) -> IO () +testFetch args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- getStmt env err conn "select dummy from dual" + (_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt) 1 100 oci_SQLT_CHR + rc <- OCI.stmtFetch err (castPtr stmt) + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + +testFetchStmt :: (String, String, String) -> IO () +testFetchStmt args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- getStmt env err conn "select cursor(select 101 from dual) from dual" + (_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt) 1 8 oci_SQLT_RSET + stmt2 <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + withForeignPtr buf $ \p -> poke (castPtr p) stmt2 + rc <- OCI.stmtFetch err (castPtr stmt) + -- stmt2 <- OCI.bufferToStmtHandle buf + (_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt2) 1 4 oci_SQLT_INT + rc <- OCI.stmtFetch err (castPtr stmt2) + mb_i <- OCI.bufferToInt nullptr buf + assertEqual "testFetchStmt" (Just 101) mb_i + OCI.handleFree oci_HTYPE_STMT (castPtr stmt2) + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + + +testNestedFetchStmt :: (String, String, String) -> IO () +testNestedFetchStmt args = do + let + -- This returns two rows, each of which contains one cursor. + -- The first cursor returns 101, the second 102. + sql = "select cursor(select n from dual) from" + ++ " (select 101 as n from dual union select 102 from dual)" + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- getStmt env err conn sql + -- Create result buffer bfor row 1 StmtHandle + (_, obuf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt) 1 8 oci_SQLT_RSET + stmt101 <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + withForeignPtr obuf $ \p -> poke (castPtr p) stmt101 + -- + -- Fetch row 1 of 2 + rc <- OCI.stmtFetch err (castPtr stmt) + -- + -- Fetch stmt101 value + (_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt101) 1 4 oci_SQLT_INT + rc <- OCI.stmtFetch err (castPtr stmt101) + mb_101 <- OCI.bufferToInt nullptr buf + assertEqual "testFetchStmt" (Just 101) mb_101 + --OCI.handleFree oci_HTYPE_STMT (castPtr stmt101) + -- + -- Create result buffer for row 2 StmtHandle... + -- or re-use the StmtHandle stmt101. + -- Both ways work. + --(_, obuf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt) 1 8 oci_SQLT_RSET + --stmt102 <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + --withForeignPtr obuf $ \p -> poke (castPtr p) stmt102 + let stmt102 = stmt101 + -- + -- Fetch row 2 of 2 + rc <- OCI.stmtFetch err (castPtr stmt) + -- What happens if we free here? + -- Will the child cursor still be valid? + -- No - we get ORA-01001: invalid cursor + -- So it looks like closing the parent closes the children too. + --OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + -- + -- Fetch stmt102 value + (_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt102) 1 4 oci_SQLT_INT + rc <- OCI.stmtFetch err (castPtr stmt102) + mb_102 <- OCI.bufferToInt nullptr buf + assertEqual "testFetchStmt" (Just 102) mb_102 + OCI.handleFree oci_HTYPE_STMT (castPtr stmt102) + -- + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + + + +testFetchFail :: (String, String, String) -> IO () +testFetchFail args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- getStmt env err conn "select dummy, 1 from dual" + (_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt) 1 100 oci_SQLT_CHR + rc <- OCI.stmtFetch err (castPtr stmt) + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + + +testBind :: (String, String, String) -> IO () +testBind args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + -- Oracle can't cope with ? as a bind variable placeholder. + -- We must use the :x style instead. + -- Sqlite can cope with either. I think the ANSI/ISO standard is :n. + OCI.stmtPrepare err (castPtr stmt) + (OCI.substituteBindPlaceHolders "select :1 from dual union select :2 from dual") + withCStringLen "hello" $ \(cstr, clen) -> + OCI.bindByPos err (castPtr stmt) 1 0 (castPtr cstr) clen oci_SQLT_CHR + withCStringLen "hello2" $ \(cstr, clen) -> + OCI.bindByPos err (castPtr stmt) 2 0 (castPtr cstr) clen oci_SQLT_CHR + OCI.stmtExecute err conn (castPtr stmt) 0 + buffer@(_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt) 1 100 oci_SQLT_CHR + rc <- OCI.stmtFetch err (castPtr stmt) + s <- OCI.bufferToString buffer + rc <- OCI.stmtFetch err (castPtr stmt) + s <- OCI.bufferToString buffer + rc <- OCI.stmtFetch err (castPtr stmt) + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + +testOutputBind :: (String, String, String) -> IO () +testOutputBind args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + -- Oracle can't cope with ? as a bind variable placeholder. + -- We must use the :x style instead. + -- Sqlite can cope with either. I think the ANSI/ISO standard is :n. + OCI.stmtPrepare err (castPtr stmt) (OCI.substituteBindPlaceHolders + ("begin if :1 <> 'hello' then " + ++ "raise_application_error(-20001, 'xx-' || :1 || '-xx'); end if; " + ++ ":1 := 'abcdefg' || substr(:1, 1, 1) || 'ijk'; :2 := 1026; end;")) + nullIndFPtr1 <- mallocForeignPtr + nullIndFPtr2 <- mallocForeignPtr + sizeFPtr1 <- mallocForeignPtr + sizeFPtr2 <- mallocForeignPtr + cintFPtr <- mallocForeignPtrBytes (sizeOf (0::CInt)) + cstrFPtr <- mallocForeignPtrBytes 16000 -- size of "hello" + withForeignPtr cstrFPtr $ \p -> + withCStringLen "hello" $ \(cstr, clen) -> copyBytes p (castPtr cstr) (clen+1) + withForeignPtr sizeFPtr1 $ \p -> poke p 5 + withForeignPtr sizeFPtr2 $ \p -> poke p (fromIntegral (sizeOf (0::CInt))) + OCI.bindOutputByPos err (castPtr stmt) 1 (nullIndFPtr1, castForeignPtr cstrFPtr, sizeFPtr1) 16000 oci_SQLT_CHR + OCI.bindOutputByPos err (castPtr stmt) 2 (nullIndFPtr2, castForeignPtr cintFPtr, sizeFPtr2) (sizeOf (0::CInt)) oci_SQLT_INT + OCI.stmtExecute err conn (castPtr stmt) 1 + s <- withForeignPtr cstrFPtr (peekCString . castPtr) + assertEqual "testOutputBind: 1" "abcdefghijk" s + ind <- withForeignPtr nullIndFPtr1 peek + assertEqual "testOutputBind: 2" 0 ind + i <- withForeignPtr cintFPtr peek + assertEqual "testOutputBind: 3" 1026 (i :: CInt) + size <- withForeignPtr sizeFPtr1 peek >>= return . fromIntegral + assertEqual "testOutputBind: 4" 11 size + size <- withForeignPtr sizeFPtr2 peek >>= return . fromIntegral + assertEqual "testOutputBind: 5" (sizeOf (0::CInt)) size + s <- OCI.bufferToString (undefined, castForeignPtr cstrFPtr, nullIndFPtr1, sizeFPtr1) + assertEqual "testOutputBind: 6" (Just "abcdefghijk") s + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + +testOutputBindNoStrings :: (String, String, String) -> IO () +testOutputBindNoStrings args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + OCI.stmtPrepare err (castPtr stmt) (OCI.substituteBindPlaceHolders + ("begin if :1 <> 2 then " + ++ "raise_application_error(-20001, 'xx-' || to_char(:1) || '-xx'); end if; " + ++ ":1 := 130; :2 := 1026; end;")) + let sizeOfCInt = sizeOf (0::CInt) + nullIndFPtr1 <- mallocForeignPtr + nullIndFPtr2 <- mallocForeignPtr + sizeFPtr1 <- mallocForeignPtr + sizeFPtr2 <- mallocForeignPtr + cintFPtr1 <- mallocForeignPtrBytes sizeOfCInt + cintFPtr2 <- mallocForeignPtrBytes sizeOfCInt + withForeignPtr cintFPtr1 $ \p -> poke p 2 + withForeignPtr cintFPtr2 $ \p -> poke p 3 + withForeignPtr sizeFPtr1 $ \p -> poke p (fromIntegral sizeOfCInt) + withForeignPtr sizeFPtr2 $ \p -> poke p (fromIntegral sizeOfCInt) + let buffer1 = (nullIndFPtr1, castForeignPtr cintFPtr1, sizeFPtr1) + let buffer2 = (nullIndFPtr2, castForeignPtr cintFPtr2, sizeFPtr2) + OCI.bindOutputByPos err (castPtr stmt) 1 buffer1 sizeOfCInt oci_SQLT_INT + OCI.bindOutputByPos err (castPtr stmt) 2 buffer2 sizeOfCInt oci_SQLT_INT + OCI.stmtExecute err conn (castPtr stmt) 1 + ind <- withForeignPtr nullIndFPtr1 peek + assertEqual "testOutputBind: 0" 0 ind + i <- withForeignPtr cintFPtr1 peek + assertEqual "testOutputBind: 1" 130 (i :: CInt) + ind <- withForeignPtr nullIndFPtr2 peek + assertEqual "testOutputBind: 2" 0 ind + i <- withForeignPtr cintFPtr2 peek + assertEqual "testOutputBind: 3" 1026 (i :: CInt) + size <- withForeignPtr sizeFPtr1 peek >>= return . fromIntegral + assertEqual "testOutputBind: 4" sizeOfCInt size + size <- withForeignPtr sizeFPtr2 peek >>= return . fromIntegral + assertEqual "testOutputBind: 5" sizeOfCInt size + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + +testOutputStmtBind :: (String, String, String) -> IO () +testOutputStmtBind args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + OCI.stmtPrepare err (castPtr stmt) (OCI.substituteBindPlaceHolders + ("begin open :1 for select dummy from dual; end;")) + nullIndFPtr <- mallocForeignPtr + sizeFPtr <- mallocForeignPtr + bufrFPtr <- mallocForeignPtrBytes (sizeOf nullPtr) + -- you have to pass in a valid Statement Handle + -- is it replaced or just modified? + stmtx <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + withForeignPtr bufrFPtr $ \p -> poke p (castPtr stmtx) + withForeignPtr sizeFPtr $ \p -> poke p (fromIntegral (sizeOf nullPtr)) + OCI.bindOutputByPos err (castPtr stmt) 1 (nullIndFPtr, castForeignPtr bufrFPtr, sizeFPtr) (sizeOf nullPtr) oci_SQLT_RSET + OCI.stmtExecute err conn (castPtr stmt) 1 + ind <- withForeignPtr nullIndFPtr $ \p -> peek p + assertEqual "testOutputStmtBind: ind" 0 ind + --stmt2 <- withForeignPtr bufrFPtr (peek . castPtr) + let stmt2 = stmtx + buffer@(_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt2) 1 100 oci_SQLT_CHR + rc <- OCI.stmtFetch err (castPtr stmt2) + s <- OCI.bufferToString buffer + assertEqual "testOutputStmtBind: stmt2 dummy" (Just "X") s + OCI.handleFree oci_HTYPE_STMT (castPtr stmt2) + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + + +-- This just shows that the parent StmtHandle can be safely +-- closed before we fetch from the child, and this doesn't +-- seem to matter. +-- This only works for PL/SQL statements that have output bind variables. +-- For select statements that return cursors, closing the parent +-- statement closes all the child cursors too. + +testOutputStmtBindCloseEarly :: (String, String, String) -> IO () +testOutputStmtBindCloseEarly args = do + (env, err, conn) <- logon args + OCI.catchOCI ( do + stmt <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + OCI.stmtPrepare err (castPtr stmt) (OCI.substituteBindPlaceHolders + ("begin open :1 for select 'A' from dual; end;")) + nullIndFPtr <- mallocForeignPtr + sizeFPtr <- mallocForeignPtr + bufrFPtr <- mallocForeignPtrBytes (sizeOf nullPtr) + -- you have to pass in a valid Statement Handle + -- is it replaced or just modified? + stmtx <- OCI.handleAlloc oci_HTYPE_STMT (castPtr env) + withForeignPtr bufrFPtr $ \p -> poke p (castPtr stmtx) + withForeignPtr sizeFPtr $ \p -> poke p (fromIntegral (sizeOf nullPtr)) + OCI.bindOutputByPos err (castPtr stmt) 1 (nullIndFPtr, castForeignPtr bufrFPtr, sizeFPtr) (sizeOf nullPtr) oci_SQLT_RSET + OCI.stmtExecute err conn (castPtr stmt) 1 + ind <- withForeignPtr nullIndFPtr $ \p -> peek p + assertEqual "testOutputStmtBindCloseEarly: ind" 0 ind + --stmt2 <- withForeignPtr bufrFPtr (peek . castPtr) + OCI.handleFree oci_HTYPE_STMT (castPtr stmt) + let stmt2 = stmtx + buffer@(_, buf, nullptr, sizeptr) <- OCI.defineByPos err (castPtr stmt2) 1 100 oci_SQLT_CHR + rc <- OCI.stmtFetch err (castPtr stmt2) + s <- OCI.bufferToString buffer + assertEqual "testOutputStmtBindCloseEarly: stmt2 dummy" (Just "A") s + OCI.handleFree oci_HTYPE_STMT (castPtr stmt2) + ) (\ociexc -> reportAndIgnore (castPtr err) ociexc nullAction) + logoff (env, err, conn) + +testSubst input expect = do + let actual = OCI.substituteBindPlaceHolders input + when (actual /= expect) (error $ "testSubstBindPlaceHolders failed: " ++ input ++ " -> " ++ actual) + +testSubstituteBindPlaceHolders :: IO () +testSubstituteBindPlaceHolders = do + testSubst "?'?'?" ":1'?':2" + testSubst "?" ":1" + testSubst "" "" + testSubst "x" "x" + testSubst "????????????" ":1:2:3:4:5:6:7:8:9:10:11:12" + testSubst "?'''?'''''?" ":1'''?''''':2" + + +parseArgs :: [String] -> IO (String, String, String) +parseArgs args = do + let [u, p, d] = args + return (u, p, d) + +testlist args = + [ testCreateEnv + , testConnect args + , testBeginTrans args + , testExecute args + , testFetch args + , testFetchFail args + , testFetchStmt args + , testNestedFetchStmt args + , testBind args + , testOutputBind args + , testOutputBindNoStrings args + , testOutputStmtBind args + , testOutputStmtBindCloseEarly args + , testSubstituteBindPlaceHolders + ] + +runTest :: [String] -> IO () +runTest as = do + args <- parseArgs as + counts <- runTestTT "Oracle low-level tests" (testlist args) + return ()
+ Database/Test/Enumerator.lhs view
@@ -0,0 +1,480 @@+ +| +Module : Database.Test.Enumerator +Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +License : BSD-style +Maintainer : oleg@pobox.com, alistair@abayley.org +Stability : experimental +Portability : non-portable + +Simple test harness. Demonstrates possible usage. + +Tests in this module are organised in groups of three/four functions: + sqlXXX + iterXXX + expectXXX + actionXXX + +These have to be tied together by a function which uses backend-specific +functions and types. See the various backend-specific test modules for examples. + + +> {-# LANGUAGE OverlappingInstances #-} + +> module Database.Test.Enumerator where + +> import Database.Enumerator +> import Database.Util +> import Data.Time +> import System.Time +> import Data.Int +> import Control.Exception.MonadIO +> import Control.Monad.Trans (liftIO) +> import Test.MiniUnit + + +> testTable = "takusen_test" + +> sqlDropDual = "drop table tdual" +> sqlCreateDual = "create table tdual (dummy varchar(1) primary key)" +> sqlInsertDual = "insert into tdual values ('X')" +> sqlDropTest = "drop table " ++ testTable +> sqlCreateTest = "create table " ++ testTable ++ " (id integer, v varchar(250))" + +> sqlInsertTest1 = "insert into " ++ testTable ++ " (id, v) values (1, '2')" +> sqlInsertTest2 = "insert into " ++ testTable ++ " (id, v) values (2, '2')" +> sqlInsertTest3 = "insert into " ++ testTable ++ " (id, v) values (3, '3')" +> sqlInsertTest4 = "insert into " ++ testTable ++ " (id, v) values (4, '4')" + + +> reportError sql (DBFatal (ssc, sssc) e m) = do +> putStrLn ("FATAL: " ++ ssc ++ sssc ++ " - " ++ m) +> putStrLn (" " ++ sql) +> reportError sql (DBError (ssc, sssc) e m) = do +> putStrLn ("ERROR: " ++ ssc ++ sssc ++ " - " ++ m) +> putStrLn (" " ++ sql) +> reportError sql (DBUnexpectedNull r c) = +> putStrLn $ "Unexpected null in row " ++ (show r) ++ ", column " ++ (show c) ++ "." +> reportError sql (DBNoData) = putStrLn "Fetch: no more data." + +----------------------------------------------------------- + +> class DBLiteralValue a where +> literalDate :: a -> Int64 -> String +> literalInt :: a -> Int -> String +> literalInt64 :: a -> Int64 -> String +> literalFloat :: a -> Float -> String +> literalDouble :: a -> Double -> String +> -- default methods +> literalInt _ i = show i +> literalInt64 _ i = show i +> literalFloat _ i = show i +> literalDouble _ i = show i + + +> data SqliteFunctions = SqliteFunctions +> data OracleFunctions = OracleFunctions +> data PGSqlFunctions = PGSqlFunctions +> data ODBCFunctions = ODBCFunctions + +> instance DBLiteralValue SqliteFunctions where +> literalDate _ i = dateSqlite i + +> instance DBLiteralValue OracleFunctions where +> literalDate _ i = dateOracle i + +> instance DBLiteralValue PGSqlFunctions where +> literalDate _ i = datePG i +> literalInt _ i = show i ++ "::int4" +> literalInt64 _ i = show i ++ "::int8" +> literalFloat _ i = show i ++ "::float4" +> literalDouble _ i = show i ++ "::float8" + +> instance DBLiteralValue ODBCFunctions where +> literalDate _ i = dateISO i + + + +> dateSqlite :: Int64 -> String +> dateSqlite i = if i == 0 then "99999999999999" else show i + +> dateOracle :: Int64 -> String +> dateOracle i +> | i == 0 = "to_date(null)" +> | i > 0 = "to_date('" ++ (zeroPad 14 i) ++ "', 'yyyymmddhh24miss')" +> | i < 0 = "to_date('" ++ (zeroPad 14 i) ++ "', 'syyyymmddhh24miss')" + +> dateISO :: Int64 -> String +> dateISO i = +> let +> (year, month, day, hour, minute, second) = int64ToDateParts i +> zp = zeroPad +> in +> if i == 0 then "null" +> else zp 4 year ++ "-" ++ zp 2 month ++ "-" ++ zp 2 day +> ++ "T" ++ zp 2 hour ++ ":" ++ zp 2 minute ++ ":" ++ zp 2 second + + +For postgres: +0000-01-01 AD -> 0001-01-01 BC +0000-12-31 AD -> 0001-12-31 BC +0001-01-01 AD -> 0001-01-01 AD + +Using Doubles as storage (not sure about this?) +4714-11-24 BC -> mindate +5874897-12-31 AD -> maxdate +Using 8-bytes ints: +4713 BC -> 294276 AD + +Postgres only allows specification of -ve years by use of the AD/BC suffix. +Sadly, this differs from the astronomical year number like so: +astro: ...3,2,1,0,-1,-2,-3,... +ad/bc: ...3AD,2AD,1AD,1BC,2BC,3BC,... + +i.e. 0 astro = 1BC, -1 astro = 2BC, etc. + +ISO8601 uses astronomical years, so we ought to be able to write +-1000-12-25 (instead of 1001-01-01 BC), but Postgres won't parse this. + +So in datePG we want: +int64 0000-01-01 -> 0001-01-01 AD +int64 0001-01-01 -> 0001-01-01 AD +int64 -0001-01-01 -> 0000-01-01 AD +int64 -0002-01-01 -> 0003-01-01 BC +int64 -4712-01-01 -> 4713-01-01 BC + +> datePG :: Int64 -> String +> datePG i = +> let +> (year1, month, day, hour, minute, second) = int64ToDateParts i +> year = case () of +> _ | year1 == 0 -> 1 +> | year1 < 0 -> abs (year1 - 1) +> | otherwise -> year1 +> suffix = if year1 < 1 then " BC'" else " AD'" +> zp = zeroPad +> in +> if i == 0 then "null::timestamp" +> --else "timestamp with time zone '" ++ zp 4 year ++ "-" ++ zp 2 month ++ "-" ++ zp 2 day +> else "timestamp '" ++ zp 4 year ++ "-" ++ zp 2 month ++ "-" ++ zp 2 day +> ++ " " ++ zp 2 hour ++ ":" ++ zp 2 minute ++ ":" ++ zp 2 second ++ suffix + + + + +> execDDL_ s = catchDB (execDDL s) (reportRethrowMsg ("sql: " ++ s ++ "\n")) +> execDML_ s = execDDL_ s + +Use execDrop when the DDL is likely to raise an error. +Note that PostgreSQL + ODBC seems to require you commit or rollback the DDL; +if you don't then the next statement will fail with a 25P02 +("in failed SQL transaction") +I guess that's a result of PostgreSQL's transactional DDL feature. + +> execDrop s = catchDB (withTransaction Serializable (execDDL s)) (\e -> return ()) + +> makeFixture doDrop doDDL = flip catchDB (reportRethrowMsg "makeFixture: ") $ do +> doDrop sqlDropDual +> doDrop sqlDropTest +> doDDL sqlCreateDual +> beginTransaction ReadCommitted +> doDDL sqlInsertDual +> commit +> doDDL sqlCreateTest +> withTransaction Serialisable $ do +> doDDL sqlInsertTest1 +> doDDL sqlInsertTest2 +> doDDL sqlInsertTest3 + +> destroyFixture execDDL_ = flip catchDB (reportRethrowMsg "destroyFixture: ") $ do +> execDDL_ sqlDropDual +> execDDL_ sqlDropTest +> catchDB commit (const (return ())) + +> selectTest query iter expect = do +> actual <- doQuery query iter [] +> assertEqual query expect actual + + + +----------------------------------------------------------- + +This is used in a few tests... + +> sqlSingleValue = "select ? from tdual" + +> sqlNoRows = "select dummy from tdual where dummy = 'a' or dummy = '2' " +> iterNoRows (c1::String) acc = result $ c1:acc +> expectNoRows = []::[String] + +> sqlTermEarly = "select 'hello1' from tdual union select 'hello2' from tdual union select 'hello3' from tdual order by 1" +> iterTermEarly c1 acc = if c1 == "hello2" +> then return (Left (c1:acc)) +> else result (c1:acc) +> expectTermEarly = ["hello2", "hello1"] + +> sqlFloatsAndInts fns = "select " ++ (literalDouble fns 4841.3403490431) ++ ", " +> ++ (literalInt fns (-22340234)) ++ " from tdual union select 33311.32332, 23789234 from tdual order by 1" +> --iterFloatsAndInts :: (Monad m) => Double -> Int -> IterAct m [(Double, Int)] +> iterFloatsAndInts (c1::Double) (c2::Int) acc = result $ (c1, c2):acc +> expectFloatsAndInts :: [(Double, Int)] +> expectFloatsAndInts = [ (33311.32332, 23789234) , (4841.3403490431, -22340234) ] + +> sqlNullString = "select 'hello1', 'hello2', null from tdual" +> iterNullString :: (Monad m) => String -> String -> Maybe String +> -> IterAct m [(String, String, Maybe String)] +> iterNullString c1 c2 c3 acc = result $ (c1, c2, c3):acc +> expectNullString = [ ("hello1", "hello2", Nothing) ] + +Access can't handle SQL comments (-- or /* */). + +> sqlEmptyString = "select 'hello1', 'Oracle always fails this test', '' from tdual" +> iterEmptyString :: (Monad m) => String -> String -> Maybe String +> -> IterAct m [(String, String, Maybe String)] +> iterEmptyString c1 c2 c3 acc = result $ (c1, c2, c3):acc +> expectEmptyString = [ ("hello1", "Oracle always fails this test", Just "") ] + +> sqlUnhandledNull = "select 'hello1', 'hello2', null from tdual" +> iterUnhandledNull :: (Monad m) => String -> String -> UTCTime +> -> IterAct m [(String, String, UTCTime)] +> iterUnhandledNull c1 c2 c3 acc = result $ (c1, c2, c3):acc +> expectUnhandledNull = [] + +> sqlNullDate fns = "select 'hello1', 'hello2', " ++ (literalDate fns 0) ++ " from tdual" +> iterNullDate :: (Monad m) => String -> String -> Maybe UTCTime +> -> IterAct m [(String, String, UTCTime)] +> iterNullDate c1 c2 c3 acc = result $ (c1, c2, ifNull c3 (int64ToUTCTime 10101000000)):acc +> expectNullDate = [ ("hello1", "hello2", (int64ToUTCTime 10101000000)) ] + +> sqlDate fns = "select " ++ (literalDate fns 20041224235959) ++ " from tdual" +> iterDate :: (Monad m) => UTCTime -> IterAct m [UTCTime] +> iterDate c1 acc = result $ c1:acc +> expectDate = [ (int64ToUTCTime 20041224235959) ] + +> iterCalDate :: (Monad m) => CalendarTime -> IterAct m [CalendarTime] +> iterCalDate c1 acc = result $ c1:acc +> expectCalDate = [ (int64ToCalTime 20041224235959) ] + + +These are the Oracle date boundary cases. + +> sqlBoundaryDates fns = +> "select " ++ (literalDate fns 99991231000000) ++ " from tdual" +> ++ " union select " ++ (literalDate fns 10101000000) ++ " from tdual" +> ++ " union select " ++ (literalDate fns (-10101000000)) ++ " from tdual" +> ++ " union select " ++ (literalDate fns (-47120101000000)) ++ " from tdual" +> ++ " order by 1 desc" +> iterBoundaryDates :: (Monad m) => UTCTime -> IterAct m [UTCTime] +> iterBoundaryDates c1 acc = result $ c1:acc +> expectBoundaryDates = +> [ int64ToUTCTime (-47120101000000) +> , int64ToUTCTime (-10101000000) +> , int64ToUTCTime 10101000000 +> , int64ToUTCTime 99991231000000 +> ] + +|Goal: exercise the "happy path" throught cursor code +i.e. open and fetch all rows, close after last row. + +> sqlCursor fns = "select " ++ literalInt fns 1 ++ " from tdual union select " ++ literalInt fns 2 ++ " from tdual" +> iterCursor :: (Monad m) => Int -> IterAct m [Int] +> iterCursor i acc = result $ i:acc +> actionCursor query = do +> withCursor query iterCursor [] $ \c -> do +> doneBool <- cursorIsEOF c +> assertBool query (not doneBool) +> r <- cursorCurrent c +> assertEqual query [1] r +> -- +> cursorNext c +> doneBool <- cursorIsEOF c +> assertBool query (not doneBool) +> r <- cursorCurrent c +> assertEqual query [2, 1] r +> -- +> -- Now that the result-set is exhausted, cursorIsEOF returns True, +> -- and cursorCurrent returns the same value as the previous call to cursorCurrent. +> cursorNext c +> doneBool <- cursorIsEOF c +> assertBool query doneBool +> r <- cursorCurrent c +> assertEqual query [2, 1] r +> -- +> -- What happens if try to advance again? +> -- We get a DBException: the DBNoData case. +> --cursorNext c +> doneBool <- cursorIsEOF c +> assertBool query doneBool +> r <- cursorCurrent c +> assertEqual query [2, 1] r +> -- +> return () + +|Goal: ensure exception raised when too many rows +fetched from cursor. + +This test will raise an exception, as it tries to +fetch too many rows from the cursor. +The exception handler is coded as if we expect the +exception i.e. it ignores it. +The main action should never finish, so there's +a failure assertion at the bottom, just in case +the exception is not raised. + +> actionExhaustCursor query = catchDB ( +> withCursor query iterCursor [] $ \c -> do +> cursorNext c +> cursorNext c +> cursorNext c +> cursorNext c +> assertFailure "selectExhaustCursor" +> ) (\e -> return () ) + +> sqlBindString = "select ? from tdual union select ? from tdual order by 1" +> iterBindString :: (Monad m) => String -> IterAct m [String] +> iterBindString i acc = result $ i:acc +> expectBindString = ["b1", "a2"] +> actionBindString stmt bindVals = do +> withTransaction Serialisable $ do +> withPreparedStatement stmt $ \pstmt -> do +> withBoundStatement pstmt bindVals $ \bstmt -> do +> actual <- doQuery bstmt iterBindString [] +> assertEqual sqlBindString expectBindString actual + + +Each back-end has it's own idea of parameter placeholder syntax. +We currently support ?-style as a lowest-common-denominator, +and each back-end converts occurences of "?" +to the back-end-specific style where required. +If you use a back-end specific style, you can expect it to be passed +through unmolested. + ? : ODBC, MS Sql Server, Sqlite + :n : Oracle + $n : Postgres + +> sqlBindInt = "select ? from tdual union select ? from tdual order by 1" +> iterBindInt :: (Monad m) => Int -> IterAct m [Int] +> iterBindInt i acc = result $ i:acc +> expectBindInt :: [Int]; expectBindInt = [2, 1] +> actionBindInt stmt bindVals = do +> withTransaction Serialisable $ do +> withPreparedStatement stmt $ \pstmt -> do +> withBoundStatement pstmt bindVals $ \bstmt -> do +> actual <- doQuery bstmt iterBindInt [] +> assertEqual sqlBindInt expectBindInt actual + +> sqlBindIntDoubleString = "select ?,?,? from tdual union select ?,?,? from tdual order by 1" +> iterBindIntDoubleString :: (Monad m) => Int -> Double -> String -> IterAct m [(Int, Double, String)] +> iterBindIntDoubleString i d s acc = result $ (i, d, s):acc +> expectBindIntDoubleString :: [(Int, Double, String)] +> expectBindIntDoubleString = [(3, 4.4, "row 2"), (1, 2.2, "row 1")] +> actionBindIntDoubleString stmt = do +> withTransaction Serialisable $ do +> actual <- doQuery stmt iterBindIntDoubleString [] +> assertEqual sqlBindIntDoubleString expectBindIntDoubleString actual + +> sqlBindDate = sqlSingleValue +> iterBindDate :: (Monad m) => UTCTime -> IterAct m [UTCTime] +> iterBindDate c1 acc = result $ c1:acc +> expectBindDate = [ int64ToUTCTime 20041224235959 ] +> actionBindDate stmt = do +> withTransaction Serialisable $ do +> actual <- doQuery stmt iterBindDate [] +> assertEqual sqlBindDate expectBindDate actual + +> sqlBindBool = "select ?, ? from tdual" +> iterBindBool :: (Monad m) => Bool -> Bool -> IterAct m [(Bool, Bool)] +> iterBindBool b1 b2 acc = result $ (b1,b2):acc +> expectBindBool = [ (True, False) ] +> actionBindBool stmt = do +> withTransaction Serialisable $ do +> actual <- doQuery stmt iterBindBool [] +> assertEqual sqlBindBool expectBindBool actual + +> sqlBindBoundaryDates = +> "select ? from tdual" +> ++ " union select ? from tdual" +> ++ " union select ? from tdual" +> ++ " union select ? from tdual" +> ++ " order by 1 desc" +> actionBindBoundaryDates stmt = do +> withTransaction Serialisable $ do +> actual <- doQuery stmt iterBindDate [] +> assertEqual sqlBindBoundaryDates expectBoundaryDates actual + + +> sqlBoundStmtDML = "insert into " ++ testTable ++ " (id, v) values (?, ?)" +> actionBoundStmtDML stmt = do +> withPreparedStatement stmt $ \pstmt -> do +> -- do it twice, to check that prepared stmt can be reused. +> -- Note that with bound statements, the query (or command) +> -- already been executed, so it's too late to begin the transaction. +> beginTransaction Serialisable +> withBoundStatement pstmt [bindP (100::Int), bindP "100"] $ \bstmt -> do +> count <- execDML bstmt +> rollback +> assertEqual sqlBoundStmtDML 1 count +> beginTransaction Serialisable +> withBoundStatement pstmt [bindP (100::Int), bindP "100"] $ \bstmt -> do +> count <- execDML bstmt +> rollback +> assertEqual sqlBoundStmtDML 1 count + + + +With 'MyTree' we test the ability to send and receive arbtrary Show-able +values as Strings i.e. we create our own datatype for the test. + +> data MyTree a = Leaf a | Branch [MyTree a] deriving (Eq, Show, Read) + +> sqlPolymorphicFetch = sqlSingleValue +> iterPolymorphicFetch :: (Monad m) => MyTree String -> IterAct m (MyTree String) +> iterPolymorphicFetch v _ = result' v +> expectPolymorphicFetch = Branch [Leaf "a", Leaf "b", Branch [Leaf "c", Leaf "d"], Leaf "e"] +> actionPolymorphicFetch stmt = do +> actual <- doQuery stmt iterPolymorphicFetch (Leaf "") +> assertEqual sqlPolymorphicFetch expectPolymorphicFetch actual + +> sqlPolymorphicFetchNull = "select '' from tdual" +> iterPolymorphicFetchNull :: (Monad m) => Maybe (MyTree String) -> IterAct m (Maybe (MyTree String)) +> iterPolymorphicFetchNull v _ = result' v +> expectPolymorphicFetchNull :: Maybe (MyTree String) +> expectPolymorphicFetchNull = Nothing +> actionPolymorphicFetchNull stmt = do +> actual <- doQuery stmt iterPolymorphicFetchNull Nothing +> assertEqual sqlPolymorphicFetchNull Nothing actual + +> sqlRebind = sqlSingleValue +> iterRebind (i::Int) acc = result $ i:acc +> expectRebind1 :: [Int]; expectRebind1 = [1] +> expectRebind2 :: [Int]; expectRebind2 = [2] +> actionRebind stmt bindVal1 bindVal2 = do +> withPreparedStatement stmt $ \pstmt -> do +> withBoundStatement pstmt bindVal1 $ \bstmt -> do +> actual <- doQuery bstmt iterRebind [] +> assertEqual sqlRebind expectRebind1 actual +> withBoundStatement pstmt bindVal2 $ \bstmt -> do +> actual <- doQuery bstmt iterRebind [] +> assertEqual sqlRebind expectRebind2 actual + +> sqlExceptionRollback = "select count(*) from " ++ testTable +> iterExceptionRollback (i::Int) acc = result $ i:acc +> actionExceptionRollback insertStmt selectStmt = do +> catchDB ( +> withTransaction Serialisable $ do +> execDML insertStmt +> throwDB DBNoData +> ) (\e -> return () ) +> count <- doQuery selectStmt iterExceptionRollback [] +> assertEqual sqlExceptionRollback [3] count + +> sqlIterateeMatchesResultSet = "select ?,?,? from tdual" +> --iterMatchesResultSet :: (Monad m) => Int -> Double -> String -> IterAct m [(Int, Double, String)] +> --iterMatchesResultSet i d s acc = result $ (i, d, s):acc +> iterMatchesResultSet :: (Monad m) => Int -> Double -> String -> String -> IterAct m [(Int, Double, String, String)] +> iterMatchesResultSet i d s s2 acc = result $ (i, d, s, s2):acc +> actionIterateeMatchesResultSet stmt = do +> catchDB ( do +> actual <- doQuery stmt iterMatchesResultSet [] +> assertFailure "actionIterateeMatchesResultSet" +> ) (\e -> return () )
+ Database/Test/Performance.lhs view
@@ -0,0 +1,99 @@+ +| +Module : Database.Test.Performance +Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +License : BSD-style +Maintainer : oleg@pobox.com, alistair@abayley.org +Stability : experimental +Portability : non-portable + +Performance tests. Currently just tests large result sets. + + +> {-# LANGUAGE OverlappingInstances #-} + +> module Database.Test.Performance where + +> import Database.Enumerator +> import Database.Util +> import System.Environment (getArgs) +> import Control.Monad +> import System.Time +> import Test.MiniUnit +> import Control.Monad.Reader + +> data ShouldRunTests = RunTests | Don'tRunTests deriving (Show, Eq) + +> timedCursor stmt limit rows = do +> withCursor stmt (rowCounter rows) 0 $ \c -> do +> ct1 <- liftIO getClockTime +> replicateM_ rows (cursorNext c) +> ct2 <- liftIO getClockTime +> let diffCt = diffClockTimes ct2 ct1 +> let limitDiff = TimeDiff 0 0 0 0 0 limit 0 +> print_ $ "timedCursor: " ++ timeDiffToString diffCt +> assertBool ("timedCursor: time " ++ (timeDiffToString diffCt) ++ " (limit " ++ (timeDiffToString limitDiff) ++ ")") +> (diffCt < limitDiff) + + +> timedSelect stmt limit rows = do +> ct1 <- liftIO getClockTime +> r <- doQuery stmt (rowCounter rows) 0 +> ct2 <- liftIO getClockTime +> let diffCt = diffClockTimes ct2 ct1 +> -- assume it must complete within limit seconds +> let limitDiff = TimeDiff 0 0 0 0 0 limit 0 +> print_ $ "timedSelect: " ++ timeDiffToString diffCt +> assertBool ("timedSelect: time " ++ (timeDiffToString diffCt) ++ " (limit " ++ (timeDiffToString limitDiff) ++ ")") +> (diffCt < limitDiff) +> assertEqual ("timedSelect: rows " ++ (show r)) rows r + + +|This counter takes the maximum number of rows to fetch as its first argument, +so don't forget to curry it when using it as an iteratee function. +We also try to ensure that it is strict in the counter; +we don't want thousands or millions of unevaluated '+' thunks sitting +on the stack. + +> rowCounter :: (Monad m) => Int -> Int -> IterAct m Int +> rowCounter n _ i = result' (i+1) +> --if i >= n then return (Left $! i) else return (Right $! (1 + i)) +> --if i >= n then return (Left i) else return (Right (1 + i)) + + +2 ^ 16 = 65536 +2 ^ 20 = 1048576 + +Cartesian product. Each instance of the subquery multiplies +the total number of rows by 2, so the number of rows +is 2 ^ (count of subquery instances). +You start to notice the pause around 2^13, +and 2^16 blows out the standard 1M stack +if you use the lazy version of result. Bummer. + +> sqlRows2Power17 :: String +> sqlRows2Power17 = +> "select 1 from" +> ++ " ( select 1 x from tdual union select 0 from tdual) t1" +> ++ ", ( select 2 x from tdual union select 0 from tdual) t2" +> ++ ", ( select 3 x from tdual union select 0 from tdual) t3" +> ++ ", ( select 4 x from tdual union select 0 from tdual) t4" +> ++ ", ( select 5 x from tdual union select 0 from tdual) t5" +> ++ ", ( select 6 x from tdual union select 0 from tdual) t6" +> ++ ", ( select 7 x from tdual union select 0 from tdual) t7" +> ++ ", ( select 8 x from tdual union select 0 from tdual) t8" +> ++ ", ( select 9 x from tdual union select 0 from tdual) t9" +> ++ ", ( select 10 x from tdual union select 0 from tdual) t10" +> ++ ", ( select 11 x from tdual union select 0 from tdual) t11" +> ++ ", ( select 12 x from tdual union select 0 from tdual) t12" +> ++ ", ( select 13 x from tdual union select 0 from tdual) t13" +> ++ ", ( select 14 x from tdual union select 0 from tdual) t14" +> ++ ", ( select 15 x from tdual union select 0 from tdual) t15" +> ++ ", ( select 16 x from tdual union select 0 from tdual) t16" +> ++ ", ( select 17 x from tdual union select 0 from tdual) t17" + +> sqlRows2Power20 :: String +> sqlRows2Power20 = sqlRows2Power17 +> ++ ", ( select 18 x from tdual union select 0 from tdual) t18" +> ++ ", ( select 19 x from tdual union select 0 from tdual) t19" +> ++ ", ( select 20 x from tdual union select 0 from tdual) t20"
+ Database/Test/Util.lhs view
@@ -0,0 +1,129 @@+> {-# LANGUAGE CPP #-} + +> module Database.Test.Util where + +> import Database.Util +> import Test.MiniUnit +> import Data.Int +> import Data.Char + + +> runTest :: a -> [String] -> IO () +> runTest _ _ = do +> counts <- runTestTT "Util module tests" testlist +> return () + +> testlist = +> [ testSubstr +> , testWordsBy +> , testInt64ToDatePartsMinDate +> , testInt64ToDatePartsMaxDate +> , testUtcTimeToInt64MinDate +> , testUtcTimeToInt64MaxDate +> , testCalTimeToInt64MinDate +> , testCalTimeToInt64MaxDate +> , testInt64ToCalTimeMinDate +> , testInt64ToCalTimeMaxDate +> , testPGDatetimeToUTCTimeMinDate +> , testPGDatetimeToUTCTimeMaxDate +> , testPGDatetimeToUTCTimeBCBoundary +> , testPGDatetimeToUTCTimeBCBoundary2 +> , testUTCTimeToPGDatetimeMinDate +> , testUTCTimeToPGDatetimeMaxDate +> ] + +> testSubstr = do +> assertEqual "substr - 1" "a" (substr 1 1 "abc") +> assertEqual "substr - 2" "b" (substr 2 1 "abc") +> assertEqual "substr - 3" "c" (substr 3 1 "abc") +> assertEqual "substr - 4" "bc" (substr 2 2 "abc") +> assertEqual "substr - 5" "ab" (substr 1 2 "abc") +> assertEqual "substr - 6" "abc" (substr 1 4 "abc") +> assertEqual "substr -76" "" (substr 4 4 "abc") + +> testWordsBy = do +> assertEqual "wordsBy - 1" [] (wordsBy isDigit "") +> assertEqual "wordsBy - 2" [] (wordsBy isDigit " --,") +> assertEqual "wordsBy - 2.5" ["5"] (wordsBy isDigit "5") +> assertEqual "wordsBy - 2.75" ["5"] (wordsBy isDigit "5 ") +> assertEqual "wordsBy - 3" ["5"] (wordsBy isDigit "5 --,") +> assertEqual "wordsBy - 4" ["6"] (wordsBy isDigit " --,6") +> assertEqual "wordsBy - 5" ["7"] (wordsBy isDigit " --7, ") +> assertEqual "wordsBy - 6" ["100", "12", "67", "25"] (wordsBy isDigit "100-12,67--, 25") + + +-4712 (4713BC?) is a very common minimum date among DBMS implementations. +Maximum varies, but is often 5874897 AD. + +ghc-6.4.1 needs this, because it only has Show instances for +up to 5-tuples. + +#if __GLASGOW_HASKELL__ <= 604 +> instance (Show a, Show b, Show c, Show d, Show e, Show f) +> => Show (a,b,c,d,e,f) where +> show (a,b,c,d,e,f) = +> "(" ++ show a +> ++ "," ++ show a +> ++ "," ++ show b +> ++ "," ++ show c +> ++ "," ++ show d +> ++ "," ++ show e +> ++ "," ++ show f +> ++ ")" +#endif + +> testInt64ToDatePartsMinDate = do +> let expect :: (Int64,Int64,Int64,Int64,Int64,Int64); expect = (-4712,1,1,0,0,0) +> assertEqual "testInt64ToDatePartsMinDate" expect (int64ToDateParts (-47120101000000)) + +> testInt64ToDatePartsMaxDate = do +> let expect :: (Int64,Int64,Int64,Int64,Int64,Int64); expect = (999999,12,31,23,59,59) +> assertEqual "testInt64ToDatePartsMaxDate" expect (int64ToDateParts (9999991231235959)) + +> testUtcTimeToInt64MinDate = do +> let expect :: Int64; expect = (-47120101000000) +> assertEqual "testUtcTimeToInt64MinDate" expect (utcTimeToInt64 (mkUTCTime (-4712) 1 1 0 0 0)) + +> testUtcTimeToInt64MaxDate = do +> let expect :: Int64; expect = (9999991231235959) +> assertEqual "testUtcTimeToInt64MaxDate" expect (utcTimeToInt64 (mkUTCTime 999999 12 31 23 59 59)) + +> testCalTimeToInt64MinDate = do +> let expect :: Int64; expect = (-47120101000000) +> assertEqual "testCalTimeToInt64MinDate" expect (calTimeToInt64 (mkCalTime (-4712) 1 1 0 0 0)) + +> testCalTimeToInt64MaxDate = do +> let expect :: Int64; expect = (9999991231235959) +> assertEqual "testCalTimeToInt64MaxDate" expect (calTimeToInt64 (mkCalTime 999999 12 31 23 59 59)) + +> testInt64ToCalTimeMinDate = do +> let expect = mkCalTime (-4712) 1 1 0 0 0 +> assertEqual "testInt64ToCalTimeMinDate" expect (int64ToCalTime (-47120101000000)) + +> testInt64ToCalTimeMaxDate = do +> let expect = mkCalTime 999999 12 31 23 59 59 +> assertEqual "testInt64ToCalTimeMaxDate" expect (int64ToCalTime 9999991231235959) + +> testPGDatetimeToUTCTimeMinDate = do +> let expect = mkUTCTime (-4712) 1 1 0 0 0 +> assertEqual "testPGDatetimeToUTCTimeMinDate" expect (pgDatetimetoUTCTime "4713-01-01 00:00:00 BC") + +> testPGDatetimeToUTCTimeMaxDate = do +> let expect = mkUTCTime 999999 1 1 0 0 0 +> assertEqual "testPGDatetimeToUTCTimeMaxDate" expect (pgDatetimetoUTCTime "999999-01-01 00:00:00+00") + +> testPGDatetimeToUTCTimeBCBoundary = do +> let expect = mkUTCTime 0 1 1 0 0 0 +> assertEqual "testPGDatetimeToUTCTimeBCBoundary" expect (pgDatetimetoUTCTime "0001-01-01 00:00:00 BC") + +> testPGDatetimeToUTCTimeBCBoundary2 = do +> let expect = mkUTCTime 0 12 31 0 0 0 +> assertEqual "testPGDatetimeToUTCTimeBCBoundary2" expect (pgDatetimetoUTCTime "0001-12-31 00:00:00 BC") + +> testUTCTimeToPGDatetimeMinDate = do +> let expect = "4713-01-01T00:00:00.000000+00 BC" +> assertEqual "testUTCTimeToPGDatetimeMinDate" expect (utcTimeToPGDatetime (mkUTCTime (-4712) 1 1 0 0 0)) + +> testUTCTimeToPGDatetimeMaxDate = do +> let expect = "999999-01-01T00:00:00.300001+00 AD" +> assertEqual "testUTCTimeToPGDatetimeMaxDate" expect (utcTimeToPGDatetime (mkUTCTime 999999 1 1 0 0 0.300001))
+ Database/Util.hs view
@@ -0,0 +1,283 @@+{- +Module : Database.Util +Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +License : BSD-style +Maintainer : oleg@pobox.com, alistair@abayley.org +Stability : experimental +Portability : non-portable + +Utility functions. Mostly used in database back-ends, and tests. +-} + +{-# LANGUAGE TypeSynonymInstances #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE OverlappingInstances #-} +{-# LANGUAGE UndecidableInstances #-} + +module Database.Util where + +import System.Time +import Control.Monad.Trans (liftIO) +import Control.Monad.Reader +import Data.Int +import Data.List +import Data.Char +import Data.Time +import Data.Word (Word8) +import Foreign.Ptr (Ptr, castPtr) +import Foreign.Marshal.Array (peekArray) +import Numeric (showHex) +import Text.Printf + +{- +MyShow requires overlapping AND undecidable instances. +-} + +class Show a => MyShow a where show_ :: a -> String +instance MyShow String where show_ s = s +instance (Show a) => MyShow a where show_ = show + +-- Like 'System.IO.print', except that Strings are not escaped or quoted. + +print_ :: (MonadIO m, MyShow a) => a -> m () +print_ s = liftIO (putStrLn (show_ s)) + +-- Convenience for making UTCTimes. Assumes the time given is already UTC time +-- i.e. there's no timezone adjustment. + +mkUTCTime :: (Integral a, Real b) => a -> a -> a -> a -> a -> b -> UTCTime +mkUTCTime year month day hour minute second = + localTimeToUTC (hoursToTimeZone 0) + (LocalTime + (fromGregorian (fromIntegral year) (fromIntegral month) (fromIntegral day)) + (TimeOfDay (fromIntegral hour) (fromIntegral minute) (realToFrac second))) + +mkCalTime :: Integral a => a -> a -> a -> a -> a -> a -> CalendarTime +mkCalTime year month day hour minute second = + CalendarTime + { ctYear = fromIntegral year + , ctMonth = toEnum (fromIntegral month - 1) + , ctDay = fromIntegral day + , ctHour = fromIntegral hour + , ctMin = fromIntegral minute + , ctSec = fromIntegral second + , ctPicosec = 0 + , ctWDay = Sunday + , ctYDay = -1 + , ctTZName = "UTC" + , ctTZ = 0 + , ctIsDST = False + } + +{- +20040822073512 + 10000000000 (10 ^ 10) * year + 100000000 (10 ^ 8) * month + 1000000 (10 ^ 6) * day + 10000 (10^4) * hour + +Use quot and rem, /not/ div and mod, +so that we get sensible behaviour for -ve numbers. +-} + +int64ToDateParts :: Int64 -> (Int64, Int64, Int64, Int64, Int64, Int64) +int64ToDateParts i = + let + year1 = (i `quot` 10000000000) + month = ((abs i) `rem` 10000000000) `quot` 100000000 + day = ((abs i) `rem` 100000000) `quot` 1000000 + hour = ((abs i) `rem` 1000000) `quot` 10000 + minute = ((abs i) `rem` 10000) `quot` 100 + second = ((abs i) `rem` 100) + in (year1, month, day, hour, minute, second) + +datePartsToInt64 :: + (Integral a1, Integral a2, Integral a3, Integral a4, Integral a5, Integral a6) + => (a1, a2, a3, a4, a5, a6) -> Int64 +datePartsToInt64 (year, month, day, hour, minute, second) = + let + yearm :: Int64 + yearm = 10000000000 + sign :: Int64 + sign = if year < 0 then -1 else 1 + in yearm * fromIntegral year + + sign * 100000000 * fromIntegral month + + sign * 1000000 * fromIntegral day + + sign * 10000 * fromIntegral hour + + sign * 100 * fromIntegral minute + + sign * fromIntegral second + + +calTimeToInt64 :: CalendarTime -> Int64 +calTimeToInt64 ct = + datePartsToInt64 + ( ctYear ct, fromEnum (ctMonth ct) + 1, ctDay ct + , ctHour ct, ctMin ct, ctSec ct) + +utcTimeToInt64 utc = + let + (LocalTime ltday time) = utcToLocalTime (hoursToTimeZone 0) utc + (TimeOfDay hour minute second) = time + (year, month, day) = toGregorian ltday + in datePartsToInt64 (year, month, day, hour, minute, round second) + + +int64ToCalTime :: Int64 -> CalendarTime +int64ToCalTime i = + let (year, month, day, hour, minute, second) = int64ToDateParts i + in mkCalTime year month day hour minute second + +int64ToUTCTime :: Int64 -> UTCTime +int64ToUTCTime i = + let (year, month, day, hour, minute, second) = int64ToDateParts i + in mkUTCTime year month day hour minute second + + +zeroPad n i = + if i < 0 + then "-" ++ (zeroPad n (abs i)) + else take (n - length (show i)) (repeat '0') ++ show i + +substr i n s = take n (drop (i-1) s) + +wordsBy :: (Char -> Bool) -> String -> [String] +wordsBy pred s = skipNonMatch pred s + +{- +2 states: + - skipNonMatch is for when we are looking for the start of our next word + - scanWord is for when we are currently scanning a word +-} + +skipNonMatch :: (Char -> Bool) -> String -> [String] +skipNonMatch pred "" = [] +skipNonMatch pred (c:cs) + | pred c = scanWord pred cs [c] + | otherwise = skipNonMatch pred cs + +scanWord pred "" acc = [reverse acc] +scanWord pred (c:cs) acc + | pred c = scanWord pred cs (c:acc) + | otherwise = [reverse acc] ++ skipNonMatch pred cs + + +positions :: Eq a => [a] -> [a] -> [Int] +positions [] _ = [] +positions s ins = map fst (filter (isPrefixOf s . snd) (zip [1..] (tails ins))) + +{- + 1234567890123456789012345 +"2006-11-24 07:51:49.228+00" +"2006-11-24 07:51:49.228" +"2006-11-24 07:51:49.228 BC" +"2006-11-24 07:51:49+00 BC" + +FIXME use TZ to specify timezone? +Not necessary, PostgreSQL always seems to output ++00 for timezone. It's already adjusted the time, +I think. Need to test this with different server timezones, though. +-} +pgDatetimetoUTCTime :: String -> UTCTime +pgDatetimetoUTCTime s = + let (year, month, day, hour, minute, second, tz) = pgDatetimeToParts s + in mkUTCTime year month day hour minute second + +isoDatetimeToUTCTime s = pgDatetimetoUTCTime s + +pgDatetimetoCalTime :: String -> CalendarTime +pgDatetimetoCalTime s = + let (year, month, day, hour, minute, second, tz) = pgDatetimeToParts s + in mkCalTime year month day hour minute (round second) + +{- +isInfixOf is defined in the Data.List that comes with ghc-6.6, +but it is not in the libs that come with ghc-6.4.1. +-} + +myIsInfixOf srch list = or (map (isPrefixOf srch) (tails list)) + + +-- Parses ISO format datetimes, and also the variation that PostgreSQL uses. + +pgDatetimeToParts :: String -> (Int, Int, Int, Int, Int, Double, Int) +pgDatetimeToParts s = + let + pred c = isAlphaNum c || c == '.' + ws = wordsBy pred s + parts :: [Int]; parts = map read (take 5 ws) + secs :: Double; secs = read (ws!!5) + hasTZ = myIsInfixOf "+" s + tz :: Int; tz = if hasTZ then read (ws !! 6) else 0 + isBC = myIsInfixOf "BC" s + -- It seems only PostgreSQL uses the AD/BC suffix. + -- If BC is present then we need to do something odd with the year. + year :: Int; year = if isBC then (- ((parts !! 0) - 1)) else parts !! 0 + in (year, (parts !! 1), (parts !! 2) + , (parts !! 3), (parts !! 4), secs, tz) + + +utcTimeToIsoString :: (Show a, Integral a, Integral b) => + UTCTime -> String -> (a -> a) -> (b -> String) -> String +utcTimeToIsoString utc dtSep adjYear mkSuffix = + let + (LocalTime ltday time) = utcToLocalTime (hoursToTimeZone 0) utc + (TimeOfDay hour minute second) = time + (year1, month, day) = toGregorian ltday + suffix = mkSuffix (fromIntegral year1) + year = adjYear (fromIntegral year1) + s1 :: Double; s1 = realToFrac second + secs :: String; secs = printf "%09.6f" s1 + in zeroPad 4 year + ++ "-" ++ zeroPad 2 month + ++ "-" ++ zeroPad 2 day + ++ dtSep ++ zeroPad 2 hour + ++ ":" ++ zeroPad 2 minute + ++ ":" ++ secs + ++ "+00" ++ suffix + +utcTimeToPGDatetime :: UTCTime -> String +utcTimeToPGDatetime utc = utcTimeToIsoString utc "T" adjYear mkSuffix + where + mkSuffix year1 = if year1 < 1 then " BC" else " AD" + adjYear year1 = if year1 < 1 then abs(year1 - 1) else year1 + +utcTimeToIsoDatetime :: UTCTime -> String +utcTimeToIsoDatetime utc = utcTimeToIsoString utc "T" id (const "Z") + +utcTimeToOdbcDatetime :: UTCTime -> String +utcTimeToOdbcDatetime utc = utcTimeToIsoString utc " " id (const "") + + +-- Assumes CalendarTime is also UTC i.e. ignores ctTZ component. + +calTimeToPGDatetime :: CalendarTime -> String +calTimeToPGDatetime ct = + let + (year1, month, day, hour, minute, second, pico, tzsecs) = + ( ctYear ct, fromEnum (ctMonth ct) + 1, ctDay ct + , ctHour ct, ctMin ct, ctSec ct, ctPicosec ct, ctTZ ct) + suffix = if year1 < 1 then " BC" else " AD" + year = if year1 < 1 then abs(year1 - 1) else year1 + s1 :: Double; s1 = realToFrac second + ((fromIntegral pico) / (10.0 ^ 12) ) + secs :: String; secs = printf "%09.6f" s1 + in zeroPad 4 year + ++ "-" ++ zeroPad 2 month + ++ "-" ++ zeroPad 2 day + ++ " " ++ zeroPad 2 hour + ++ ":" ++ zeroPad 2 minute + ++ ":" ++ secs + ++ "+00" ++ suffix + + +printArrayContents :: Int -> Ptr Word8 -> IO () +printArrayContents sz ptr = do + putStrLn ("printArrayContents: sz = " ++ show sz) + l <- peekArray sz ptr + let + toHex :: Word8 -> String; + toHex i = (if i < 16 then "0" else "") ++ showHex i "" + putStrLn (concat (intersperse " " (map toHex l))) + let + toChar :: Word8 -> String + toChar i = if 31 < i && i < 127 then [chr (fromIntegral i)] else " " + putStrLn (concat (intersperse " " (map toChar l)))
+ Foreign/C/Test/UTF8.hs view
@@ -0,0 +1,138 @@+ +-- | +-- Module : Foreign.C.Test.UTF8 +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable +-- +-- UTF8 decoder and encoder tests. + + +module Foreign.C.Test.UTF8 where + +import Prelude hiding (catch) +import Control.Exception.Extensible +import Data.Char +import Foreign.C.String +import Foreign.C.UTF8 +import Foreign.Marshal.Array +import Foreign.Ptr +import Test.MiniUnit +import qualified Test.QuickCheck as QC +import Data.Word (Word8) + + +runTest :: a -> [String] -> IO () +runTest _ args = runTestTT "UTF8" mkTestList >> return () + +--mkTestList :: Test +--mkTestList = TestList (map TestCase testlist) +mkTestList = testlist + +testlist :: [IO ()] +testlist = + [ testUTF8RoundTrip + , testUTF8StringLenRoundTrip + , quickCheckUTF8RoundTrip + , testFromUTF8Failure5Bytes + , testFromUTF8Failure6Bytes + -- , testLargeFromUTF8 + -- , testLargeFromUTF8Len + ] + + +instance QC.Arbitrary Char where + arbitrary = QC.choose (chr 1, chr 0x10FFFF) + coarbitrary = undefined + +prop_roundtrip s = s == fromUTF8 (toUTF8 s) +quickCheckUTF8RoundTrip = QC.test prop_roundtrip + +testUTF8RoundTrip = do + utf8RoundTrip "1ByteLow" 0x000001 [0x01] + utf8RoundTrip "1ByteHigh" 0x00007F [0x7F] + utf8RoundTrip "2BytesLow" 0x000080 [0xC2, 0x80] + utf8RoundTrip "2BytesHigh" 0x0007FF [0xDF, 0xBF] + utf8RoundTrip "3BytesLow" 0x000800 [0xE0, 0xA0, 0x80] + utf8RoundTrip "3BytesHigh" 0x00FFFF [0xEF, 0xBF, 0xBF] + utf8RoundTrip "4BytesLow" 0x010000 [0xF0, 0x90, 0x80, 0x80] + -- chr 0x10FFFF is the largest code-point Haskell currently allows + utf8RoundTrip "4BytesHigh" 0x10FFFF [0xF4, 0x8F, 0xBF, 0xBF] + +utf8RoundTrip :: String -> Int -> [Word8] -> IO () +utf8RoundTrip msg unicode utf8 = do + assertEqual ("testToUTF8-" ++ msg) utf8 (toUTF8 [chr unicode]) + assertEqual ("testFromUTF8-" ++ msg) [chr unicode] (fromUTF8 utf8) + withUTF8String [chr unicode] $ \cstr -> do + w8 <- peekArray0 0 (castPtr cstr) + assertEqual ("testToUTF8Ptr-" ++ msg) utf8 w8 + withCString (map (chr . fromIntegral) utf8) $ \cstr -> do + s <- peekUTF8String cstr + assertEqual ("testFromUTF8Ptr-" ++ msg) [chr unicode] s + +testUTF8StringLenRoundTrip = do + utf8StringLenRoundTrip "1ByteLow" [0x000001, 0x000001] [0x01, 0x01] + utf8StringLenRoundTrip "2BytesLow" [0x000080, 0x00007F] [0xC2, 0x80, 0x7F] + utf8StringLenRoundTrip "3BytesLow" [0x000800, 0x000001] [0xE0, 0xA0, 0x80, 0x01] + utf8StringLenRoundTrip "4BytesLow" [0x010000, 0x00007F] [0xF0, 0x90, 0x80, 0x80, 0x7F] + utf8StringLenRoundTrip "4BytesHigh" [0x10FFFF, 0x00007F] [0xF4, 0x8F, 0xBF, 0xBF, 0x01] + +utf8StringLenRoundTrip :: String -> [Int] -> [Word8] -> IO () +utf8StringLenRoundTrip msg codepoints utf8 = do + let unicode = map chr codepoints + let expect = take (length unicode - 1) unicode + -- convert our unicode code-points (Haskell String) + -- into a UTF8 CStringLen. + -- Pass this back to peekUTF8StringLen to convert back into Haskell String. + -- Chop off the last char - make sure it's only one byte. + withUTF8StringLen unicode $ \(cstr, clen) -> do + assertEqual ("testUTF8StringLenRoundTrip-" ++ msg) (length utf8) clen + s <- peekUTF8StringLen (cstr, clen - 1) + assertEqual ("testUTF8StringLenRoundTrip-" ++ msg) expect s + + + +--testUTF8StringLenRoundTrip = do + +testFromUTF8Failure5Bytes = do + let utf8 = [0xF8, 0x80, 0x80, 0x80, 0x80] + let handler :: ErrorCall -> IO () + handler (ErrorCall msg) = assertEqual "testFromUTF8Failure5Bytes" "fromUTF8: illegal UTF-8 character 248" msg + catch (do + assertEqual "testFromUTF8Failure5Bytes" [chr 0x10FFFF] (fromUTF8 utf8) + assertBool "testFromUTF8Failure5Bytes: no error raised" False + ) handler + +testFromUTF8Failure6Bytes = do + let utf8 = [0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF] + let handler :: ErrorCall -> IO () + handler (ErrorCall msg) = assertEqual "testFromUTF8Failure6Bytes" "fromUTF8: illegal UTF-8 character 253" msg + catch (do + assertEqual "testFromUTF8Failure6Bytes" [chr 0x10FFFF] (fromUTF8 utf8) + assertBool "testFromUTF8Failure6Bytes: no error raised" False + ) handler +{- +testLargeFromUTF8 = do + let sz = 1000000 + withCString (take sz (repeat 'a')) $ \cstr -> do + s <- peekUTF8String cstr + assertEqual "testLargeFromUTF8" sz (length s) + s <- peekUTF8StringB cstr + assertEqual "testLargeFromUTF8B" sz (length s) + s <- peekUTF8StringLen (cstr, sz) + assertEqual "testLargeFromUTF8Len" sz (length s) + s <- peekUTF8StringLenB (cstr, sz) + assertEqual "testLargeFromUTF8LenB" sz (length s) +-} + +{- +testLargeFromUTF8Len = do + let sz = 1000000 + withCStringLen (take sz (repeat 'a')) $ \(cstr, clen) -> do + putStrLn "testLargeFromUTF8Len: call peekUTF8StringLen" + s <- peekUTF8StringLen (cstr, clen) + putStrLn "testLargeFromUTF8Len: assert length" + assertEqual "testLargeFromUTF8Len" sz (length s) +-}
+ Foreign/C/UTF8.hs view
@@ -0,0 +1,313 @@+ +{-# LANGUAGE CPP #-} + +-- | +-- Module : Foreign.C.UTF8 +-- Copyright : (c) 2004 John Meacham, Alistair Bayley +-- License : BSD-style +-- Maintainer : alistair@abayley.org +-- Stability : experimental +-- Portability : portable +-- +-- Marshall Haskell Strings to and from UTF8-encoded CStrings. +-- This module's code is inspired by John Meacham's UTF8 en- & de-coders, +-- and also those found in the HXT library (module Text.XML.HXT.DOM.Unicode). +-- +-- Note that the -Len functions all return the length in bytes, +-- not Chars (this is more useful, as you are most likely to want +-- to pass the length to an FFI function, which is most likely +-- expecting the length in bytes). If you want the length in Chars, +-- well, you have the original String, so... + + +-- This module has been reasonably optimised. You can check GHC's +-- simplifier output (for unboxing, mainly) with this: +-- ghc -O2 -c UTF8.hs -ddump-simpl > simpl.txt + +module Foreign.C.UTF8 + ( peekUTF8String, peekUTF8StringLen + , newUTF8String, withUTF8String, withUTF8StringLen + , toUTF8String, fromUTF8String + , lengthUTF8, fromUTF8, toUTF8 + ) where + +import Control.Monad (when, liftM) +import Data.Bits +import Data.Char +import Data.Word (Word8) +import Foreign.C.Types +import Foreign.C.String +import Foreign.Ptr +import Foreign.Marshal.Array +import Foreign.Storable + +#ifdef __GLASGOW_HASKELL__ +import GHC.Base (unsafeChr) +#else +unsafeChr :: Int -> Char +unsafeChr i = chr i +#endif + + +nullCChar :: CChar +nullCChar = 0 + +nullByte :: Word8 +nullByte = 0 + +-- | Analogous to peekCString. Converts UTF8 CString to String. +peekUTF8String :: CString -> IO String +peekUTF8String cs = fromUTF8Ptr0 (castPtr cs) +--peekUTF8String cs = peekArray0 nullByte (castPtr cs) >>= return . fromUTF8 + +-- | Analogous to peekCStringLen. Converts UTF8 CString to String. +-- The resulting String will end either when @len@ bytes +-- have been converted, or when a NULL is found. +peekUTF8StringLen :: CStringLen -> IO String +peekUTF8StringLen (cs, len) = fromUTF8Ptr (len-1) (castPtr cs) "" +--peekUTF8StringLen (cs, len) = peekArray len (castPtr cs) >>= return . fromUTF8 + +-- | Analogous to newCString. Creates UTF8 encoded CString. +newUTF8String :: String -> IO CString +newUTF8String hs = do + p <- newArray0 nullByte (toUTF8 hs) + return (castPtr p) + +-- | Analogous to newCStringLen. +-- The length returned is in bytes (encoding units), not chars. +newUTF8StringLen :: String -> IO CStringLen +newUTF8StringLen hs = do + let utf8 = toUTF8 hs + p <- newArray0 nullByte utf8 + return (castPtr p, length utf8) + +-- | Analogous to withCString. Creates UTF8 encoded CString. +withUTF8String :: String -> (CString -> IO a) -> IO a +withUTF8String s action = + withUTF8StringLen s (\(cstr, _) -> action cstr) + +-- | Analogous to withCStringLen. +-- The length returned is in bytes (encoding units), not chars. +withUTF8StringLen :: String -> (CStringLen -> IO a) -> IO a +withUTF8StringLen s action = do + let utf8 = toUTF8 s + withArray0 nullByte utf8 + (\arr -> action (castPtr arr, length utf8) ) + +-- | Convert a String that was marshalled from a CString without +-- any decoder applied. This might be useful if the client encoding +-- is unknown, and the user code must convert. +-- We assume that the UTF8 CString was marshalled as if Latin-1 +-- i.e. all chars are in the range 0-255. +fromUTF8String :: String -> String +fromUTF8String = fromUTF8 . map charToWord8 + +charToWord8 :: Char -> Word8 +charToWord8 = fromIntegral . fromEnum + +-- | Convert a Haskell String into a UTF8 String, where each UTF8 byte +-- is represented by its Char equivalent i.e. only chars 0-255 are used. +-- The resulting String can be marshalled to CString directly i.e. with +-- a Latin-1 encoding. +toUTF8String :: String -> String +toUTF8String = map word8ToChar . toUTF8 + +word8ToChar :: Word8 -> Char +word8ToChar = unsafeChr . fromIntegral + + +lengthUTF8 :: String -> Int +lengthUTF8 s = length (toUTF8 s) + +{- +The codepoint-to-UTF8 rules: +0x00 - 0x7f: 7 bits: as is +0x80 - 0x07ff: 11 bits + byte 1: 0xC0 OR ((x << 6) AND 0x1F) i.e. 0xC0 + bits 7-11 (bits 12-up are 0) + byte 2: 0x80 OR (x AND 0x3F) i.e. 0x80 + bits 1-6 +0x0800 - 0xFFFF: 16 bits + byte 1: 0xE0 OR ((x << 12) AND 0x0F) i.e. 0xE0 + bits 13-16 + byte 2: 0x80 OR ((x << 6) AND 0x3F) i.e. 0x80 + bits 7-12 + byte 3: 0x80 OR (x AND 0x3F) i.e. 0x80 + bits 1-6 +0x00010000 - 0x001FFFFF: 21 bits + byte 1: 0xF0 OR ((x << 18) AND 0x07) i.e. 0xF0 + bits 19-21 + byte 2: 0x80 OR ((x << 12) AND 0x3F) i.e. 0x80 + bits 13-18 + byte 3: 0x80 OR ((x << 6) AND 0x3F) i.e. 0x80 + bits 7-12 + byte 4: 0x80 OR (x AND 0x3F) i.e. 0x80 + bits 1-6 +0x00200000 - 0x03FFFFFF: 26 bits + byte 1: 0xF8 OR ((x << 24) AND 0x03) i.e. 0xF8 + bits 25-26 + byte 2: 0x80 OR ((x << 18) AND 0x3F) i.e. 0x80 + bits 19-24 + byte 3: 0x80 OR ((x << 12) AND 0x3F) i.e. 0x80 + bits 13-18 + byte 4: 0x80 OR ((x << 6) AND 0x3F) i.e. 0x80 + bits 7-12 + byte 5: 0x80 OR (x AND 0x3F) i.e. 0x80 + bits 1-6 +0x04000000 - 0x7FFFFFFF: 31 bits + byte 1: 0xFC OR ((x << 30) AND 0x01) i.e. 0xFC + bit 31 + byte 2: 0x80 OR ((x << 24) AND 0x3F) i.e. 0x80 + bits 25-30 + byte 3: 0x80 OR ((x << 18) AND 0x3F) i.e. 0x80 + bits 19-24 + byte 4: 0x80 OR ((x << 12) AND 0x3F) i.e. 0x80 + bits 13-18 + byte 5: 0x80 OR ((x << 6) AND 0x3F) i.e. 0x80 + bits 7-12 + byte 6: 0x80 OR (x AND 0x3F) i.e. 0x80 + bits 1-6 +-} + +-- | Convert Unicode characters to UTF-8. +toUTF8 :: String -> [Word8] +toUTF8 [] = [] +toUTF8 (x:xs) = toUTF8' (ord x) where + toUTF8' x + | x <= 0x0000007F = fromIntegral x : more + | x <= 0x000007FF + = w8 0xC0 6 : w8 0x80 0 : more + | x <= 0x0000FFFF + = w8 0xE0 12 : w8 0x80 6 : w8 0x80 0 : more + -- If we want to encode chars > 1114111 then this test should be + -- x <= 0x001FFFFF + -- because that's the upper limit of the 4-byte encoding + -- (and the 5- and 6-byte cases below might also be enabled). + | x <= 0x0010FFFF + = w8 0xF0 18 : w8 0x80 12 : w8 0x80 6 : w8 0x80 0 : more + | otherwise = error ("toUTF8: codepoint " ++ show x + ++ " is greater than the largest allowed (decimal 1114111, hex 0x10FFFF).") + {- + -- Potentially useful code, if Haskell ever supports codepoints > 0x0010FFFF. + -- There are no tests for this, because we can't create Strings containing + -- chars > 0x0010FFFF. + | x <= 0x03FFFFFF + = w8 0xF8 24 : w8 0x80 18 : w8 0x80 12 : w8 0x80 6 : w8 0x80 0 : more + | x <= 0x7FFFFFFF + = w8 0xFC 30 : w8 0x80 24 : w8 0x80 18 : w8 0x80 12 : w8 0x80 6 : w8 0x80 0 : more + | otherwise = error ("toUTF8: codepoint " ++ show x ++ " is greater " + ++ "then the largest that can be represented by UTF8 encoding" + ++ "(decimal 2147483647, hex 0x7FFFFFFF).") + -} + where + more = toUTF8 xs + w8 :: Word8 -> Int -> Word8 + w8 base rshift = base .|. (fromIntegral (shiftR x rshift) .&. mask) + where + mask + | base == 0x80 = 0x3F + | base == 0xC0 = 0x1F + | base == 0xE0 = 0x0F + | base == 0xF0 = 0x07 + | base == 0xF8 = 0x03 + | base == 0xFC = 0x01 + +{- +And the rules for UTF8-to-codepoint: +examine first byte: +0x00-0x7F: 1 byte: as-is +0x80-0xBF: error (surrogate) +0xC0-0xDF: 2 bytes: b1 AND 0x1F + remaining +0xE0-0xEF: 3 bytes: b1 AND 0x0F + remaining +0xF0-0xF7: 4 bytes: b1 AND 0x07 + remaining +0xF8-0xFB: 5 bytes: b1 AND 0x03 + remaining +0xFC-0xFD: 6 bytes: b1 AND 0x01 + remaining +0xFE-0xFF: error + (byte-order-mark indicators: UTF8 - EFBBBF, UTF16 - FEFF or FFFE) +remaining = lower 6 bits of each byte, concatenated +-} + +-- | Convert UTF-8 to Unicode. +fromUTF8 :: [Word8] -> String +fromUTF8 [] = "" +fromUTF8 (x:xs) + | x <= 0x7F = remaining 0 (fromIntegral x) xs + | x <= 0xBF = err x + | x <= 0xDF = remaining 1 (bAND x 0x1F) xs + | x <= 0xEF = remaining 2 (bAND x 0x0F) xs + | x <= 0xF7 = remaining 3 (bAND x 0x07) xs + | otherwise = err x + {- + -- Again, only works for chars > 0x0010FFFF, which we can't test. + | x <= 0xFB = remaining 4 (bAND x 0x03) xs + | x <= 0xFD = remaining 5 (bAND x 0x01) xs + | otherwise = err x + -} + where + err x = error ("fromUTF8: illegal UTF-8 character " ++ show x) + bAND :: Word8 -> Word8 -> Int + bAND x m = fromIntegral (x .&. m) + remaining :: Int -> Int -> [Word8] -> String + remaining 0 x xs = chr x : fromUTF8 xs + remaining n x [] = error "fromUTF8: incomplete UTF8 sequence" + remaining n x (b:xs) + | b == 0 = err x + | otherwise = remaining (n-1) ((shiftL x 6) .|. (bAND b 0x3F)) xs + +{- +This version of fromUTF8Ptr starts at the end of the array and works backwards. +This will allow us to create the result String with constant space +usage. Contrast this with creating the String by processing the array +from start to end: in this case we would probably use an accumulating +parameter, and reverse the list when we reach the end of the array. +This isn't so bad, if we expect reverse to work in constant space +(more or less). +-} + +-- | Convert UTF-8 to Unicode, from a null-terminated C array of bytes. +-- This function is useful, in addition to 'fromUTF8' above, +-- because it doesn't create an intermediate @[Word8]@ list. +fromUTF8Ptr0 :: Ptr Word8 -> IO String +fromUTF8Ptr0 p = do + len <- lengthArray0 nullByte p + fromUTF8Ptr (len-1) p "" + +-- | The bytes parameter should be len-1 +-- i.e. if the CString has length 2, then you should pass bytes=1. +-- That's because we add bytes to the Ptr p to get the offset +-- for each byte; byte 1 is at p+0, byte 2 is at p+1, etc. +fromUTF8Ptr :: Int -> Ptr Word8 -> String -> IO String +fromUTF8Ptr bytes p acc + | bytes `seq` p `seq` acc `seq` False = undefined + | bytes < 0 = do + if null acc then return acc + else -- BOM = chr 65279 ( EF BB BF ) + if head acc /= chr 65279 then return acc + else return (tail acc) + | otherwise = do + x <- liftM fromIntegral (peekElemOff p bytes) + case () of + _ | x == 0 -> error ("fromUTF8Ptr: zero byte found in string as position " ++ show bytes) + | x <= 0x7F -> fromUTF8Ptr (bytes-1) p (unsafeChr x:acc) + | x <= 0xBF && bytes == 0 -> error "fromUTF8Ptr: surrogate at start of string" + | x <= 0xBF -> fromUTF8Ptr (bytes-1) p acc + | otherwise -> do + c <- readUTF8Char x bytes p + fromUTF8Ptr (bytes-1) p (c:acc) + + +readUTF8Char :: Int -> Int -> Ptr Word8 -> IO Char +readUTF8Char x offset p + | x `seq` offset `seq` p `seq` False = undefined + | otherwise = + case () of + _ | x == 0 -> err x + | x <= 0x7F -> return (unsafeChr x) + | x <= 0xBF -> err x + | x <= 0xDF -> do + x1 <- liftM fromIntegral (peekElemOff p (offset + 1)) + return (unsafeChr ( + ((x - 0xC0) * 64) + + (x1 - 0x80) + )) + | x <= 0xEF -> do + x1 <- liftM fromIntegral (peekElemOff p (offset + 1)) + x2 <- liftM fromIntegral (peekElemOff p (offset + 2)) + return (unsafeChr ( + ((x - 0xE0) * 4096) + + ((x1 - 0x80) * 64) + + (x2 - 0x80) + )) + | x <= 0xF7 -> do + x1 <- liftM fromIntegral (peekElemOff p (offset + 1)) + x2 <- liftM fromIntegral (peekElemOff p (offset + 2)) + x3 <- liftM fromIntegral (peekElemOff p (offset + 3)) + return (unsafeChr ( + ((x - 0xF0) * 262144) + + ((x1 - 0x80) * 4096) + + ((x2 - 0x80) * 64) + + (x3 - 0x80) + )) + | otherwise -> err x + where + err x = error ("readUTF8Char: illegal UTF-8 character " ++ show x)
+ LICENSE view
@@ -0,0 +1,32 @@+The Takusen License + +Copyright 2013, Pavel Ryzhov +Copyright 2004, Oleg Kiselyov, Alistair Bayley. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + * Neither the name of the copyright holder(s) nor the names of + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ Main.hs view
@@ -0,0 +1,69 @@+ +-- | +-- Module : Main +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : non-portable +-- +-- Simple driver module, mainly for testing. +-- Imports test modules and runs test suites. +-- +-- This project is now hosted at haskell.org: +-- +-- @darcs get <http://darcs.haskell.org/takusen>@ +-- +-- Invoke main like this (assuming the compiled executable is called @takusen@): +-- +-- > takusen stub noperf +-- > takusen sqlite noperf "" "" dbname +-- > takusen oracle noperf "" "" dbname -- no username, so os-authenticated +-- > takusen mssql noperf user paswd dbname + +module Main (main) where + + +-- import Database.Sqlite.Test.Enumerator as Sqlite +import Database.Oracle.Test.Enumerator as Oracle +--import Database.Test.MultiConnect as Multi +-- import Database.ODBC.Test.Enumerator as ODBC +import Database.Stub.Test.Enumerator as Stub +--import Database.MSSqlServer.Test.Enumerator as MSSql +--import Database.PostgreSQL.Test.Enumerator as PGSql +import System.Environment (getArgs) +import Database.Test.Performance as Perf +import Database.Test.Util as Util +import Foreign.C.Test.UTF8 as UTF8 + + +main :: IO () +main = do + args <- getArgs + if (length args < 2) + then showUsage + else do + let (impl:perf:as) = args + doTests impl perf as + +showUsage = do + putStrLn "usage: takusen backend {no}perf user pswd database" + +doTests impl perf args = do + let runPerf = if perf == "perf" then Perf.RunTests else Perf.Don'tRunTests + case lookup impl backendTests of + Nothing -> putStrLn $ "No backend for " ++ impl ++ "." + Just test -> test runPerf args + +backendTests :: [(String, Perf.ShouldRunTests -> [String] -> IO ())] +backendTests = + [ ("sqlite", Sqlite.runTest) + , ("pgsql", PGSql.runTest) + , ("odbc", ODBC.runTest) + --, ("mssql", MSSql.runTest) + , ("oracle", Oracle.runTest) + --, ("multi", Multi.runTest) + , ("stub", Stub.runTest) + , ("utf8", UTF8.runTest) + , ("util", Util.runTest) + ]
+ Setup.hs view
@@ -0,0 +1,137 @@+#!/usr/bin/env runhaskell + +-- setup configure -fodbc -foracle -fpostgres -fsqlite + +import Prelude hiding (catch) +import Distribution.PackageDescription + ( PackageDescription(..), Library(..), BuildInfo(..), HookedBuildInfo + , emptyHookedBuildInfo, emptyBuildInfo + ) +import Distribution.PackageDescription.Parse ( writeHookedBuildInfo ) +import Distribution.Package (Dependency(..), PackageName(..)) +import Distribution.Simple.Setup ( ConfigFlags(..), BuildFlags(.. ), fromFlag) +import Distribution.Simple + ( defaultMainWithHooks, autoconfUserHooks, UserHooks(..), Args ) +import Distribution.Simple.Program (findProgramOnPath, simpleProgram, Program(..)) +import Distribution.Simple.LocalBuildInfo (LocalBuildInfo) +import Distribution.Simple.Utils (warn, info, rawSystemStdout) +import Distribution.Verbosity (Verbosity) + +import qualified System.Info (os) +import System.Directory (canonicalizePath, removeFile) +import System.Environment (getEnv) +import System.FilePath (combine, dropFileName, FilePath, pathSeparators) +import Control.Monad(liftM) +import Control.Exception (SomeException, try, catch) +import Data.List (isInfixOf) +import Data.Maybe (fromJust) +import Data.Monoid (mconcat) + +{- +One install script to rule them all, and in the darkness build them... + +See this page for useful notes on tagging and releasing: + http://www.haskell.org/haskellwiki/How_to_write_a_Haskell_program + +To-dos for Takusen: + - Oracle resource leak: Ref Cursors (StmtHandles) not freed + - better result-set <-> iteratee validation. Check column types? + - use hsc2hs to create #define constants from header files, + rather than hard-code them. + - Blob support (and clob?). + + - Unwritten tests: + * incorrect fold function (doesn't match result-set) + +-} + +emptyCatchHandler :: SomeException -> IO () +emptyCatchHandler _ = return () + +main = defaultMainWithHooks autoconfUserHooks + { preConf=preConf, postConf=postConf + , hookedPrograms = [sqlplusProgram] + } + where + preConf :: Args -> ConfigFlags -> IO HookedBuildInfo + preConf args flags = do + catch (removeFile "Takusen.buildinfo") emptyCatchHandler + return emptyHookedBuildInfo + postConf :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO () + postConf args flags pkgdesc localbuildinfo = do + let verbose = fromFlag (configVerbosity flags) + let lbi = libBuildInfo (fromJust (library pkgdesc)) + let buildtools = buildTools lbi + oraBI <- configOracle verbose buildtools + let bi = mconcat [oraBI, lbi] + writeHookedBuildInfo "Takusen.buildinfo" (Just bi, []) + +sqlplusProgram = simpleProgram "sqlplus" + +isWindows = System.Info.os == "mingw32" || System.Info.os == "windows" + +-- ghc-6.6.1 can't cope with a trailing slash or backslash on the end +-- of the include dir path, so we strip it off. +-- Not sure why this is; there might be something else causing it to fail +-- which has gone unnoticed. +stripTrailingSep :: String -> String +stripTrailingSep p + = reverse + . (\s -> if [head s] `isInfixOf` pathSeparators then drop 1 s else s) + . reverse + $ p + +makeConfig path libDir includeDir = do + libDirs <- canonicalizePath (combine path libDir) + includeDirs <- canonicalizePath (combine path includeDir) + return + (emptyBuildInfo + { extraLibDirs = [stripTrailingSep libDirs], includeDirs = [stripTrailingSep includeDirs] }) + +nothingForSomeException :: SomeException -> IO (Maybe String) +nothingForSomeException _ = return Nothing + +maybeGetEnv :: String -> IO (Maybe String) +maybeGetEnv env = catch (liftM Just (getEnv env)) nothingForSomeException + +-- Check that the program is in the buildtools. +-- If it is, then run the action (which should return BuildInfo). +-- If not, return emptyBuildInfo. +-- Cabal populates the buildtools list depending on which flags +-- have been passed to "setup configure". +guardProg :: Program -> [Dependency] -> IO BuildInfo -> IO BuildInfo +guardProg prog tools action = if prog `isElem` tools then action else return emptyBuildInfo + where + isElem program = any (match program) + match program (Dependency (PackageName tool) _) = programName program == tool + +-- Run the first action to give a Maybe FilePath. +-- If this is Nothing then emit a warning about library not found. +-- Otherwise, run the second action over the FilePath. +guardPath :: IO (Maybe FilePath) -> String -> Verbosity -> (FilePath -> IO BuildInfo) -> IO BuildInfo +guardPath pathAction libName verbose resAction = do + mb <- pathAction + case mb of + Nothing -> warn verbose ("No " ++libName++ " library found") >> return emptyBuildInfo + Just path -> info verbose ("Using " ++libName++ ": " ++ path) >> resAction path + +-- From the Oracle 10g manual: +-- +-- Appendix D - Getting Started with OCI for Windows: +-- Compiling OCI Applications for Windows: +-- http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14250/ociadwin.htm#i634569 +-- Header files are in: ORACLE_BASE\ORACLE_HOME\oci\include +-- DLLs are in: ORACLE_BASE\ORACLE_HOME\bin +-- +-- For Unix: +-- Appendix B - OCI Demonstration Programs: +-- http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14250/ociabdem.htm#i459676 +-- Header files are in: $ORACLE_HOME/rdbms/public +-- Header files are in: $ORACLE_HOME/lib + +configOracle verbose buildtools = + guardProg sqlplusProgram buildtools $ + guardPath (maybeGetEnv "ORACLE_HOME") "Oracle" verbose $ \path -> do + let (libDir, incDir) = + if isWindows then ("bin", "oci/include") else ("", "sdk/include") -- ("lib", "rdbms/public") + makeConfig path libDir incDir
+ Test/Main.hs view
@@ -0,0 +1,7 @@+ +module Main where + +import Test.MiniUnitTest + +main :: IO () +main = tests
+ Test/MiniUnit.hs view
@@ -0,0 +1,178 @@+ +-- | +-- Module : Test.MiniUnit +-- Copyright : (c) 2004 Oleg Kiselyov, Alistair Bayley +-- License : BSD-style +-- Maintainer : oleg@pobox.com, alistair@abayley.org +-- Stability : experimental +-- Portability : portable +-- +-- This is just a simple one-module unit test framework, with the same +-- API as "Test.HUnit" (albeit with a lot of stuff missing). +-- We use it because it works in 'Control.Exception.MonadIO.CaughtMonadIO' +-- instead of IO +-- (and also because I couldn't convert "Test.HUnit" +-- to use 'Control.Exception.MonadIO.CaughtMonadIO'). + +{-# LANGUAGE CPP #-} + +module Test.MiniUnit + ( + -- ** Primary API + runTestTT, assertFailure, assertBool, assertString, assertEqual + -- ** Exposed for self-testing only; see "Test.MiniUnitTest" + , TestResult(..), throwUserError, runSingleTest, reportResults + ) +where + +import Control.Exception.MonadIO +import Control.Exception +import Control.Monad +import Control.Monad.Trans (liftIO) +import System.IO.Error (ioeGetErrorString) +import System.IO +import Data.List +import Data.IORef + + +data TestResult = TestSuccess | TestFailure String | TestException String + deriving (Show, Eq) + +-- We'll use HUnit's trick of throwing an IOError when an assertion fails. +-- This will terminate the test case, obviously, but we catch the exception +-- and record that it haa failed so that we can continue with other +-- test cases. + +-- Unlike HUnit, we catch all exceptions; any that are not thrown by +-- failed assertions are recorded as test errors (as opposed to test failures), +-- and the testing continues... + +-- When an assertion fails, we throw an IOException with a special +-- text prefix, which the exception handler will detect. +assertFailure :: CaughtMonadIO m => String -> m () +assertFailure msg = throwUserError (exceptionPrefix ++ msg) + +exceptionPrefix = "MiniUnit:" +hugsPrefix = "IO Error: User error\nReason: " +nhc98Prefix = "I/O error (user-defined), call to function `userError':\n " +ghcPrefix = "" -- We don't use this; it's just documentation... + +dropPrefix p s = if isPrefixOf p s then drop (length p) s else s +trimCompilerPrefixes = dropPrefix hugsPrefix . dropPrefix nhc98Prefix + +throwUserError :: CaughtMonadIO m => String -> m () +throwUserError msg = liftIO (throwIO (userError msg)) + +runSingleTest :: CaughtMonadIO m => m () -> m TestResult +runSingleTest action = do + let + iohandler :: CaughtMonadIO m =>IOException -> m TestResult + iohandler e = + let errText = trimCompilerPrefixes (ioeGetErrorString e) in + if isPrefixOf exceptionPrefix errText + then return (TestFailure (dropPrefix exceptionPrefix errText)) + else return (TestException (show e)) + errhandler :: CaughtMonadIO m => SomeException -> m TestResult + errhandler e = return (TestException (show e)) + (action >> return TestSuccess) + `gcatch` iohandler + `gcatch` errhandler + +-- Predicates for list filtering +isSuccess TestSuccess = True +isSuccess _ = False +isFailure (TestFailure _) = True +isFailure _ = False +isError (TestException _) = True +isError _ = False + +-- Make function composition look more like Unix pipes. +-- This first definition requires a Point-Free Style. +-- I prefer the PFS, as you can use it in (for example) predicate +-- functions passed as arguments (see filter example below). +infixl 9 |> +(|>) = flip (.) + +-- This second definition affords a more pointed style... +-- We can use this operator to inject an argument into a pipe +-- defined using |>; it has lower precedence, so will bind last. +-- e.g. ... = mylist |>> zip [1..] |> filter (snd |> pred) |> map show |> concat +infixl 8 |>> +(|>>) = flip ($) + +--reportFilter pred = zip [1..] |> filter (snd |> pred) |> map testReporter |> concat + +testReporter (n, TestSuccess) = "" +testReporter (n, TestException s) = "Test " ++ show n ++ " failed with exception:\n" ++ s ++ "\n" +testReporter (n, TestFailure s) = "Test " ++ show n ++ " failed with message:\n" ++ s ++ "\n" + +reportResults list = + let + s = list |>> filter isSuccess |> length + e = list |>> filter isError |> length + f = list |>> filter isFailure |> length + in "Test cases: " ++ show (length list) + ++ " Failures: " ++ show f + ++ " Errors: " ++ show e + -- ++ reportFilter isFailure list + -- ++ reportFilter isError list + +-- 2 defns for same result; which is better? +--contains pred = filter pred |> null |> not +contains p l = maybe False (const True) (find p l) + +-- | Return 0 if everything is rosy, +-- 1 if there were assertion failures (but no exceptions), +-- 2 if there were any exceptions. +-- You could use this return code as the return code from +-- your program, if you're driving from the command line. +runTestTT :: CaughtMonadIO m => String -> [m ()] -> m Int +runTestTT desc list = do + liftIO (putStrLn "") + when (desc /= "") (liftIO (putStr (desc ++ " - "))) + liftIO (putStrLn ("Test case count: " ++ show (length list))) + r <- mapM (\(n, t) -> liftIO (putStr "." >> hFlush stdout) >> runSingleTestTT n t) (zip [1..] list) + liftIO (putStrLn "") + liftIO (putStrLn (reportResults r)) + if contains isError r + then return 2 + else if contains isFailure r + then return 1 + else return 0 + +-- Could use this instead of runSingleTest - it will output +-- failures and exceptions as they occur, rather than all +-- at the end. +runSingleTestTT :: CaughtMonadIO m => Int -> m () -> m TestResult +runSingleTestTT n test = do + r <- runSingleTest test + case r of + TestSuccess -> return r + TestFailure _ -> liftIO (putStrLn ('\n':(testReporter (n ,r)))) >> return r + TestException _ -> liftIO (putStrLn ('\n':(testReporter (n, r)))) >> return r + +--------------------------------------------- +-- That's the basic framework; now for some sugar... +-- ... stolen straight from Dean Herrington's HUnit code. +-- Shall we steal his infix operators, too? + +assertBool :: CaughtMonadIO m => String -> Bool -> m () +assertBool msg b = unless b (assertFailure msg) + +assertString :: CaughtMonadIO m => String -> m () +assertString s = unless (null s) (assertFailure s) + +assertEqual :: (Eq a, Show a, CaughtMonadIO m) => + String -- ^ message preface + -> a -- ^ expected + -> a -- ^ actual + -> m () +assertEqual preface expected actual = do + let + msg = + (if null preface then "" else preface ++ "\n") + ++ "expect: " ++ show expected ++ "\nactual: " ++ show actual + unless (actual == expected) (assertFailure msg) + + +--p @? msg = assertBool msg p
+ Test/MiniUnitTest.hs view
@@ -0,0 +1,64 @@+ +{-# LANGUAGE NoMonomorphismRestriction #-} + +module Test.MiniUnitTest where + +import Test.MiniUnit +import Data.IORef +import Control.Exception.MonadIO +import Control.Monad.Trans (liftIO) + + +tests = do + print_ "MiniUnit tests..." + test__assertFailure + test__runSingleTestSuccess + test__runSingleTestFailure + test__runSingleTestException + test__reportResults + print_ "Testing runTestTT; ignore following test output." + test__runTestTT + print_ "MiniUnit tests done." + +print_ s = liftIO (putStrLn s) + +test__assertFailure = catch + (assertFailure "test__assertFailure" + >> error "test__assertFailure: failed: exception not thrown.") + (\e -> print_ "test__assertFailure OK") + +reportResult name result = do + case result of + TestSuccess -> print_ (name ++ " OK") + TestFailure _ -> print_ (name ++ " failed") + TestException _ -> print_ (name ++ " exception") + +test__runSingleTestSuccess = + runSingleTest (return ()) + >>= reportResult "test__runSingleTestSuccess" + +test__runSingleTestFailure = + runSingleTest (assertFailure "test__runSingleTestFailure") + >>= reportResult "test__runSingleTestFailure" + +test__runSingleTestException = do + result <- runSingleTest (throwUserError "boo") + case result of + TestSuccess -> print_ "test__runSingleTestException failed" + TestFailure _ -> print_ "test__runSingleTestException failed!" + TestException _ -> print_ "test__runSingleTestException OK" + +test__reportResults = do + results <- mapM runSingleTest + [assertFailure "test__runSingleTest", return (), throwUserError "boo"] + let expect = "Test cases: 3 Failures: 1 Errors: 1" + if reportResults results == expect + then print_ "test__reportResults OK" + else print_ "test__reportResults failed!" + + +test__runTestTT = do + r <- runTestTT "MiniUnitTest" [assertFailure "test__runSingleTest", return (), throwUserError "boo"] + return () + +----
+ takusen-oracle.cabal view
@@ -0,0 +1,108 @@+Name: takusen-oracle +Version: 0.9.0 +License: BSD3 +License-file: LICENSE +Author: Alistair Bayley, Oleg Kiselyov, Pavel Ryzhov +Copyright: 2003-2009, Alistair Bayley, Oleg Kiselyov, 2013, Pavel Ryzhov +Maintainer: paul@paulrz.cz +Stability: experimental +Homepage: https://github.com/paulrzcz/takusen-oracle.git +Package-url: https://github.com/paulrzcz/takusen-oracle.git +Category: Database +Build-type: Custom +Cabal-Version: >= 1.16 +Synopsis: Database library with left-fold interface for Oracle. +Description: + Takusen-Oracle is a Oracle access library. Like HSQL and HDBC, we support + arbitrary SQL statements (currently strings, extensible to anything + that can be converted to a string). + + It is based on original Takusen library. It was just upgraded to support + Oracle 11gR2/12c instant client and GHC 7.4.2 and higher. + +Extra-tmp-files: + Database/Oracle/OCIFunctions_stub.c + Database/Oracle/OCIFunctions_stub.h + +source-repository this + type: git + location: https://github.com/paulrzcz/takusen-oracle.git + tag: 0.9.0 + +Flag buildtests + Description: Build test executables + Default: False + + +Executable takusen_tests + Default-Language: Haskell2010 + If !flag(buildtests) + Buildable: False + else + -- If we want to build test exe, then it needs Takusen installed. + Build-Depends: takusen-oracle + Main-Is: Main.hs + Other-modules: + Database.Enumerator + , Database.InternalEnumerator + , Database.Util + , Database.Test.Enumerator + , Database.Test.Util + , Database.Test.Performance + , Database.Oracle.Enumerator + , Database.Oracle.OCIConstants + , Database.Oracle.OCIFunctions + , Database.Oracle.Test.Enumerator + , Database.Oracle.Test.OCIFunctions + , Control.Exception.MonadIO + , Foreign.C.UTF8 + , Foreign.C.Test.UTF8 + , Test.MiniUnit + Build-Depends: base >= 4.5 && < 5 + , mtl + , time + , old-time + , QuickCheck ==2.* + , random + Extensions: CPP DeriveDataTypeable ScopedTypeVariables + +Executable miniunit_tests + Default-Language: Haskell2010 + If !flag(buildtests) + Buildable: False + Main-Is: Test/Main.hs + Other-modules: + Control.Exception.MonadIO + , Test.MiniUnit + , Test.MiniUnitTest + Build-Depends: base >= 4.5 && < 5 + , mtl + Other-Extensions: CPP DeriveDataTypeable ScopedTypeVariables + +Library + Default-Language: Haskell2010 + Exposed-modules: + Database.Enumerator + , Database.Util + , Control.Exception.MonadIO + , Foreign.C.UTF8 + + Exposed-modules: + Database.Oracle.Enumerator + , Database.Oracle.OCIConstants + , Database.Oracle.OCIFunctions + Build-Tools: sqlplus + If os(windows) + Extra-Libraries: oci + Else + Extra-Libraries: clntsh + + Build-Depends: base + , mtl + , time + , old-time + Other-Extensions: CPP DeriveDataTypeable + Other-modules: + Database.InternalEnumerator + -- Modules in Other-modules are passed to Haddock with --hide=<module-name>. + Ghc-Prof-Options: -prof -auto-all