Initial commit

This commit is contained in:
Miguel de la Cruz 2021-09-11 20:50:34 +02:00
commit 48b34bca9d
102 changed files with 278172 additions and 0 deletions

71
services/store/store.go Normal file
View file

@ -0,0 +1,71 @@
package store
import (
"database/sql"
"fmt"
"strings"
_ "github.com/mattn/go-sqlite3"
)
type Store struct {
Path string
Conn *sql.DB
}
func addPathOptions(path string) string {
if !strings.HasPrefix(path, ":memory:") {
path = "file:" + path
}
return fmt.Sprintf("%s?_foreign_keys=true", path)
}
func NewStore(path string) (*Store, error) {
s := &Store{Path: path}
conn, err := sql.Open("sqlite3", addPathOptions(path))
if err != nil {
return nil, err
}
if err := s.EnsureSchema(); err != nil {
return nil, err
}
s.Conn = conn
return s, nil
}
func (s *Store) Close() error {
return s.Conn.Close()
}
func (s *Store) EnsureSchema() error {
schema := `
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(255) NOT NULL,
mail VARCHAR(255) UNIQUE NOT NULL,
username VARCHAR(255) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS game (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
name VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS gamemember (
game_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
role VARCHAR(255) NOT NULL,
PRIMARY KEY (game_id, user_id)
);
`
_, err := s.Conn.Exec(schema)
return err
}

View file

@ -0,0 +1,32 @@
package store
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestAddPathOptions(t *testing.T) {
testCases := []struct {
Name string
Path string
Expected string
}{
{
Name: "Path is memory",
Path: ":memory:",
Expected: ":memory:?_foreign_keys=true",
},
{
Name: "Path is a file path",
Path: "./some_file.sqlite",
Expected: "file:./some_file.sqlite?_foreign_keys=true",
},
}
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
require.Equal(t, tc.Expected, addPathOptions(tc.Path))
})
}
}