2023-03-16 14:54:10 +00:00
|
|
|
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
|
|
|
|
module Lib
|
|
|
|
( seedData
|
|
|
|
) where
|
|
|
|
import Data.Aeson
|
|
|
|
import Data.Text
|
2023-04-11 15:07:11 +00:00
|
|
|
|
2023-03-16 14:54:10 +00:00
|
|
|
import qualified Data.ByteString.Lazy as B
|
2023-04-11 15:07:11 +00:00
|
|
|
|
2023-03-16 14:54:10 +00:00
|
|
|
import Database.SQLite.Simple
|
|
|
|
|
|
|
|
import Config
|
|
|
|
|
|
|
|
import GHC.Generics
|
2023-04-11 15:07:11 +00:00
|
|
|
data ImageUris = ImageUris {
|
|
|
|
small :: Text,
|
|
|
|
normal :: Text,
|
|
|
|
large :: Text,
|
|
|
|
png :: Text,
|
|
|
|
art_crop :: Text,
|
|
|
|
border_crop :: Text
|
|
|
|
}deriving (Show,Generic)
|
|
|
|
instance FromJSON ImageUris
|
|
|
|
instance ToJSON ImageUris
|
2023-03-16 14:54:10 +00:00
|
|
|
|
|
|
|
data Card = Card{
|
|
|
|
object :: Text,
|
|
|
|
id :: Text,
|
|
|
|
lang :: Text,
|
|
|
|
name :: Text,
|
2023-04-11 15:07:11 +00:00
|
|
|
oracle_text :: Maybe Text,
|
|
|
|
image_uris :: Maybe ImageUris
|
2023-03-16 14:54:10 +00:00
|
|
|
} deriving (Show,Generic)
|
|
|
|
|
|
|
|
instance FromJSON Card
|
|
|
|
instance ToJSON Card
|
|
|
|
|
|
|
|
instance ToRow Card where
|
2023-04-11 15:07:11 +00:00
|
|
|
toRow (Card object id lang name oracle_text (Just (ImageUris _ image_link _ _ _ _ ))) = toRow (id, lang, name, oracle_text, image_link)
|
|
|
|
toRow (Card object id lang name oracle_text Nothing) = toRow (id, lang, name, oracle_text, pack "Nothing")
|
2023-03-16 14:54:10 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
getJSON :: String -> IO B.ByteString
|
|
|
|
getJSON file = B.readFile file
|
|
|
|
|
|
|
|
insertCards :: Connection -> [Card] -> IO()
|
|
|
|
insertCards conn ((card):cards) = do
|
2023-04-11 15:07:11 +00:00
|
|
|
execute conn "INSERT INTO card (scryfall_id, lang, name, oracle_text, image_uri) VALUES (?,?,?,?,?)" card
|
2023-03-16 14:54:10 +00:00
|
|
|
insertCards conn cards
|
|
|
|
return ()
|
|
|
|
insertCards conn [] = return ()
|
|
|
|
|
|
|
|
seedData :: IO ()
|
|
|
|
seedData = do
|
|
|
|
-- Get JSON data and decode it
|
|
|
|
|
|
|
|
seedData <- getDataSeedPath
|
|
|
|
dbPath <- getDbPath
|
2023-04-11 15:07:11 +00:00
|
|
|
d <- (eitherDecode <$> getJSON seedData) :: IO (Either String [Card])
|
2023-03-16 14:54:10 +00:00
|
|
|
conn <- open dbPath
|
2023-04-11 15:07:11 +00:00
|
|
|
execute_ conn "CREATE TABLE IF NOT EXISTS card (id INTEGER PRIMARY KEY, scryfall_id TEXT, lang TEXT, name TEXT, oracle_text TEXT, image_uri TEXT)"
|
2023-03-16 14:54:10 +00:00
|
|
|
|
2023-04-11 14:39:44 +00:00
|
|
|
|
2023-03-16 14:54:10 +00:00
|
|
|
case d of
|
|
|
|
Left err -> putStrLn err
|
|
|
|
Right ps -> insertCards conn ps
|
|
|
|
|