計算機科学のブログ

Haskell - 実践Haskell - Haskellでのデータベースの使用 - データの追加

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

軽量マークアップ言語

db-lesson/package.yaml

name:                db-lesson
version:             0.1.0.0
github:              "githubuser/db-lesson"
license:             BSD-3-Clause
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2025 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
- time
- sqlite-simple

ghc-options:
- -Wall
- -Wcompat
- -Widentities
- -Wincomplete-record-updates
- -Wincomplete-uni-patterns
- -Wmissing-export-lists
- -Wmissing-home-modules
- -Wpartial-fields
- -Wredundant-constraints

default-extensions:
- OverloadedStrings

library:
  source-dirs: src

executables:
  db-lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - db-lesson

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

コード

db-lesson/app/Main.hs

module Main (main) where

-- import Lib
import Database.SQLite.Simple

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

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

addTool :: String -> String -> IO ()
addTool name description = do
    withConn
        "tools.db"
        (\conn ->
            execute conn
                    (mconcat ["INSERT INTO tools ",
                              "(name, description, lastReturned, timesBorrowed)",
                              "VALUES",
                              "(?, ?, ?, ?)"])
                    (name, description, "2000-01-01" :: String, 0 :: Int))
    putStrLn "tool added"

main :: IO ()
main = addTool "tool1" "desc1"

入出力結果(Terminal, Zsh)

% stack run
db-lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
db-lesson> build (lib + exe) with ghc-9.8.4
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..
[1 of 2] Compiling Main [Source file changed]
[3 of 3] Linking .stack-work/dist/aarch64-osx/ghc-9.8.4/build/db-lesson-exe/db-lesson-exe [Objects changed]
ld: warning: -U option is redundant when using -undefined dynamic_lookup
db-lesson> copy/register
Installing library in /Users//db-lesson/.stack-work/install/aarch64-osx/27e00dd04a6f7fc061662d4eebb16cc69859af4840b4ab18e626ce23aacafb60/9.8.4/lib/aarch64-osx-ghc-9.8.4/db-lesson-0.1.0.0-KdsmupJGb67J5JKrReDDyj
Installing executable db-lesson-exe in /Users//db-lesson/.stack-work/install/aarch64-osx/27e00dd04a6f7fc061662d4eebb16cc69859af4840b4ab18e626ce23aacafb60/9.8.4/bin
Registering library for db-lesson-0.1.0.0..
db-lesson-exe: SQLite3 returned ErrorError while attempting to perform prepare "INSERT INTO tools (name, description, lastReturned, timesBorrowed)VALUES(?, ?, ?, ?)": no such table: tools
%