2020-07-28 19:38:30 +02:00
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
|
|
--------------------------------------------------------------------------------
|
|
|
|
module Trips where
|
|
|
|
--------------------------------------------------------------------------------
|
|
|
|
import Database.SQLite.Simple
|
2020-07-28 19:46:05 +02:00
|
|
|
import Utils
|
2020-07-28 19:38:30 +02:00
|
|
|
|
|
|
|
import qualified Types as T
|
|
|
|
--------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
-- | Create a new `trip` in `dbFile`.
|
|
|
|
create :: FilePath -> T.Trip -> IO ()
|
|
|
|
create dbFile trip = withConnection dbFile $ \conn ->
|
|
|
|
execute conn "INSERT INTO Trips (username,destination,startDate,endDate,comment) VALUES (?,?,?,?,?)"
|
2020-07-28 19:46:05 +02:00
|
|
|
(trip |> T.tripFields)
|
2020-07-28 19:38:30 +02:00
|
|
|
|
|
|
|
-- | Delete a trip from `dbFile` using its `tripPK` Primary Key.
|
|
|
|
delete :: FilePath -> T.TripPK -> IO ()
|
|
|
|
delete dbFile tripPK =
|
|
|
|
withConnection dbFile $ \conn -> do
|
|
|
|
execute conn "DELETE FROM Trips WHERE username = ? AND destination = ? and startDate = ?"
|
2020-07-28 19:46:05 +02:00
|
|
|
(tripPK |> T.tripPKFields)
|
2020-07-28 19:38:30 +02:00
|
|
|
|
|
|
|
-- | Return a list of all of the trips in `dbFile`.
|
|
|
|
list :: FilePath -> IO [T.Trip]
|
|
|
|
list dbFile = withConnection dbFile $ \conn ->
|
Prefer SELECT (a,b,c) to SELECT *
"SELECT *" in SQL may not guarantee the order in which a record's columns are
returned. For example, in my FromRow instances for Account, I make successive call
The following scenario silently and erroneously assigns:
firstName, lastName = lastName, firstName
```sql
CREATE TABLE People (
firstName TEXT NOT NULL,
lastName TEXT NOT NULL,
age INTEGER NOT NULL,
PRIMARY KEY (firstName, lastName)
)
```
```haskell
data Person = Person { firstName :: String, lastName :: String, age :: Integer }
fromRow = do
firstName <- field
lastName <- field
age <- field
pure Person{..}
getPeople :: Connection -> IO [Person]
getPeople conn = query conn "SELECT * FROM People"
```
This silently fails because both firstName and lastName are Strings, and so the
FromRow Person instance type-checks, but you should expect to receive a list of
names like "Wallace William" instead of "William Wallace".
The following won't break the type-checker, but will result in a runtime parsing
error:
```haskell
-- all code from the previous example remains the same except for:
fromRow = do
age <- field
firstName <- field
lastName <- field
```
The "SELECT *" will return records like (firstName,lastName,age), but the
FromRow instance for Person will attempt to parse firstName as
Integer.
So... what have we learned? Prefer "SELECT (firstName,lastName,age)" instead of
"SELECT *".
2020-07-30 19:52:45 +02:00
|
|
|
query_ conn "SELECT (username,destination,startDate,endDate,comment) FROM Trips"
|