1
0
Fork 0

[haskell] embed sql migration scripts from external files

This commit is contained in:
Julien Dessaux 2023-07-24 00:01:49 +02:00
parent d1f0faf30f
commit 565afa5c7b
Signed by: adyxax
GPG key ID: F92E51B86E07177E
3 changed files with 34 additions and 30 deletions

View file

@ -20,10 +20,10 @@ dependencies:
- base >= 4.7 && < 5
- bytestring
- directory
- file-embed
- http-conduit
- http-types
- mtl
- raw-strings-qq
- sqlite-simple
- text
- time

View file

@ -1,5 +1,6 @@
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
module SpaceTraders.Database
( close
@ -7,36 +8,14 @@ module SpaceTraders.Database
) where
import Control.Exception
import qualified Data.ByteString as B
import Data.FileEmbed
import qualified Database.SQLite.Simple as S
import Text.RawString.QQ
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
migrations :: [S.Query]
migrations = [
[r|CREATE TABLE schema_version (
version INTEGER NOT NULL
);|],
[r|CREATE TABLE tokens (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);|],
[r|CREATE TABLE agents (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);|],
[r|CREATE TABLE contracts (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);|],
[r|CREATE TABLE ships (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);|],
[r|CREATE UNIQUE INDEX ships_data_symbol ON ships (json_extract(data, '$.symbol'));|],
[r|CREATE TABLE systems (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);|],
[r|CREATE UNIQUE INDEX systems_data_symbol ON systems (json_extract(data, '$.symbol'));|]]
migrations :: [B.ByteString]
migrations = [ $(embedFile "src/SpaceTraders/Database/000_init.sql") ]
close :: S.Connection -> IO ()
close conn = S.close conn
@ -48,7 +27,7 @@ open = do
S.execute_ conn "PRAGMA journal_mode = WAL;"
S.withTransaction conn $ do
version <- getSchemaVersion conn `catch` defaultVersion
mapM_ (S.execute_ conn) $ drop version migrations
mapM_ (S.execute_ conn) $ S.Query <$> (filter (/= "\n") . concat . map ((T.splitOn ";") . T.decodeUtf8) $ drop version migrations)
S.execute_ conn "DELETE FROM schema_version;"
S.execute conn "INSERT INTO schema_version (version) VALUES (?);" (S.Only $ length migrations)
return conn

View file

@ -0,0 +1,25 @@
CREATE TABLE schema_version (
version INTEGER NOT NULL
);
CREATE TABLE tokens (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);
CREATE TABLE agents (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);
CREATE TABLE contracts (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);
CREATE TABLE ships (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);
CREATE UNIQUE INDEX ships_data_symbol ON ships (json_extract(data, '$.symbol'));
CREATE TABLE systems (
id INTEGER PRIMARY KEY,
data TEXT NOT NULL
);
CREATE UNIQUE INDEX systems_data_symbol ON systems (json_extract(data, '$.symbol'));