Skip to content

Commit

Permalink
Add piped mode
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisdone committed May 24, 2021
1 parent 671f190 commit 00e00f5
Showing 1 changed file with 50 additions and 29 deletions.
79 changes: 50 additions & 29 deletions app/Main.hs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ main = do
case args of
[connStr] -> do
conn <- ODBC.connect (T.pack connStr)
repl conn
term<- hIsTerminalDevice stdin
if term
then repl conn
else piped conn
_ -> error "usage: <connection string>"

-- | Accepts a query/command and prints any results.
Expand All @@ -40,32 +43,50 @@ repl c = do
e -> throwIO e))
(\(e :: ODBC.ODBCException) -> putStrLn (displayException e))
repl c

-- | Accepts a single input and prints any results.
piped :: ODBC.Connection -> IO ()
piped c = do
input <- T.hGetContents stdin
hSetBuffering stdout LineBuffering
catch
(catch
(do (_, count) <- ODBC.stream c input output (False, 0 :: Int)
putStrLn ("Rows: " ++ show count))
(\case
UserInterrupt -> pure ()
e -> throwIO e))
(\(e :: ODBC.ODBCException) -> putStrLn (displayException e))
repl c

prompt :: IO (Maybe T.Text)
prompt = do
hSetBuffering stdout NoBuffering
putStr "> "
catch (fmap Just T.getLine) (\(_ :: IOException) -> pure Nothing)

output :: (Show b, Num b) => (a, b) -> [(ODBC.Column, ODBC.Value)] -> IO (ODBC.Step (Bool, b))
output (_printedHeaders, count) rowWithHeaders = do
T.putStrLn
("[row " <> T.pack (show count) <> "]\n" <>
T.unlines
(map
(\(name, value) ->
ODBC.columnName name <> ": " <> T.pack (showColumn value))
rowWithHeaders))
pure (ODBC.Continue (True, count + 1))
where
prompt = do
hSetBuffering stdout NoBuffering
putStr "> "
catch (fmap Just T.getLine) (\(_ :: IOException) -> pure Nothing)
output (_printedHeaders, count) rowWithHeaders = do
T.putStrLn
("[row " <> T.pack (show count) <> "]\n" <>
T.unlines
(map
(\(name, value) ->
ODBC.columnName name <> ": " <> T.pack (showColumn value))
rowWithHeaders))
pure (ODBC.Continue (True, count + 1))
where
showColumn =
\case
ODBC.NullValue -> "NULL"
ODBC.TextValue t -> show t
ODBC.ByteStringValue bs -> show bs
ODBC.BinaryValue bs -> show bs
ODBC.BoolValue b -> show b
ODBC.DoubleValue d -> printf "%f" d
ODBC.FloatValue d -> printf "%f" d
ODBC.IntValue i -> show i
ODBC.DayValue d -> show d
ODBC.ByteValue b -> show b
ODBC.TimeOfDayValue v -> show v
ODBC.LocalTimeValue v -> show v
showColumn =
\case
ODBC.NullValue -> "NULL"
ODBC.TextValue t -> show t
ODBC.ByteStringValue bs -> show bs
ODBC.BinaryValue bs -> show bs
ODBC.BoolValue b -> show b
ODBC.DoubleValue d -> printf "%f" d
ODBC.FloatValue d -> printf "%f" d
ODBC.IntValue i -> show i
ODBC.DayValue d -> show d
ODBC.ByteValue b -> show b
ODBC.TimeOfDayValue v -> show v
ODBC.LocalTimeValue v -> show v

0 comments on commit 00e00f5

Please sign in to comment.