From 00e00f5538b726b2a81b22606faabb77edafb689 Mon Sep 17 00:00:00 2001 From: Chris Done Date: Mon, 24 May 2021 11:55:51 +0100 Subject: [PATCH] Add piped mode --- app/Main.hs | 79 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 50 insertions(+), 29 deletions(-) diff --git a/app/Main.hs b/app/Main.hs index 8888ec5..f95935a 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -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: " -- | Accepts a query/command and prints any results. @@ -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