From 1be0cccde2652e239a8f8782cb128d885ab1e6b4 Mon Sep 17 00:00:00 2001 From: Michael Orlitzky Date: Fri, 30 May 2014 14:46:52 -0400 Subject: [PATCH] Handle SQL errors gracefully. --- src/Main.hs | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/src/Main.hs b/src/Main.hs index f00ebb3..d1d1ea8 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -6,11 +6,12 @@ where import Data.Maybe ( fromMaybe ) import Data.Monoid ( (<>) ) import Data.String.Utils ( join ) +import Database.HDBC ( SqlError(..), handleSql ) import Database.HDBC.PostgreSQL ( connectPostgreSQL ) import Database.HDBC.Sqlite3 ( connectSqlite3 ) import System.Console.CmdArgs ( def ) import System.Directory ( doesFileExist ) - +import System.IO ( hPutStrLn, stderr ) import CommandLine ( get_args ) import Configuration ( Configuration(..), merge_optional ) import qualified OptionalConfiguration as OC ( from_rc ) @@ -65,14 +66,20 @@ main = do -- If a database name was specified, and that name exists as a file -- on the system, assume that the user wanted to use SQLite. - r <- case (database cfg) of - Nothing -> connectPostgreSQL (connection_string cfg) >>= report cfg + handleSql show_sql_error $ do + r <- case (database cfg) of + Nothing -> connectPostgreSQL (connection_string cfg) >>= report cfg + + Just dbname -> do + exists <- doesFileExist dbname + if exists + then connectSqlite3 dbname >>= report cfg + else connectPostgreSQL (connection_string cfg) >>= report cfg - Just dbname -> do - exists <- doesFileExist dbname - if exists - then connectSqlite3 dbname >>= report cfg - else connectPostgreSQL (connection_string cfg) >>= report cfg + -- The DB connection is implicitly closed when it gets garbage collected. + putStrLn r - -- The DB connection is implicitly closed when it gets garbage collected. - putStrLn r + where + show_sql_error :: SqlError -> IO () + show_sql_error se = hPutStrLn stderr $ + "SQL Error (" ++ (show $ seNativeError se) ++ "): " ++ (seErrorMsg se) -- 2.43.2