計算機科学のブログ

実践Haskell データベースの使用 インターフェイス、ユーザー入力、コマンドの追加

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON41(Haskellでのデータベースの使用)、41.9(練習問題)Q41-2の解答を求めてみる。

package.yaml

name:                db-lesson
version:             0.1.0.0
github:              "githubuser/db-lesson"
license:             BSD3
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2022 Author name here"

extra-source-files:
- README.md
- ChangeLog.md

# Metadata used when publishing your package
# synopsis:            Short description of your package
# category:            Web

# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description:         Please see the README on GitHub at <https://github.com/githubuser/db-lesson#readme>

dependencies:
- base >= 4.7 && < 5

library:
  source-dirs: src

executables:
  db-lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - db-lesson
    - time
    - sqlite-simple
    default-extensions:
    - OverloadedStrings

tests:
  db-lesson-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - db-lesson

コード

app/Main.hs

module Main where

-- import Control.Applicative
import Data.Time (Day, UTCTime (utctDay), getCurrentTime)
import Database.SQLite.Simple
  ( Connection,
    FromRow (..),
    Only (Only),
    Query,
    close,
    execute,
    field,
    open,
    query_,
  )
-- import Database.SQLite.Simple.FromRow
import Lib

data Tool = Tool
  { toolId :: Int,
    name :: String,
    description :: String,
    lastReturned :: Day,
    timesBorrowed :: Int
  }

data User = User
  { userId :: Int,
    userName :: String
  }

instance Show User where
  show user =
    mconcat
      [ show $ userId user,
        ".) ",
        userName user
      ]

instance Show Tool where
  show tool =
    mconcat
      [ show $ toolId tool,
        ".) ",
        name tool,
        "\n description: ",
        description tool,
        "\n last returned: ",
        show $ lastReturned tool,
        "\n times borrowed: ",
        show $ timesBorrowed tool,
        "\n"
      ]

instance FromRow Tool where
  fromRow = Tool <$> field <*> field <*> field <*> field <*> field

withConn :: String -> (Connection -> IO ()) -> IO ()
withConn dbName action = do
  conn <- open dbName
  action conn
  close conn

printToolQuery :: Query -> IO ()
printToolQuery q = withConn "tools.db" $ \conn -> do
  resp <- query_ conn q :: IO [Tool]
  mapM_ print resp

printTools :: IO ()
printTools = printToolQuery "SELECT * FROM tools;"

addUser :: String -> IO ()
addUser userName =
  withConn
    "tools.db"
    $ \conn -> do
      execute
        conn
        "INSERT INTO users (username) VALUES (?)"
        $ Only userName
      print "user added"

addTool :: String -> String -> IO ()
addTool toolName toolDescription =
  withConn
    "tools.db"
    $ \conn -> do
      currentDay <- utctDay <$> getCurrentTime
      execute
        conn
        ( mconcat
            [ "INSERT INTO tools ",
              "(name, description, lastReturned, timesBorrowed)",
              "VALUES (?, ?, ?, ?)"
            ]
        )
        ( toolName,
          toolDescription,
          currentDay,
          show 0
        )
      print "tool added"

promptAndAddTool :: IO ()
promptAndAddTool = do
  print "Enter tool name"
  toolName <- getLine
  print "Enter tool description"
  toolDescription <- getLine
  addTool toolName toolDescription

performCommand :: String -> IO ()
performCommand command
  | command == "addtool" = promptAndAddTool >> main
  | command == "tools" = printTools >> main
  | command == "quit" = print "bye!"
  | otherwise = print "Sorry command n9ot found" >> main

main :: IO ()
main = do
  print "Enter a command"
  command <- getLine
  performCommand command

入出力結果(Terminal, Zsh)

% stack build
db-lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
db-lesson> build (lib + exe)
Preprocessing library for db-lesson-0.1.0.0..
Building library for db-lesson-0.1.0.0..
Preprocessing executable 'db-lesson-exe' for db-lesson-0.1.0.0..
Building executable 'db-lesson-exe' for db-lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/db-lesson-exe/db-lesson-exe ...
db-lesson> copy/register
Installing library in /Users/…/db-lesson/.stack-work/install/x86_64-osx/ab5b3640cd39493075c57a4e40b7505b193ab716e242cc230234f0b245ae2353/9.0.2/lib/x86_64-osx-ghc-9.0.2/db-lesson-0.1.0.0-2ySc30kDbQ7mjauu4huJo
Installing executable db-lesson-exe in /Users/…/db-lesson/.stack-work/install/x86_64-osx/ab5b3640cd39493075c57a4e40b7505b193ab716e242cc230234f0b245ae2353/9.0.2/bin
Registering library for db-lesson-0.1.0.0..
% stack exec db-lesson-exe
"Enter a command"
addtool
"Enter tool name"
tool name 2
"Enter tool description"
tool description 2
"tool added"
"Enter a command"
tools
1.) hammer
 description: hits stuff
 last returned: 2017-01-01
 times borrowed: 0

2.) saw
 description: cuts stuff
 last returned: 2017-01-01
 times borrowed: 0

3.) tool name
 description: tool description
 last returned: 2022-04-07
 times borrowed: 0

4.) toll name 1
 description: tool description 1
 last returned: 2022-04-08
 times borrowed: 0

5.) tool name 2
 description: tool description 2
 last returned: 2022-04-08
 times borrowed: 0

"Enter a command"
quit
"bye!"
%