X-Git-Url: http://gitweb.michael.orlitzky.com/?a=blobdiff_plain;f=src%2FMain.hs;h=d1d1ea81fa43516bd44b01b294326451b9fbafaf;hb=1be0cccde2652e239a8f8782cb128d885ab1e6b4;hp=d153716e3ad575f9368ce2bc779785721986068b;hpb=bc4c3efd191f3cc5b7b9f046775bff706c491a7d;p=mailbox-count.git diff --git a/src/Main.hs b/src/Main.hs index d153716..d1d1ea8 100644 --- a/src/Main.hs +++ b/src/Main.hs @@ -1,17 +1,23 @@ +{-# LANGUAGE DoAndIfThenElse #-} +{-# LANGUAGE NoMonomorphismRestriction #-} module Main 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 ) import Report ( report ) + -- | Construct a connection string (postgres-only, for now) from a -- 'Configuration'. All of these are optional, at least for -- Postgres, and so we want to avoid appending e.g. \"host=\" to the @@ -58,16 +64,22 @@ main = do -- log the errors. let cfg = (def :: Configuration) `merge_optional` opt_config - -- Check the optional config for missing required options. - --when (isNothing (OC.password opt_config)) $ do - -- report_error "No password supplied." - -- exitWith (ExitFailure exit_no_password) + -- If a database name was specified, and that name exists as a file + -- on the system, assume that the user wanted to use SQLite. + handleSql show_sql_error $ do + r <- case (database cfg) of + Nothing -> connectPostgreSQL (connection_string cfg) >>= report cfg - --when (isNothing (OC.username opt_config)) $ do - -- report_error "No username supplied." - --exitWith (ExitFailure exit_no_username) + Just dbname -> do + exists <- doesFileExist dbname + if exists + then connectSqlite3 dbname >>= report cfg + else connectPostgreSQL (connection_string cfg) >>= report cfg - conn <- connectPostgreSQL (connection_string cfg) - r <- report conn (detail cfg) - putStrLn r --- disconnect conn + -- 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)